Skip to main content

datafusion_expr/
higher_order_function.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//! [`HigherOrderUDF`]: User Defined Higher Order Functions
6
7use crate::expr::{
8    HigherOrderFunction, display_comma_separated,
9    schema_name_from_exprs_comma_separated_without_space,
10};
11use crate::type_coercion::functions::value_fields_with_higher_order_udf;
12use crate::udf_eq::UdfEq;
13use crate::{ColumnarValue, Documentation, Expr, ExprSchemable};
14use arrow::array::{ArrayRef, RecordBatch, RecordBatchOptions};
15use arrow::datatypes::{DataType, FieldRef, Schema};
16use arrow_schema::SchemaRef;
17use datafusion_common::config::ConfigOptions;
18use datafusion_common::datatype::FieldExt;
19use datafusion_common::hash_map::EntryRef;
20use datafusion_common::tree_node::{
21    Transformed, TreeNode, TreeNodeContainer, TreeNodeRecursion,
22};
23use datafusion_common::{
24    DFSchema, HashMap, HashSet, Result, ScalarValue, exec_err, internal_datafusion_err,
25    internal_err, not_impl_err, plan_datafusion_err, plan_err,
26};
27use datafusion_expr_common::dyn_eq::{DynEq, DynHash};
28use datafusion_expr_common::signature::Volatility;
29use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
30use std::any::Any;
31use std::cmp::Ordering;
32use std::fmt::Debug;
33use std::hash::{Hash, Hasher};
34use std::mem;
35use std::sync::Arc;
36
37/// The types of arguments for which a function has implementations.
38///
39/// [`HigherOrderTypeSignature`] **DOES NOT** define the types that a user query could call the
40/// function with. DataFusion will automatically coerce (cast) argument types to
41/// one of the supported function signatures, if possible.
42///
43/// # Overview
44/// Functions typically provide implementations for a small number of different
45/// argument [`DataType`]s, rather than all possible combinations. If a user
46/// calls a function with arguments that do not match any of the declared types,
47/// DataFusion will attempt to automatically coerce (add casts to) function
48/// arguments so they match the [`HigherOrderTypeSignature`]. See the [`type_coercion`] module
49/// for more details
50///
51/// [`type_coercion`]: crate::type_coercion
52#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
53pub enum HigherOrderTypeSignature {
54    /// The acceptable signature and coercions rules are special for this
55    /// function.
56    ///
57    /// If this signature is specified,
58    /// DataFusion will call [`HigherOrderUDFImpl::coerce_value_types`] to prepare argument types.
59    UserDefined,
60    /// One or more lambdas or arguments with arbitrary types
61    VariadicAny,
62    /// The specified number of lambdas or arguments with arbitrary types.
63    Any(usize),
64    /// Exactly the specified arguments in the given order, with arbitrary types.
65    /// DataFusion will call [`HigherOrderUDFImpl::coerce_value_types`] to prepare the value
66    /// argument types.
67    Exact(Vec<ValueOrLambda<(), ()>>),
68}
69
70/// Provides information necessary for calling a higher order function.
71///
72/// - [`HigherOrderTypeSignature`] defines the argument types that a function has implementations
73///   for.
74///
75/// - [`Volatility`] defines how the output of the function changes with the input.
76#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
77pub struct HigherOrderSignature {
78    /// The data types that the function accepts. See [HigherOrderTypeSignature] for more information.
79    pub type_signature: HigherOrderTypeSignature,
80    /// The volatility of the function. See [Volatility] for more information.
81    pub volatility: Volatility,
82    /// The max number of times to call [HigherOrderUDFImpl::lambda_parameters] before raising an error.
83    /// Used to guard against implementations that causes an infinite loop by endlessly returning
84    /// [LambdaParametersProgress::Partial]. Defaults to 256
85    pub lambda_parameters_max_iterations: usize,
86}
87
88const LAMBDA_PARAMETERS_MAX_ITERATIONS: usize = 256;
89
90impl HigherOrderSignature {
91    /// Creates a new `HigherOrderSignature` from a given type signature and volatility.
92    pub fn new(type_signature: HigherOrderTypeSignature, volatility: Volatility) -> Self {
93        HigherOrderSignature {
94            type_signature,
95            volatility,
96            lambda_parameters_max_iterations: LAMBDA_PARAMETERS_MAX_ITERATIONS,
97        }
98    }
99
100    /// User-defined coercion rules for the function.
101    pub fn user_defined(volatility: Volatility) -> Self {
102        Self {
103            type_signature: HigherOrderTypeSignature::UserDefined,
104            volatility,
105            lambda_parameters_max_iterations: LAMBDA_PARAMETERS_MAX_ITERATIONS,
106        }
107    }
108
109    /// An arbitrary number of lambdas or arguments of any type.
110    pub fn variadic_any(volatility: Volatility) -> Self {
111        Self {
112            type_signature: HigherOrderTypeSignature::VariadicAny,
113            volatility,
114            lambda_parameters_max_iterations: LAMBDA_PARAMETERS_MAX_ITERATIONS,
115        }
116    }
117
118    /// A specified number of arguments of any type
119    pub fn any(arg_count: usize, volatility: Volatility) -> Self {
120        Self {
121            type_signature: HigherOrderTypeSignature::Any(arg_count),
122            volatility,
123            lambda_parameters_max_iterations: LAMBDA_PARAMETERS_MAX_ITERATIONS,
124        }
125    }
126
127    /// Exactly the specified arguments in the given order, with arbitrary types.
128    /// DataFusion will call [`HigherOrderUDFImpl::coerce_value_types`] to prepare the value
129    /// argument types.
130    ///
131    /// # Example
132    /// A function that takes one value argument followed by one lambda:
133    /// ```
134    /// # use datafusion_expr::{HigherOrderSignature, ValueOrLambda, Volatility};
135    /// let sig = HigherOrderSignature::exact(
136    ///     vec![ValueOrLambda::Value(()), ValueOrLambda::Lambda(())],
137    ///     Volatility::Immutable,
138    /// );
139    /// ```
140    pub fn exact(args: Vec<ValueOrLambda<(), ()>>, volatility: Volatility) -> Self {
141        Self {
142            type_signature: HigherOrderTypeSignature::Exact(args),
143            volatility,
144            lambda_parameters_max_iterations: LAMBDA_PARAMETERS_MAX_ITERATIONS,
145        }
146    }
147}
148
149impl PartialEq for dyn HigherOrderUDFImpl {
150    fn eq(&self, other: &Self) -> bool {
151        self.dyn_eq(other as _)
152    }
153}
154
155impl PartialOrd for dyn HigherOrderUDFImpl {
156    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
157        let mut cmp = self.name().cmp(other.name());
158        if cmp == Ordering::Equal {
159            cmp = self.signature().partial_cmp(other.signature())?;
160        }
161        if cmp == Ordering::Equal {
162            cmp = self.aliases().partial_cmp(other.aliases())?;
163        }
164        // Contract for PartialOrd and PartialEq consistency requires that
165        // a == b if and only if partial_cmp(a, b) == Some(Equal).
166        if cmp == Ordering::Equal && self != other {
167            // Functions may have other properties besides name and signature
168            // that differentiate two instances (e.g. type, or arbitrary parameters).
169            // We cannot return Some(Equal) in such case.
170            return None;
171        }
172        debug_assert!(
173            cmp == Ordering::Equal || self != other,
174            "Detected incorrect implementation of PartialEq when comparing functions: '{}' and '{}'. \
175            The functions compare as equal, but they are not equal based on general properties that \
176            the PartialOrd implementation observes,",
177            self.name(),
178            other.name()
179        );
180        Some(cmp)
181    }
182}
183
184impl Eq for dyn HigherOrderUDFImpl {}
185
186impl Hash for dyn HigherOrderUDFImpl {
187    fn hash<H: Hasher>(&self, state: &mut H) {
188        self.dyn_hash(state)
189    }
190}
191
192/// Arguments passed to [`HigherOrderUDFImpl::invoke_with_args`] when invoking a
193/// higher order function.
194#[derive(Debug, Clone)]
195pub struct HigherOrderFunctionArgs {
196    /// The evaluated arguments and lambdas to the function
197    pub args: Vec<ValueOrLambda<ColumnarValue, LambdaArgument>>,
198    /// Field associated with each arg, if it exists
199    /// For lambdas, it will be the field of the result of
200    /// the lambda if evaluated with the parameters
201    /// returned from [`HigherOrderUDFImpl::lambda_parameters`]
202    pub arg_fields: Vec<ValueOrLambda<FieldRef, FieldRef>>,
203    /// The number of rows in record batch being evaluated
204    pub number_rows: usize,
205    /// The return field of the higher order function returned
206    /// (from `return_field_from_args`) when creating the
207    /// physical expression from the logical expression
208    pub return_field: FieldRef,
209    /// The config options at execution time
210    pub config_options: Arc<ConfigOptions>,
211}
212
213impl HigherOrderFunctionArgs {
214    /// The return type of the function. See [`Self::return_field`] for more
215    /// details.
216    pub fn return_type(&self) -> &DataType {
217        self.return_field.data_type()
218    }
219}
220
221/// A lambda argument to a HigherOrderFunction
222#[derive(Clone, Debug)]
223pub struct LambdaArgument {
224    /// The parameters defined in this lambda
225    ///
226    /// For example, for `array_transform([2], v -> -v)`,
227    /// this will be `vec![Field::new("v", DataType::Int32, true)]`
228    params: Vec<FieldRef>,
229    /// Indices into [`Self::params`] of the parameters that are actually
230    /// referenced by [`Self::body`] (taking nested-lambda shadowing into
231    /// account), in the original declaration order of `params`.
232    ///
233    /// [`Self::evaluate`] only evaluates and pushes the closures whose
234    /// corresponding parameter index appears here, so unused declared
235    /// parameters leave no slot in the merged batch and the body's compressed
236    /// column indices line up directly with what the evaluator built.
237    ///
238    /// Callers who already have a `LambdaExpr` should pass
239    /// `LambdaExpr::used_param_indices()` directly to [`Self::new`] — both
240    /// are indices into the same positionally-aligned `params` list.
241    ///
242    /// Every index here must be `< params.len()`; see the precondition on
243    /// [`Self::new`].
244    ///
245    /// Relies on captures sorting before this lambda's own params in the
246    /// planner's (un-projected) index space, which is what makes
247    /// `captures ++ used_params` below line up with the projected body.
248    used_param_indices: Vec<usize>,
249    /// The body of the lambda
250    ///
251    /// For example, for `array_transform([2], v -> -v)`,
252    /// this will be the physical expression of `-v`
253    body: Arc<dyn PhysicalExpr>,
254    /// Cached schema built from `params`. Reused across every `evaluate` call
255    /// (and across every nested-list iteration when the lambda is called once
256    /// per outer sublist), avoiding the per-call `Schema::new` build that
257    /// includes constructing the internal name -> index map.
258    schema: SchemaRef,
259    /// A RecordBatch containing the captured columns inside this lambda body, if any
260    ///
261    /// For example, for `array_transform([2], v -> v + a + b)`,
262    /// this will be a `RecordBatch` with two columns, `a` and `b`
263    captures: Option<RecordBatch>,
264}
265
266impl LambdaArgument {
267    /// # Preconditions
268    ///
269    /// Every index in `used_param_indices` must be `< params.len()`;
270    /// violating this panics on out-of-bounds indexing below. Callers should
271    /// pass `LambdaExpr::used_param_indices()`, which always indexes into the
272    /// same `params` list, rather than constructing indices by hand.
273    pub fn new(
274        params: Vec<FieldRef>,
275        body: Arc<dyn PhysicalExpr>,
276        captures: Option<RecordBatch>,
277        used_param_indices: &[usize],
278    ) -> Self {
279        debug_assert!(
280            used_param_indices.iter().all(|i| *i < params.len()),
281            "used_param_indices contains an index out of bounds for params \
282             (len {}): {:?}",
283            params.len(),
284            used_param_indices
285        );
286
287        let used_param_indices = used_param_indices.to_vec();
288        let effective_params = used_param_indices.iter().map(|i| Arc::clone(&params[*i]));
289
290        let fields: Vec<FieldRef> = match &captures {
291            Some(batch) => batch
292                .schema_ref()
293                .fields()
294                .iter()
295                .cloned()
296                .chain(effective_params)
297                .collect(),
298            None => effective_params.collect(),
299        };
300
301        let schema = Arc::new(Schema::new(fields));
302
303        Self {
304            params,
305            used_param_indices,
306            body,
307            schema,
308            captures,
309        }
310    }
311
312    /// Evaluate this lambda
313    /// `args` should evaluate to the value of each parameter
314    /// of the correspondent lambda returned in [HigherOrderUDFImpl::lambda_parameters].
315    ///
316    /// Only the closures in `args` for parameters the lambda body actually
317    /// references are called; closures for declared-but-unused parameters
318    /// are skipped entirely. Callers should not rely on every closure in
319    /// `args` being invoked.
320    ///
321    /// `spread_captures` is responsible for transforming the captured column arrays
322    /// so they align with the evaluation batch. Captures are snapshotted from the
323    /// outer batch at construction time, giving one value per outer row, but the
324    /// function may evaluate the lambda body over a batch with a different number
325    /// of rows. It is the function's responsibility to provide the appropriate
326    /// `spread_captures` closure to expand (or otherwise reshape) the captures
327    /// to match.
328    ///
329    /// Taking as an example the following table:
330    ///
331    /// ```sql
332    /// CREATE TABLE t (arr INT[], a INT) AS VALUES
333    ///   ([1, 2, 3], 10),
334    ///   ([],        20),
335    ///   ([4],       30);
336    /// ```
337    ///
338    /// `SELECT array_transform(arr, v -> v + a) from t` would execute over three outer rows:
339    ///
340    /// ```text
341    /// arr (ListArray):  [[1, 2, 3], [], [4]]   -- 3 outer rows, 4 total elements
342    /// a   (captured):   [10,        20,  30]   -- one value per outer row
343    /// ```
344    ///
345    /// `array_transform` flattens the list elements into a single batch of 4 rows,
346    /// so `spread_captures` must repeat/drop captured values to match:
347    ///
348    /// ```text
349    /// v (flattened args): [1,  2,  3,  4]
350    /// a (spread):         [10, 10, 10, 30]  -- 10 repeated for 3 elements in row 0,
351    ///                                        -- 20 dropped for the empty sublist in row 1,
352    ///                                        -- 30 once for the single element in row 2
353    /// ```
354    ///
355    /// The lambda body `v + a` then evaluates element-wise over these 4-row arrays,
356    /// producing `[11, 12, 13, 34]`, which `array_transform` reassembles into `[[11, 12, 13], [], [34]]`.
357    ///
358    /// If the lambda has no captures, `spread_captures` is never called.
359    pub fn evaluate(
360        &self,
361        args: &[&dyn Fn() -> Result<ArrayRef>],
362        spread_captures: impl FnOnce(&[ArrayRef]) -> Result<Vec<ArrayRef>>,
363    ) -> Result<ColumnarValue> {
364        let spread_captures = self
365            .captures
366            .as_ref()
367            .map(|captures| {
368                let spread_columns = spread_captures(captures.columns())?;
369
370                RecordBatch::try_new(captures.schema(), spread_columns)
371            })
372            .transpose()?;
373
374        let merged = merge_captures_with_variables(
375            spread_captures.as_ref(),
376            Arc::clone(&self.schema),
377            &self.params,
378            &self.used_param_indices,
379            args,
380        )?;
381
382        self.body.evaluate(&merged)
383    }
384}
385
386fn merge_captures_with_variables(
387    captures: Option<&RecordBatch>,
388    schema: SchemaRef,
389    params: &[FieldRef],
390    used_param_indices: &[usize],
391    variables: &[&dyn Fn() -> Result<ArrayRef>],
392) -> Result<RecordBatch> {
393    if variables.len() < params.len() {
394        return exec_err!(
395            "expected at least {} lambda arguments to merge with captures, got {}",
396            params.len(),
397            variables.len()
398        );
399    }
400
401    let push_param_arrays = |columns: &mut Vec<ArrayRef>| -> Result<()> {
402        for &i in used_param_indices {
403            columns.push(variables[i]()?);
404        }
405        Ok(())
406    };
407
408    let columns = match captures {
409        Some(captures) => {
410            let mut columns = captures.columns().to_vec();
411            push_param_arrays(&mut columns)?;
412            columns
413        }
414        None => {
415            let mut columns = Vec::with_capacity(used_param_indices.len());
416            push_param_arrays(&mut columns)?;
417            columns
418        }
419    };
420
421    if columns.is_empty() {
422        // No columns to derive a row count from, so borrow one variable's
423        // array length instead (all variables have the same length).
424        let row_count = variables.first().ok_or_else(|| {
425            internal_datafusion_err!(
426                "merge_captures_with_variables: no variables to derive a row count from"
427            )
428        })?()?
429        .len();
430        return Ok(RecordBatch::try_new_with_options(
431            schema,
432            vec![],
433            &RecordBatchOptions::new().with_row_count(Some(row_count)),
434        )?);
435    }
436
437    Ok(RecordBatch::try_new(schema, columns)?)
438}
439
440/// Information about arguments passed to the function
441///
442/// This structure contains metadata about how the function was called
443/// such as the type of the arguments, any scalar arguments and if the
444/// arguments can (ever) be null
445///
446/// See [`HigherOrderUDFImpl::return_field_from_args`] for more information
447#[derive(Clone, Debug)]
448pub struct HigherOrderReturnFieldArgs<'a> {
449    /// The data types of the arguments to the function
450    ///
451    /// If argument `i` to the function is a lambda, it will be the field of the result of the
452    /// lambda if evaluated with the parameters returned from [`HigherOrderUDFImpl::lambda_parameters`]
453    ///
454    /// For example, with `array_transform([1], v -> v == 5)`
455    /// this field will be
456    /// ```ignore
457    /// [
458    ///     ValueOrLambda::Value(Field::new("", DataType::new_list(DataType::Int32, true), true)),
459    ///     ValueOrLambda::Lambda(Field::new("", DataType::Boolean, true))
460    /// ]
461    /// ```
462    pub arg_fields: &'a [ValueOrLambda<FieldRef, FieldRef>],
463    /// Is argument `i` to the function a scalar (constant)?
464    ///
465    /// If the argument `i` is not a scalar, it will be None
466    ///
467    /// For example, if a function is called like `array_transform([1], v -> v == 5)`
468    /// this field will be `[Some(ScalarValue::List(...), None]`
469    pub scalar_arguments: &'a [Option<&'a ScalarValue>],
470}
471
472/// An argument to a higher order function
473#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Hash)]
474pub enum ValueOrLambda<V, L> {
475    /// A value with associated data
476    Value(V),
477    /// A lambda with associated data
478    Lambda(L),
479}
480
481/// Represents a step during the resolution of the parameters of all lambdas of a given
482/// higher-order function via [HigherOrderUDFImpl::lambda_parameters]. It's valid that the
483/// fields of a given lambda changes between steps, and is up to the implementation to
484/// provide during the function evaluation the parameters that matches the fields returned
485/// at the [LambdaParametersProgress::Complete] step. See [HigherOrderUDFImpl::lambda_parameters]
486/// docs for more details
487pub enum LambdaParametersProgress {
488    /// The parameters of some lambdas are unknown due to a dependency on another lambda output field
489    /// or are placeholders due to a dependency on it's own output field. It's perfectly valid to
490    /// contain only `Some`'s and not a single `None`, representing lambdas that depends only on itself
491    /// and not on others. [HigherOrderUDFImpl::lambda_parameters] will be called again with the output
492    /// field of all lambdas with known parameters.
493    Partial(Vec<Option<Vec<FieldRef>>>),
494    /// There are no unmet dependencies and all parameters are known, [HigherOrderUDFImpl::lambda_parameters]
495    /// will not be called again
496    Complete(Vec<Vec<FieldRef>>),
497}
498
499/// Trait for implementing user defined higher order functions.
500///
501/// This trait exposes the full API for implementing user defined functions and
502/// can be used to implement any function.
503///
504/// New higher order functions typically implement this trait and are then
505/// wrapped in a [`HigherOrderUDF`] for registration with DataFusion.
506///
507/// See [`array_transform.rs`] for a commented complete implementation
508///
509/// [`array_transform.rs`]: https://github.com/apache/datafusion/blob/main/datafusion/functions-nested/src/array_transform.rs
510pub trait HigherOrderUDFImpl: Debug + DynEq + DynHash + Send + Sync + Any {
511    /// Returns this function's name
512    fn name(&self) -> &str;
513
514    /// Returns any aliases (alternate names) for this function.
515    ///
516    /// Aliases can be used to invoke the same function using different names.
517    /// For example in some databases `now()` and `current_timestamp()` are
518    /// aliases for the same function. This behavior can be obtained by
519    /// returning `current_timestamp` as an alias for the `now` function.
520    ///
521    /// Note: `aliases` should only include names other than [`Self::name`].
522    /// Defaults to `[]` (no aliases)
523    fn aliases(&self) -> &[String] {
524        &[]
525    }
526
527    /// Returns the name of the column this expression would create
528    ///
529    /// See [`Expr::schema_name`] for details
530    fn schema_name(&self, args: &[Expr]) -> Result<String> {
531        Ok(format!(
532            "{}({})",
533            self.name(),
534            schema_name_from_exprs_comma_separated_without_space(args)?
535        ))
536    }
537
538    /// Returns a [`HigherOrderSignature`] describing the argument types for which this
539    /// function has an implementation, and the function's [`Volatility`].
540    ///
541    /// See [`HigherOrderSignature`] for more details on argument type handling
542    /// and [`Self::return_field_from_args`] for computing the return type.
543    ///
544    /// [`Volatility`]: datafusion_expr_common::signature::Volatility
545    fn signature(&self) -> &HigherOrderSignature;
546
547    /// Return the field of all the parameters supported by the lambdas in `fields`.
548    /// If a lambda support multiple parameters, all should be returned, regardless of
549    /// whether they are used or not on a particular invocation
550    ///
551    /// Tip: If you have a [`HigherOrderFunction`] invocation, you can call the helper
552    /// [`HigherOrderFunction::lambda_parameters`] instead of this method directly
553    ///
554    /// The name of the returned fields are ignored.
555    ///
556    /// This function is repeatedelly called until [LambdaParametersProgress::Complete] is returned, with
557    /// `step` increased by one at each invocation, starting at 0.
558    ///
559    /// For functions which all lambda parameters depend only on the field of it's value arguments,
560    /// this can return [LambdaParametersProgress::Complete] at step 0. Taking as an example a strict
561    /// array_reduce with the signature `(arr: [V], initial_value: I, (I, V) -> I, (I) -> O) -> O`, which
562    /// requires it's initial value to be the exact same type of it's merge output, which is also the
563    /// parameter of it's finish lambda, the expression
564    ///
565    /// `array_reduce([1.2, 2.1], 0.0, (acc, v) -> acc + v + 1.5, v -> v > 5.1)`
566    ///
567    ///  would result in this function being called as the following:
568    ///
569    /// ```ignore
570    /// let lambda_parameters = array_reduce.lambda_parameters(
571    ///     0,
572    ///     &[
573    ///         // the Field of the literal `[1.2, 2.1]`, the array being reduced
574    ///         ValueOrLambda::Value(Arc::new(Field::new("", DataType::new_list(DataType::Float32, true), true))),
575    ///         // the Field of the literal `0.0`, the initial value
576    ///         ValueOrLambda::Value(Arc::new(Field::new("", DataType::Float32, true))),
577    ///         // the Field of the output of the merge lambda, which is unknown at this point because it depends
578    ///         // on the return of this call
579    ///         ValueOrLambda::Lambda(None),
580    ///         // the Field of the output of the finish lambda, unknown for the same reason as above
581    ///         ValueOrLambda::Lambda(None),
582    /// ])?;
583    ///
584    /// assert_eq!(
585    ///      lambda_parameters,
586    ///      LambdaParametersProgress::Complete(vec![
587    ///         // the finish lambda supported parameters, regardless of how many are actually used
588    ///         vec![
589    ///             // the accumulator which is the field of the initial value
590    ///             Arc::new(Field::new("ignored_name", DataType::Float32, true)),
591    ///             // the array values being reduced
592    ///             Arc::new(Field::new("", DataType::Float32, true)),
593    ///         ],
594    ///         // the merge lambda supported parameters
595    ///         vec![
596    ///             // the reduced value which is the field of the initial value
597    ///             Arc::new(Field::new("ignored_name", DataType::Float32, true)),
598    ///         ],
599    ///      ])
600    /// );
601    /// ```
602    ///
603    /// For functions which lambda parameters depends on the output of other lambdas, or on their own lambda,
604    /// this can return [LambdaParametersProgress::Partial] until all dependencies are met. Note that for
605    /// lambda with cyclic dependencies, you likely want to use [HigherOrderUDFImpl::coerce_values_for_lambdas] too.
606    /// Take as an example a flexible array_reduce with the signature `(arr: [V], initial_value: I, (ACC, V) -> ACC, (ACC) -> O) -> O`.
607    /// It has a cyclic dependency in the merge lambda, and a dependency of the finish lambda in the merge lambda,
608    /// and only requires the initial value to be *coercible* to the output of the merge lambda, which is defined by
609    /// it's [HigherOrderUDFImpl::coerce_values_for_lambdas] implementation. The expression
610    ///
611    /// `array_reduce([1.2, 2.1], 0, (acc, v) -> acc + v + 1.5, v -> v > 5.1)`
612    ///
613    /// would result in this function being called as the following:
614    ///
615    /// ```ignore
616    /// let lambda_parameters = array_reduce.lambda_parameters(
617    ///     0,
618    ///     &[
619    ///         // the Field of the literal `[1.2, 2.1]`, the array being reduced
620    ///         ValueOrLambda::Value(Arc::new(Field::new("", DataType::new_list(DataType::Float32, true), true))),
621    ///         // the Field of the literal `0`, the initial value
622    ///         ValueOrLambda::Value(Arc::new(Field::new("", DataType::Int32, true))),
623    ///         // the Field of the output of the merge lambda, which is unknown at this point because it depends on
624    ///         // the return this call
625    ///         ValueOrLambda::Lambda(None),
626    ///         // the Field of the output of the finish lambda, unknown for the same reason as above
627    ///         ValueOrLambda::Lambda(None),
628    /// ])?;
629    ///
630    /// assert_eq!(
631    ///      lambda_parameters,
632    ///      LambdaParametersProgress::Partial(vec![
633    ///         // the finish lambda supported parameters, regardless of how many are actually used
634    ///         Some(vec![
635    ///             // at step 0, use the field of the initial value
636    ///             Arc::new(Field::new("ignored_name", DataType::Int32, true)),
637    ///             // the array values being reduced
638    ///             Arc::new(Field::new("", DataType::Float32, true)),
639    ///         ]),
640    ///         // the merge lambda supported parameters, unknown at this point due to dependency on the merge output
641    ///         None,
642    ///      ])
643    /// );
644    ///
645    /// let lambda_parameters = array_reduce.lambda_parameters(
646    ///     1,
647    ///     &[
648    ///         // the Field of the literal `[1.2, 2.1]`, the array being reduced
649    ///         ValueOrLambda::Value(Arc::new(Field::new("", DataType::new_list(DataType::Float32, true), true))),
650    ///         // the Field of the literal `0`, the initial value
651    ///         ValueOrLambda::Value(Arc::new(Field::new("", DataType::Int32, true))),
652    ///         // the Field of the output of the merge lambda, which could be inferred to be a Float32 based on the
653    ///         // returned values of the previous step
654    ///         ValueOrLambda::Value(Arc::new(Field::new("", DataType::Float32, true))),
655    ///         // the Field of the output of the finish lambda, which is unknown at this point because it depends
656    ///         // on the return of this call
657    ///         ValueOrLambda::Lambda(None),
658    /// ])?;
659    ///
660    /// assert_eq!(
661    ///      lambda_parameters,
662    ///      LambdaParametersProgress::Complete(vec![
663    ///         // the finish lambda supported parameters, regardless of how many are actually used
664    ///         vec![
665    ///             // the finish lambda own output now used as it's accumulator
666    ///             Arc::new(Field::new("ignored_name", DataType::Float32, true)),
667    ///             // the array values being reduced
668    ///             Arc::new(Field::new("", DataType::Float32, true)),
669    ///         ],
670    ///         // the merge lambda supported parameters, which is the output of the merge lambda,
671    ///         vec![
672    ///             // the output of the merge lambda
673    ///             Arc::new(Field::new("", DataType::Float32, true)),
674    ///         ],
675    ///      ])
676    /// );
677    ///
678    /// let coerce_to = array_reduce.coerce_values_for_lambdas(&[
679    ///     // the literal `[1.2, 2.1]` data type, the array being reduced
680    ///     ValueOrLambda::Value(DataType::new_list(DataType::Float32, true)),
681    ///     // the literal `0` data type, the initial value
682    ///     ValueOrLambda::Value(DataType::Int32),
683    ///     // the output data type of the merge lambda
684    ///     ValueOrLambda::Lambda(DataType::Float32),
685    ///     // the output data type of the finish lambda
686    ///     ValueOrLambda::Lambda(DataType::Boolean),
687    /// ])?;
688    ///
689    /// assert_eq!(
690    ///     coerce_to,
691    ///     Some(vec![
692    ///         // return the same type for the array being reduced
693    ///         DataType::new_list(DataType::Float32, true),
694    ///         // coerce the initial value to the output of the merge lambda
695    ///         DataType::Float32,
696    ///     ])
697    /// );
698    ///
699    /// ```
700    ///
701    /// Note this may also be called at step 0 with all lambda outputs already set, and in that case,
702    /// [LambdaParametersProgress::Complete] must be returned
703    ///
704    /// The implementation can assume that some other part of the code has coerced
705    /// the actual argument types to match [`Self::signature`], except the coercion defined by
706    /// [Self::coerce_values_for_lambdas].
707    ///
708    /// [`HigherOrderFunction`]: crate::expr::HigherOrderFunction
709    /// [`HigherOrderFunction::lambda_parameters`]: crate::expr::HigherOrderFunction::lambda_parameters
710    fn lambda_parameters(
711        &self,
712        step: usize,
713        fields: &[ValueOrLambda<FieldRef, Option<FieldRef>>],
714    ) -> Result<LambdaParametersProgress>;
715
716    /// Coerce value arguments of a function call to types that the function can evaluate also taking into
717    /// account the *output type of it's lambdas*. This differs from [HigherOrderUDFImpl::coerce_value_types]
718    /// that only has access to the type of it's value arguments because it's called before the output type
719    /// of lambdas are known.
720    ///
721    /// See the [type coercion module](crate::type_coercion)
722    /// documentation for more details on type coercion
723    ///
724    /// # Parameters
725    /// * `fields`: The argument types of the value arguments of this function, or the output type of lambdas
726    ///
727    /// # Return value
728    /// If `Some`, contains a Vec with the same number of [ValueOrLambda::Value] in `fields`.
729    /// DataFusion will `CAST` the function call arguments to these specific types. If `None`, no
730    /// coercion will be applied beyond the one defined by the function signature.
731    ///
732    /// For example, a flexible array_reduce implementation (see [Self::lambda_parameters] docs), when working
733    /// with the expression below, may want to coerce it's initial value argument, the *integer* `0`,
734    /// to match the output of it's merge function, which is a *float*:
735    ///
736    /// `array_reduce([1.2, 2.1], 0, (acc, v) -> acc + v + 1.5, v -> v > 2.0)`
737    fn coerce_values_for_lambdas(
738        &self,
739        _fields: &[ValueOrLambda<DataType, DataType>],
740    ) -> Result<Option<Vec<DataType>>> {
741        Ok(None)
742    }
743
744    /// What type will be returned by this function, given the arguments?
745    ///
746    /// The implementation can assume that some other part of the code has coerced
747    /// the actual argument types to match [`Self::signature`], including the coercion
748    /// defined by [Self::coerce_values_for_lambdas].
749    ///
750    /// # Example creating `Field`
751    ///
752    /// Note the name of the `Field` is ignored, except for structured types such as
753    /// `DataType::Struct`.
754    ///
755    /// ```rust
756    /// # use std::sync::Arc;
757    /// # use arrow::datatypes::{DataType, Field, FieldRef};
758    /// # use datafusion_common::Result;
759    /// # use datafusion_expr::HigherOrderReturnFieldArgs;
760    /// # struct Example{}
761    /// # impl Example {
762    /// fn return_field_from_args(&self, args: HigherOrderReturnFieldArgs) -> Result<FieldRef> {
763    ///     let field = Arc::new(Field::new("ignored_name", DataType::Int32, true));
764    ///     Ok(field)
765    /// }
766    /// # }
767    /// ```
768    fn return_field_from_args(
769        &self,
770        args: HigherOrderReturnFieldArgs,
771    ) -> Result<FieldRef>;
772
773    /// Whether List or LargeList arguments should have it's non-empty null
774    /// sublists cleaned with [remove_list_null_values] before invoking this function
775    ///
776    /// The default implementation always returns true and should only be implemented
777    /// if you want to handle non-empty null sublists yourself
778    ///
779    /// [remove_list_null_values]: datafusion_common::utils::remove_list_null_values
780    // todo: extend this to listview and maps when remove_list_null_values supports it
781    fn clear_null_values(&self) -> bool {
782        true
783    }
784
785    /// Invoke the function returning the appropriate result.
786    ///
787    /// # Performance
788    ///
789    /// For the best performance, the implementations should handle the common case
790    /// when one or more of their arguments are constant values (aka
791    /// [`ColumnarValue::Scalar`]).
792    ///
793    /// [`ColumnarValue::values_to_arrays`] can be used to convert the arguments
794    /// to arrays, which will likely be simpler code, but be slower.
795    fn invoke_with_args(&self, args: HigherOrderFunctionArgs) -> Result<ColumnarValue>;
796
797    /// Returns true if some of this `exprs` subexpressions may not be evaluated
798    /// and thus any side effects (like divide by zero) may not be encountered.
799    ///
800    /// Setting this to true prevents certain optimizations such as common
801    /// subexpression elimination
802    ///
803    /// When overriding this function to return `true`, [HigherOrderUDFImpl::conditional_arguments] can also be
804    /// overridden to report more accurately which arguments are eagerly evaluated and which ones
805    /// lazily.
806    fn short_circuits(&self) -> bool {
807        false
808    }
809
810    /// Determines which of the arguments passed to *this higher-order function*
811    /// are evaluated eagerly and which may be evaluated lazily. Note that this
812    /// does *not* applies to the arguments that *lambda functions* pass to it's
813    /// body expression
814    ///
815    /// If this function returns `None`, all arguments are eagerly evaluated.
816    /// Returning `None` is a micro optimization that saves a needless `Vec`
817    /// allocation.
818    ///
819    /// If the function returns `Some`, returns (`eager`, `lazy`) where `eager`
820    /// are the arguments that are always evaluated, and `lazy` are the
821    /// arguments that may be evaluated lazily (i.e. may not be evaluated at all
822    /// in some cases).
823    ///
824    /// Implementations must ensure that the two returned `Vec`s are disjunct,
825    /// and that each argument from `args` is present in one the two `Vec`s.
826    ///
827    /// When overriding this function, [HigherOrderUDFImpl::short_circuits] must
828    /// be overridden to return `true`.
829    fn conditional_arguments<'a>(
830        &self,
831        args: &'a [Expr],
832    ) -> Option<(Vec<&'a Expr>, Vec<&'a Expr>)> {
833        if self.short_circuits() {
834            Some((vec![], args.iter().collect()))
835        } else {
836            None
837        }
838    }
839
840    /// Coerce value arguments of a function call to types that the function can evaluate.
841    /// Note that if you need to coerce values based on the output type of lambdas, you
842    /// must use [HigherOrderUDFImpl::coerce_values_for_lambdas], as this function is used before
843    /// the output type of lambdas are known
844    ///
845    /// See the [type coercion module](crate::type_coercion)
846    /// documentation for more details on type coercion
847    ///
848    /// For example, if your function requires a contiguous list argument, but the user calls
849    /// it like `my_func(c, v -> v+2)` (i.e. with `c` as a ListView), coerce_types can return `[DataType::List(..)]`
850    /// to ensure the argument is converted to a List
851    ///
852    /// # Parameters
853    /// * `arg_types`: The argument types of the value arguments of this function, excluding lambdas
854    ///
855    /// # Return value
856    /// A Vec the same length as `arg_types`. DataFusion will `CAST` the function call
857    /// arguments to these specific types.
858    fn coerce_value_types(&self, _arg_types: &[DataType]) -> Result<Vec<DataType>> {
859        not_impl_err!(
860            "Function {} does not implement coerce_value_types",
861            self.name()
862        )
863    }
864
865    /// Returns the documentation for this function.
866    ///
867    /// Documentation can be accessed programmatically as well as generating
868    /// publicly facing documentation.
869    fn documentation(&self) -> Option<&Documentation> {
870        None
871    }
872}
873
874/// Logical representation of a Higher Order User Defined Function.
875///
876/// A higher order function takes one or more lambda arguments in addition to
877/// regular value arguments. This struct contains the information DataFusion
878/// needs to plan and invoke functions you supply such as name, type signature,
879/// return type, and actual implementation.
880#[derive(Debug, Clone)]
881pub struct HigherOrderUDF {
882    inner: Arc<dyn HigherOrderUDFImpl>,
883}
884
885impl PartialEq for HigherOrderUDF {
886    fn eq(&self, other: &Self) -> bool {
887        self.inner.as_ref().dyn_eq(other.inner.as_ref())
888    }
889}
890
891impl PartialOrd for HigherOrderUDF {
892    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
893        let mut cmp = self.name().cmp(other.name());
894        if cmp == Ordering::Equal {
895            cmp = self.signature().partial_cmp(other.signature())?;
896        }
897        if cmp == Ordering::Equal {
898            cmp = self.aliases().partial_cmp(other.aliases())?;
899        }
900        // Contract for PartialOrd and PartialEq consistency requires that
901        // a == b if and only if partial_cmp(a, b) == Some(Equal).
902        if cmp == Ordering::Equal && self != other {
903            // Functions may have other properties besides name and signature
904            // that differentiate two instances (e.g. type, or arbitrary parameters).
905            // We cannot return Some(Equal) in such case.
906            return None;
907        }
908        debug_assert!(
909            cmp == Ordering::Equal || self != other,
910            "Detected incorrect implementation of PartialEq when comparing functions: '{}' and '{}'. \
911            The functions compare as equal, but they are not equal based on general properties that \
912            the PartialOrd implementation observes,",
913            self.name(),
914            other.name()
915        );
916        Some(cmp)
917    }
918}
919
920impl Eq for HigherOrderUDF {}
921
922impl Hash for HigherOrderUDF {
923    fn hash<H: Hasher>(&self, state: &mut H) {
924        self.inner.dyn_hash(state)
925    }
926}
927
928impl HigherOrderUDF {
929    /// Create a new `HigherOrderUDF` from a [`HigherOrderUDFImpl`] trait object.
930    ///
931    /// Note this is the same as using the `From` impl (`HigherOrderUDF::from`).
932    pub fn new_from_impl<F>(fun: F) -> HigherOrderUDF
933    where
934        F: HigherOrderUDFImpl + 'static,
935    {
936        Self::new_from_shared_impl(Arc::new(fun))
937    }
938
939    /// Create a new `HigherOrderUDF` from a shared [`HigherOrderUDFImpl`] trait object.
940    pub fn new_from_shared_impl(fun: Arc<dyn HigherOrderUDFImpl>) -> HigherOrderUDF {
941        Self { inner: fun }
942    }
943
944    /// Return the underlying [`HigherOrderUDFImpl`] trait object for this function.
945    pub fn inner(&self) -> &Arc<dyn HigherOrderUDFImpl> {
946        &self.inner
947    }
948
949    /// Adds additional names that can be used to invoke this function, in
950    /// addition to `name`.
951    ///
952    /// If you implement [`HigherOrderUDFImpl`] directly you should return aliases
953    /// directly.
954    pub fn with_aliases(self, aliases: impl IntoIterator<Item = &'static str>) -> Self {
955        Self::new_from_impl(AliasedHigherOrderUDFImpl::new(
956            Arc::clone(&self.inner),
957            aliases,
958        ))
959    }
960
961    /// Returns this function's name.
962    ///
963    /// See [`HigherOrderUDFImpl::name`] for more details.
964    pub fn name(&self) -> &str {
965        self.inner.name()
966    }
967
968    /// Returns the aliases for this function.
969    ///
970    /// See [`HigherOrderUDF::with_aliases`] for more details.
971    pub fn aliases(&self) -> &[String] {
972        self.inner.aliases()
973    }
974
975    /// Returns this function's schema_name.
976    ///
977    /// See [`HigherOrderUDFImpl::schema_name`] for more details.
978    pub fn schema_name(&self, args: &[Expr]) -> Result<String> {
979        self.inner.schema_name(args)
980    }
981
982    /// Returns this function's [`HigherOrderSignature`].
983    pub fn signature(&self) -> &HigherOrderSignature {
984        self.inner.signature()
985    }
986
987    /// Returns the parameters of all lambdas of this function for the current step.
988    ///
989    /// See [`HigherOrderUDFImpl::lambda_parameters`] for more details.
990    pub fn lambda_parameters(
991        &self,
992        step: usize,
993        fields: &[ValueOrLambda<FieldRef, Option<FieldRef>>],
994    ) -> Result<LambdaParametersProgress> {
995        self.inner.lambda_parameters(step, fields)
996    }
997
998    /// Coerce value arguments based on lambda output types.
999    ///
1000    /// See [`HigherOrderUDFImpl::coerce_values_for_lambdas`] for more details.
1001    pub fn coerce_values_for_lambdas(
1002        &self,
1003        fields: &[ValueOrLambda<DataType, DataType>],
1004    ) -> Result<Option<Vec<DataType>>> {
1005        self.inner.coerce_values_for_lambdas(fields)
1006    }
1007
1008    /// Returns the return field of the function given its arguments.
1009    ///
1010    /// See [`HigherOrderUDFImpl::return_field_from_args`] for more details.
1011    pub fn return_field_from_args(
1012        &self,
1013        args: HigherOrderReturnFieldArgs,
1014    ) -> Result<FieldRef> {
1015        self.inner.return_field_from_args(args)
1016    }
1017
1018    /// Whether List or LargeList arguments should have non-empty null sublists
1019    /// cleaned before invoking this function.
1020    pub fn clear_null_values(&self) -> bool {
1021        self.inner.clear_null_values()
1022    }
1023
1024    /// Invoke the function returning the appropriate result.
1025    ///
1026    /// See [`HigherOrderUDFImpl::invoke_with_args`] for more details.
1027    pub fn invoke_with_args(
1028        &self,
1029        args: HigherOrderFunctionArgs,
1030    ) -> Result<ColumnarValue> {
1031        self.inner.invoke_with_args(args)
1032    }
1033
1034    /// Returns true if some of this function's subexpressions may not be evaluated.
1035    ///
1036    /// See [`HigherOrderUDFImpl::short_circuits`] for more details.
1037    pub fn short_circuits(&self) -> bool {
1038        self.inner.short_circuits()
1039    }
1040
1041    /// Returns which arguments are evaluated eagerly vs lazily.
1042    ///
1043    /// See [`HigherOrderUDFImpl::conditional_arguments`] for more details.
1044    pub fn conditional_arguments<'a>(
1045        &self,
1046        args: &'a [Expr],
1047    ) -> Option<(Vec<&'a Expr>, Vec<&'a Expr>)> {
1048        self.inner.conditional_arguments(args)
1049    }
1050
1051    /// Coerce value arguments of a function call to types that the function can evaluate.
1052    ///
1053    /// See [`HigherOrderUDFImpl::coerce_value_types`] for more details.
1054    pub fn coerce_value_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
1055        self.inner.coerce_value_types(arg_types)
1056    }
1057
1058    /// Returns the documentation for this function, if any.
1059    pub fn documentation(&self) -> Option<&Documentation> {
1060        self.inner.documentation()
1061    }
1062}
1063
1064impl<F> From<F> for HigherOrderUDF
1065where
1066    F: HigherOrderUDFImpl + 'static,
1067{
1068    fn from(fun: F) -> Self {
1069        Self::new_from_impl(fun)
1070    }
1071}
1072
1073/// `HigherOrderUDFImpl` that adds aliases to the underlying function. It is
1074/// better to implement [`HigherOrderUDFImpl`], which supports aliases, directly
1075/// if possible.
1076#[derive(Debug, PartialEq, Eq, Hash)]
1077struct AliasedHigherOrderUDFImpl {
1078    inner: UdfEq<Arc<dyn HigherOrderUDFImpl>>,
1079    aliases: Vec<String>,
1080}
1081
1082impl AliasedHigherOrderUDFImpl {
1083    fn new(
1084        inner: Arc<dyn HigherOrderUDFImpl>,
1085        new_aliases: impl IntoIterator<Item = &'static str>,
1086    ) -> Self {
1087        let mut aliases = inner.aliases().to_vec();
1088        aliases.extend(new_aliases.into_iter().map(|s| s.to_string()));
1089        Self {
1090            inner: inner.into(),
1091            aliases,
1092        }
1093    }
1094}
1095
1096#[warn(clippy::missing_trait_methods)] // Delegates, so it should implement every single trait method
1097impl HigherOrderUDFImpl for AliasedHigherOrderUDFImpl {
1098    fn name(&self) -> &str {
1099        self.inner.name()
1100    }
1101
1102    fn aliases(&self) -> &[String] {
1103        &self.aliases
1104    }
1105
1106    fn schema_name(&self, args: &[Expr]) -> Result<String> {
1107        self.inner.schema_name(args)
1108    }
1109
1110    fn signature(&self) -> &HigherOrderSignature {
1111        self.inner.signature()
1112    }
1113
1114    fn lambda_parameters(
1115        &self,
1116        step: usize,
1117        fields: &[ValueOrLambda<FieldRef, Option<FieldRef>>],
1118    ) -> Result<LambdaParametersProgress> {
1119        self.inner.lambda_parameters(step, fields)
1120    }
1121
1122    fn coerce_values_for_lambdas(
1123        &self,
1124        fields: &[ValueOrLambda<DataType, DataType>],
1125    ) -> Result<Option<Vec<DataType>>> {
1126        self.inner.coerce_values_for_lambdas(fields)
1127    }
1128
1129    fn return_field_from_args(
1130        &self,
1131        args: HigherOrderReturnFieldArgs,
1132    ) -> Result<FieldRef> {
1133        self.inner.return_field_from_args(args)
1134    }
1135
1136    fn clear_null_values(&self) -> bool {
1137        self.inner.clear_null_values()
1138    }
1139
1140    fn invoke_with_args(&self, args: HigherOrderFunctionArgs) -> Result<ColumnarValue> {
1141        self.inner.invoke_with_args(args)
1142    }
1143
1144    fn short_circuits(&self) -> bool {
1145        self.inner.short_circuits()
1146    }
1147
1148    fn conditional_arguments<'a>(
1149        &self,
1150        args: &'a [Expr],
1151    ) -> Option<(Vec<&'a Expr>, Vec<&'a Expr>)> {
1152        self.inner.conditional_arguments(args)
1153    }
1154
1155    fn coerce_value_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
1156        self.inner.coerce_value_types(arg_types)
1157    }
1158
1159    fn documentation(&self) -> Option<&Documentation> {
1160        self.inner.documentation()
1161    }
1162}
1163
1164pub(crate) fn resolve_lambda_variables(
1165    expr: Expr,
1166    schema: &DFSchema,
1167    // a map of lambda variable name => a never empty stack of fields [ [..shadowed], in_scope ]
1168    vars: &mut HashMap<String, Vec<FieldRef>>,
1169) -> Result<Transformed<Expr>> {
1170    expr.transform_down(|expr| match expr {
1171        Expr::HigherOrderFunction(HigherOrderFunction { func, args }) => {
1172            // not inlined to reduce nesting
1173            resolve_higher_order_function(func, args, schema, vars)
1174        }
1175        Expr::LambdaVariable(mut var) => {
1176            let field_stack = vars.get(&var.name).ok_or_else(|| {
1177                plan_datafusion_err!(
1178                    "missing field of lambda variable {} while resolving",
1179                    var.name
1180                )
1181            })?;
1182
1183            let field = field_stack.last().ok_or_else(|| {
1184                internal_datafusion_err!("every entry should have at least one field")
1185            })?;
1186
1187            let field = Arc::clone(field).renamed(&var.name);
1188
1189            let transformed = var.field.as_ref().is_none_or(|old| old != &field);
1190
1191            var.field = Some(field);
1192
1193            Ok(Transformed::new_transformed(
1194                Expr::LambdaVariable(var),
1195                transformed,
1196            ))
1197        }
1198        _ => Ok(Transformed::no(expr)),
1199    })
1200}
1201
1202fn resolve_higher_order_function(
1203    func: Arc<HigherOrderUDF>,
1204    args: Vec<Expr>,
1205    schema: &DFSchema,
1206    // a map of lambda variable name => a never empty stack of fields [ [..shadowed], in_scope ]
1207    vars: &mut HashMap<String, Vec<FieldRef>>,
1208) -> Result<Transformed<Expr>> {
1209    /*  non-lambda args are resolved before invoking lambda_parameters because it will
1210        invoke ExprSchemable::to_field for every non-lambda parameter, and if one of them
1211        contains a lambda variable, it will fail due to it being unresolved. Example query:
1212
1213        array_transform([[1, 2]], a -> array_transform(a, b -> b+1))
1214
1215        the nested array_transform's lambda_parameters will call Lambdavariable::to_field
1216        on it's first argument, the variable `a`, which must be resolved
1217
1218        They are also resolved when no variable is in scope yet, as an argument can be a
1219        higher order function of its own, whose variables this is the only chance to
1220        resolve: the traversal jumps over the arguments once this returns. Example query:
1221
1222        array_any_match(array_transform(tags, x -> x), y -> y = 'c')
1223    */
1224    let args = args.map_elements(|arg| match arg {
1225        Expr::Lambda(_) => Ok(Transformed::no(arg)),
1226        _ => resolve_lambda_variables(arg, schema, vars),
1227    })?;
1228
1229    let transformed = args.transformed;
1230    let mut args = args.data;
1231
1232    let current_fields = args
1233        .iter()
1234        .map(|e| match e {
1235            Expr::Lambda(_lambda_function) => Ok(ValueOrLambda::Lambda(None)),
1236            _ => Ok(ValueOrLambda::Value(e.to_field(schema)?.1)),
1237        })
1238        .collect::<Result<Vec<_>>>()?;
1239
1240    // coerce fields because coercion may alter the lambda parameters
1241    let mut fields = value_fields_with_higher_order_udf(&current_fields, func.as_ref())?;
1242
1243    let num_lambdas = args.iter().filter(|a| matches!(a, Expr::Lambda(_))).count();
1244
1245    let mut step = 0;
1246
1247    let lambda_params = loop {
1248        match func.lambda_parameters(step, &fields)? {
1249            LambdaParametersProgress::Partial(params) => {
1250                let mut params = params.into_iter();
1251
1252                if params.len() != num_lambdas {
1253                    return plan_err!(
1254                        "{} lambda_parameters returned {} lambdas but {num_lambdas} expected",
1255                        func.name(),
1256                        params.len()
1257                    );
1258                }
1259
1260                for (arg, field) in std::iter::zip(&mut args, &mut fields) {
1261                    match (arg, field) {
1262                        (Expr::Lambda(lambda), ValueOrLambda::Lambda(field)) => {
1263                            let params = params.next().ok_or_else(|| {
1264                                internal_datafusion_err!(
1265                                    "params len should have been checked above"
1266                                )
1267                            })?;
1268
1269                            if let Some(params) = params {
1270                                for (name, field) in
1271                                    std::iter::zip(&lambda.params, params)
1272                                {
1273                                    vars.entry_ref(name)
1274                                        .or_default()
1275                                        .push(field.renamed(name.as_str()));
1276                                }
1277
1278                                let body_with_vars = resolve_lambda_variables(
1279                                    mem::take(lambda.body.as_mut()),
1280                                    schema,
1281                                    vars,
1282                                )?;
1283
1284                                remove_scope(vars, &lambda.params)?;
1285
1286                                *field = Some(body_with_vars.data.to_field(schema)?.1);
1287                                *lambda.body = body_with_vars.data;
1288                            }
1289                        }
1290                        (_, ValueOrLambda::Lambda(_)) => {
1291                            return internal_err!(
1292                                "value_fields_with_higher_order_udf returned a value for a lambda argument"
1293                            );
1294                        }
1295                        (Expr::Lambda(_), ValueOrLambda::Value(_)) => {
1296                            return internal_err!(
1297                                "value_fields_with_higher_order_udf returned a lambda for a value argument"
1298                            );
1299                        }
1300                        (_, ValueOrLambda::Value(_)) => {} // nothing to do
1301                    }
1302                }
1303            }
1304            LambdaParametersProgress::Complete(params) => break params,
1305        }
1306
1307        let limit = func.signature().lambda_parameters_max_iterations;
1308
1309        step += 1;
1310
1311        if step > limit {
1312            return plan_err!(
1313                "{} lambda_parameters called {limit} times without completion",
1314                func.name()
1315            );
1316        }
1317    };
1318
1319    let mut lambda_params = lambda_params.into_iter();
1320
1321    if num_lambdas != lambda_params.len() {
1322        return plan_err!(
1323            "{} lambda_parameters returned {} values for {num_lambdas} lambdas",
1324            func.name(),
1325            lambda_params.len()
1326        );
1327    }
1328
1329    let args = args.map_elements(|arg| match arg {
1330        Expr::Lambda(mut lambda) => {
1331            let lambda_params = lambda_params.next().ok_or_else(|| {
1332                internal_datafusion_err!(
1333                    "lambda_params len should have been checked above"
1334                )
1335            })?;
1336
1337            if lambda.params.len() > lambda_params.len() {
1338                return plan_err!(
1339                    "{} lambda defined {} params ({}), but only {} supported",
1340                    func.name(),
1341                    lambda.params.len(),
1342                    display_comma_separated(&lambda.params),
1343                    lambda_params.len()
1344                );
1345            }
1346
1347            if !all_unique(&lambda.params) {
1348                return plan_err!(
1349                    "lambda params must be unique, got ({})",
1350                    lambda.params.join(", ")
1351                );
1352            }
1353
1354            for (param, field) in std::iter::zip(&lambda.params, lambda_params) {
1355                vars.entry_ref(param)
1356                    .or_default()
1357                    .push(field.renamed(param.as_str()));
1358            }
1359
1360            let transformed =
1361                resolve_lambda_variables(mem::take(lambda.body.as_mut()), schema, vars)?;
1362
1363            *lambda.body = transformed.data;
1364
1365            remove_scope(vars, &lambda.params)?;
1366
1367            Ok(Transformed::new(
1368                Expr::Lambda(lambda),
1369                transformed.transformed,
1370                TreeNodeRecursion::Jump,
1371            ))
1372        }
1373        arg => Ok(Transformed::no(arg)), // resolved at the start of the function
1374    })?;
1375
1376    Ok(Transformed::new(
1377        Expr::HigherOrderFunction(HigherOrderFunction::new(func, args.data)),
1378        transformed || args.transformed,
1379        TreeNodeRecursion::Jump,
1380    ))
1381}
1382
1383fn remove_scope(
1384    vars: &mut HashMap<String, Vec<FieldRef>>,
1385    scope: &[String],
1386) -> Result<()> {
1387    for param in scope {
1388        match vars.entry_ref(param) {
1389            EntryRef::Occupied(mut v) => {
1390                if v.get().len() == 1 {
1391                    v.remove();
1392                } else {
1393                    v.get_mut().pop().ok_or_else(|| {
1394                        internal_datafusion_err!(
1395                            "every entry should have at least one field"
1396                        )
1397                    })?;
1398                }
1399            }
1400            EntryRef::Vacant(_v) => {
1401                return internal_err!("no empty value should be in the map");
1402            }
1403        }
1404    }
1405
1406    Ok(())
1407}
1408
1409fn all_unique(params: &[String]) -> bool {
1410    match params.len() {
1411        0 | 1 => true,
1412        2 => params[0] != params[1],
1413        _ => {
1414            let mut set = HashSet::with_capacity(params.len());
1415
1416            params.iter().all(|p| set.insert(p.as_str()))
1417        }
1418    }
1419}
1420
1421#[cfg(test)]
1422mod tests {
1423    use super::*;
1424    use std::hash::DefaultHasher;
1425    use std::sync::Arc;
1426
1427    use arrow_schema::{DataType, Field, FieldRef, Schema};
1428    use datafusion_common::{DFSchema, Result};
1429    use datafusion_expr_common::columnar_value::ColumnarValue;
1430    use datafusion_expr_common::signature::Volatility;
1431
1432    use crate::{
1433        Expr, HigherOrderSignature, HigherOrderUDF, HigherOrderUDFImpl,
1434        LambdaParametersProgress, ValueOrLambda, col,
1435        expr::{HigherOrderFunction, LambdaVariable},
1436        lambda, lambda_var, lit,
1437    };
1438
1439    #[derive(Debug, PartialEq, Eq, Hash)]
1440    struct TestHigherOrderUDF {
1441        name: &'static str,
1442        field: &'static str,
1443        signature: HigherOrderSignature,
1444    }
1445    impl HigherOrderUDFImpl for TestHigherOrderUDF {
1446        fn name(&self) -> &str {
1447            self.name
1448        }
1449
1450        fn signature(&self) -> &HigherOrderSignature {
1451            &self.signature
1452        }
1453
1454        fn lambda_parameters(
1455            &self,
1456            _step: usize,
1457            _fields: &[ValueOrLambda<FieldRef, Option<FieldRef>>],
1458        ) -> Result<LambdaParametersProgress> {
1459            unimplemented!()
1460        }
1461
1462        fn return_field_from_args(
1463            &self,
1464            _args: HigherOrderReturnFieldArgs,
1465        ) -> Result<FieldRef> {
1466            unimplemented!()
1467        }
1468
1469        fn invoke_with_args(
1470            &self,
1471            _args: HigherOrderFunctionArgs,
1472        ) -> Result<ColumnarValue> {
1473            unimplemented!()
1474        }
1475    }
1476
1477    // PartialEq and Hash must be consistent, and also PartialEq and PartialOrd
1478    // must be consistent, so they are tested together.
1479    #[test]
1480    fn test_partial_eq_hash_and_partial_ord() {
1481        // A parameterized function
1482        let f = test_func("foo", "a");
1483
1484        // Same like `f`, different instance
1485        let f2 = test_func("foo", "a");
1486        assert_eq!(&f, &f2);
1487        assert_eq!(hash(&f), hash(&f2));
1488        assert_eq!(f.partial_cmp(&f2), Some(Ordering::Equal));
1489
1490        // Different parameter
1491        let b = test_func("foo", "b");
1492        assert_ne!(&f, &b);
1493        assert_ne!(hash(&f), hash(&b)); // hash can collide for different values but does not collide in this test
1494        assert_eq!(f.partial_cmp(&b), None);
1495
1496        // Different name
1497        let o = test_func("other", "a");
1498        assert_ne!(&f, &o);
1499        assert_ne!(hash(&f), hash(&o)); // hash can collide for different values but does not collide in this test
1500        assert_eq!(f.partial_cmp(&o), Some(Ordering::Less));
1501
1502        // Different name and parameter
1503        assert_ne!(&b, &o);
1504        assert_ne!(hash(&b), hash(&o)); // hash can collide for different values but does not collide in this test
1505        assert_eq!(b.partial_cmp(&o), Some(Ordering::Less));
1506    }
1507
1508    fn test_func(name: &'static str, parameter: &'static str) -> Arc<HigherOrderUDF> {
1509        Arc::new(HigherOrderUDF::new_from_impl(TestHigherOrderUDF {
1510            name,
1511            field: parameter,
1512            signature: HigherOrderSignature::variadic_any(Volatility::Immutable),
1513        }))
1514    }
1515
1516    fn hash<T: Hash>(value: &T) -> u64 {
1517        let hasher = &mut DefaultHasher::new();
1518        value.hash(hasher);
1519        hasher.finish()
1520    }
1521
1522    #[derive(Debug, PartialEq, Eq, Hash)]
1523    struct MockArrayReduce {
1524        signature: HigherOrderSignature,
1525    }
1526
1527    impl HigherOrderUDFImpl for MockArrayReduce {
1528        fn name(&self) -> &str {
1529            "array_reduce"
1530        }
1531
1532        fn aliases(&self) -> &[String] {
1533            &[]
1534        }
1535
1536        fn signature(&self) -> &HigherOrderSignature {
1537            &self.signature
1538        }
1539
1540        fn lambda_parameters(
1541            &self,
1542            step: usize,
1543            fields: &[ValueOrLambda<FieldRef, Option<FieldRef>>],
1544        ) -> Result<LambdaParametersProgress> {
1545            // optional finish not supported for simplicity
1546            let [
1547                ValueOrLambda::Value(list),
1548                ValueOrLambda::Value(initial_value),
1549                ValueOrLambda::Lambda(merge),
1550                ValueOrLambda::Lambda(_finish),
1551            ] = fields
1552            else {
1553                unreachable!()
1554            };
1555
1556            let DataType::List(list_field) = list.data_type() else {
1557                unreachable!()
1558            };
1559
1560            Ok(match (step, merge) {
1561                (0, None) => {
1562                    // at the first step, we use the initial_value as merge accumulator,
1563                    // and return None for finish since we don't know the output of merge
1564                    LambdaParametersProgress::Partial(vec![
1565                        // merge
1566                        Some(vec![Arc::clone(initial_value), Arc::clone(list_field)]),
1567                        // finish
1568                        None,
1569                    ])
1570                }
1571                (1, Some(accumulator)) | (0, Some(accumulator)) => {
1572                    // now we can use the merge output as it's accumulator and
1573                    // as the finish parameter
1574                    LambdaParametersProgress::Complete(vec![
1575                        // merge
1576                        vec![Arc::clone(accumulator), Arc::clone(list_field)],
1577                        // finish
1578                        vec![Arc::clone(accumulator)],
1579                    ])
1580                }
1581                (1, None) => {
1582                    unreachable!()
1583                }
1584                _ => unreachable!(),
1585            })
1586        }
1587
1588        fn return_field_from_args(
1589            &self,
1590            args: HigherOrderReturnFieldArgs,
1591        ) -> Result<FieldRef> {
1592            // optional finish not supported for simplicity
1593            let [
1594                ValueOrLambda::Value(_list),
1595                ValueOrLambda::Value(_initial_value),
1596                ValueOrLambda::Lambda(_merge),
1597                ValueOrLambda::Lambda(finish),
1598            ] = args.arg_fields
1599            else {
1600                unreachable!()
1601            };
1602
1603            Ok(Arc::clone(finish))
1604        }
1605
1606        fn invoke_with_args(
1607            &self,
1608            _args: HigherOrderFunctionArgs,
1609        ) -> Result<ColumnarValue> {
1610            unreachable!()
1611        }
1612    }
1613
1614    #[test]
1615    fn test_resolve_lambda_variables() {
1616        let schema = DFSchema::try_from(Schema::new(vec![Field::new(
1617            "c",
1618            DataType::new_list(DataType::new_list(DataType::Int32, true), true),
1619            true,
1620        )]))
1621        .unwrap();
1622
1623        let func = Arc::new(HigherOrderUDF::new_from_impl(MockArrayReduce {
1624            signature: HigherOrderSignature::variadic_any(Volatility::Immutable),
1625        }));
1626
1627        /*
1628           array_reduce(
1629               c,
1630               0,
1631               (acc1, v) -> acc + array_reduce(
1632                   v,
1633                   0,
1634                   (acc2, v) -> acc2 + acc1 + v,
1635                   reduced -> reduced * 2.0
1636               ),
1637               reduced -> reduced * 2
1638           )
1639        */
1640        let expr = Expr::HigherOrderFunction(HigherOrderFunction::new(
1641            Arc::clone(&func),
1642            vec![
1643                col("c"),
1644                lit(0),
1645                lambda(
1646                    ["acc1", "v"],
1647                    lambda_var("acc1")
1648                        + Expr::HigherOrderFunction(HigherOrderFunction::new(
1649                            Arc::clone(&func),
1650                            vec![
1651                                lambda_var("v"),
1652                                lit(0),
1653                                lambda(
1654                                    ["acc2", "v"],
1655                                    lambda_var("acc2")
1656                                        + lambda_var("acc1")
1657                                        + lambda_var("v"),
1658                                ),
1659                                lambda(["reduced"], lambda_var("reduced") * lit(2.0)),
1660                            ],
1661                        )),
1662                ),
1663                lambda(["reduced"], lambda_var("reduced") * lit(2)),
1664            ],
1665        ));
1666
1667        let resolved_expr = expr.resolve_lambda_variables(&schema).unwrap().data;
1668
1669        /*
1670           array_reduce(
1671               c@[[Int32]],
1672               0@Int64,
1673               (acc1@Float64, v@[Int32]) -> acc@Float64 + array_reduce(
1674                   v@[Int32],
1675                   0@Int64,
1676                   (acc2@Float64, v@Int32) -> acc2@Float64 + acc1@Float64 + v@Int32,
1677                   reducedFloat64 -> reduced@Float64 * 2.0@Float64
1678               ),
1679               reduced@Float64 -> reduced@Float64 * 2@Int64
1680           )
1681        */
1682        let expected = Expr::HigherOrderFunction(HigherOrderFunction::new(
1683            Arc::clone(&func),
1684            vec![
1685                col("c"),
1686                lit(0),
1687                lambda(
1688                    ["acc1", "v"],
1689                    resolved_lambda_var("acc1", DataType::Float64, true)
1690                        + Expr::HigherOrderFunction(HigherOrderFunction::new(
1691                            Arc::clone(&func),
1692                            vec![
1693                                resolved_lambda_var(
1694                                    "v",
1695                                    DataType::new_list(DataType::Int32, true),
1696                                    true,
1697                                ),
1698                                lit(0),
1699                                lambda(
1700                                    ["acc2", "v"],
1701                                    resolved_lambda_var("acc2", DataType::Float64, true)
1702                                        + resolved_lambda_var(
1703                                            "acc1",
1704                                            DataType::Float64,
1705                                            true,
1706                                        )
1707                                        + resolved_lambda_var("v", DataType::Int32, true),
1708                                ),
1709                                lambda(
1710                                    ["reduced"],
1711                                    resolved_lambda_var(
1712                                        "reduced",
1713                                        DataType::Float64,
1714                                        true,
1715                                    ) * lit(2.0),
1716                                ),
1717                            ],
1718                        )),
1719                ),
1720                lambda(
1721                    ["reduced"],
1722                    resolved_lambda_var("reduced", DataType::Float64, true) * lit(2),
1723                ),
1724            ],
1725        ));
1726
1727        assert_eq!(resolved_expr, expected);
1728    }
1729
1730    fn resolved_lambda_var(name: &str, dt: DataType, nullable: bool) -> Expr {
1731        Expr::LambdaVariable(LambdaVariable::new(
1732            name.into(),
1733            Some(Arc::new(Field::new(name, dt, nullable))),
1734        ))
1735    }
1736
1737    /// A physical expression that reads the column at a fixed index of the
1738    /// batch it is evaluated against, for exercising [`LambdaArgument`]
1739    /// directly without depending on `datafusion-physical-expr`.
1740    #[derive(Debug, Eq, PartialEq, Hash)]
1741    struct ColumnAt(usize);
1742
1743    impl std::fmt::Display for ColumnAt {
1744        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1745            write!(f, "column_at({})", self.0)
1746        }
1747    }
1748
1749    impl PhysicalExpr for ColumnAt {
1750        fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
1751            Ok(ColumnarValue::Array(Arc::clone(batch.column(self.0))))
1752        }
1753
1754        fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
1755            vec![]
1756        }
1757
1758        fn with_new_children(
1759            self: Arc<Self>,
1760            _children: Vec<Arc<dyn PhysicalExpr>>,
1761        ) -> Result<Arc<dyn PhysicalExpr>> {
1762            Ok(self)
1763        }
1764
1765        fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1766            write!(f, "{self}")
1767        }
1768    }
1769
1770    /// `(k, v) -> v` with only `v` used must push `v`'s array, not `k`'s.
1771    #[test]
1772    fn test_lambda_argument_evaluate_pushes_only_used_param() {
1773        use arrow::array::Int32Array;
1774
1775        let k_field = Arc::new(Field::new("k", DataType::Int32, true));
1776        let v_field = Arc::new(Field::new("v", DataType::Int32, true));
1777
1778        let body = Arc::new(ColumnAt(0)) as Arc<dyn PhysicalExpr>;
1779        let lambda_arg = LambdaArgument::new(vec![k_field, v_field], body, None, &[1]);
1780
1781        let k_values: ArrayRef = Arc::new(Int32Array::from(vec![100, 200, 300]));
1782        let v_values: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
1783        let k_closure = || -> Result<ArrayRef> { Ok(Arc::clone(&k_values)) };
1784        let v_closure = || -> Result<ArrayRef> { Ok(Arc::clone(&v_values)) };
1785        let args: Vec<&dyn Fn() -> Result<ArrayRef>> = vec![&k_closure, &v_closure];
1786
1787        let result = lambda_arg
1788            .evaluate(&args, |arrays| Ok(arrays.to_vec()))
1789            .unwrap();
1790        let ColumnarValue::Array(result) = result else {
1791            unreachable!()
1792        };
1793
1794        assert_eq!(
1795            result.as_any().downcast_ref::<Int32Array>().unwrap(),
1796            &Int32Array::from(vec![1, 2, 3]),
1797            "body should read v's values, not k's"
1798        );
1799    }
1800
1801    /// Same as above, but with a capture occupying the leading slot.
1802    #[test]
1803    fn test_lambda_argument_evaluate_pushes_only_used_param_with_captures() {
1804        use arrow::array::Int32Array;
1805
1806        let cap_field = Arc::new(Field::new("cap", DataType::Int32, true));
1807        let k_field = Arc::new(Field::new("k", DataType::Int32, true));
1808        let v_field = Arc::new(Field::new("v", DataType::Int32, true));
1809
1810        let body = Arc::new(ColumnAt(1)) as Arc<dyn PhysicalExpr>;
1811
1812        let cap_values: ArrayRef = Arc::new(Int32Array::from(vec![9, 9, 9]));
1813        let captures = RecordBatch::try_new(
1814            Arc::new(Schema::new(vec![cap_field])),
1815            vec![cap_values],
1816        )
1817        .unwrap();
1818
1819        let lambda_arg =
1820            LambdaArgument::new(vec![k_field, v_field], body, Some(captures), &[1]);
1821
1822        let k_values: ArrayRef = Arc::new(Int32Array::from(vec![100, 200, 300]));
1823        let v_values: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
1824        let k_closure = || -> Result<ArrayRef> { Ok(Arc::clone(&k_values)) };
1825        let v_closure = || -> Result<ArrayRef> { Ok(Arc::clone(&v_values)) };
1826        let args: Vec<&dyn Fn() -> Result<ArrayRef>> = vec![&k_closure, &v_closure];
1827
1828        let result = lambda_arg
1829            .evaluate(&args, |arrays| Ok(arrays.to_vec()))
1830            .unwrap();
1831        let ColumnarValue::Array(result) = result else {
1832            unreachable!()
1833        };
1834
1835        assert_eq!(
1836            result.as_any().downcast_ref::<Int32Array>().unwrap(),
1837            &Int32Array::from(vec![1, 2, 3]),
1838            "body should read v's values, not k's or the capture's"
1839        );
1840    }
1841}