Skip to main content

datafusion_expr_common/
signature.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//! Function signatures: [`Volatility`], [`Signature`] and [`TypeSignature`]
6
7use std::fmt::Display;
8use std::hash::Hash;
9use std::sync::Arc;
10
11use arrow::datatypes::{
12    DECIMAL32_MAX_PRECISION, DECIMAL64_MAX_PRECISION, DECIMAL128_MAX_PRECISION, DataType,
13    Decimal128Type, DecimalType, Field, IntervalUnit, TimeUnit,
14};
15use datafusion_common::types::{LogicalType, LogicalTypeRef, NativeType};
16use datafusion_common::utils::ListCoercion;
17use datafusion_common::{Result, internal_err, plan_err};
18use indexmap::IndexSet;
19use itertools::Itertools;
20
21/// Constant that is used as a placeholder for any valid timezone.
22/// This is used where a function can accept a timestamp type with any
23/// valid timezone, it exists to avoid the need to enumerate all possible
24/// timezones. See [`TypeSignature`] for more details.
25///
26/// Type coercion always ensures that functions will be executed using
27/// timestamp arrays that have a valid time zone. Functions must never
28/// return results with this timezone.
29pub const TIMEZONE_WILDCARD: &str = "+TZ";
30
31/// Constant that is used as a placeholder for any valid fixed size list.
32/// This is used where a function can accept a fixed size list type with any
33/// valid length. It exists to avoid the need to enumerate all possible fixed size list lengths.
34pub const FIXED_SIZE_LIST_WILDCARD: i32 = i32::MIN;
35
36/// How a function's output changes with respect to a fixed input
37///
38/// The volatility of a function determines eligibility for certain
39/// optimizations. You should always define your function to have the strictest
40/// possible volatility to maximize performance and avoid unexpected
41/// results.
42#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
43pub enum Volatility {
44    /// Always returns the same output when given the same input.
45    ///
46    /// DataFusion will inline immutable functions during planning.
47    ///
48    /// For example, the `abs` function is immutable, so `abs(-1)` will be
49    /// evaluated and replaced  with `1` during planning rather than invoking
50    /// the function at runtime.
51    Immutable,
52    /// May return different values given the same input across different
53    /// queries but must return the same value for a given input within a query.
54    ///
55    /// For example, the `now()` function is stable, because the query `select
56    /// col1, now() from t1`, will return different results each time it is run,
57    /// but within the same query, the output of the `now()` function has the
58    /// same value for each output row.
59    ///
60    /// DataFusion will inline `Stable` functions when possible. For example,
61    /// `Stable` functions are inlined when planning a query for execution, but
62    /// not in View definitions or prepared statements.
63    Stable,
64    /// May change the return value from evaluation to evaluation.
65    ///
66    /// Multiple invocations of a volatile function may return different results
67    /// when used in the same query on different rows. An example of this is the
68    /// `random()` function.
69    ///
70    /// DataFusion can not evaluate such functions during planning or push these
71    /// predicates into scans. In the query `select col1, random() from t1`,
72    /// `random()` function will be evaluated for each output row, resulting in
73    /// a unique random value for each row.
74    Volatile,
75}
76
77/// Represents the arity (number of arguments) of a function signature
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum Arity {
80    /// Fixed number of arguments
81    Fixed(usize),
82    /// Variable number of arguments (e.g., Variadic, VariadicAny, UserDefined)
83    Variable,
84}
85
86/// The types of arguments for which a function has implementations.
87///
88/// [`TypeSignature`] **DOES NOT** define the types that a user query could call the
89/// function with. DataFusion will automatically coerce (cast) argument types to
90/// one of the supported function signatures, if possible.
91///
92/// # Overview
93/// Functions typically provide implementations for a small number of different
94/// argument [`DataType`]s, rather than all possible combinations. If a user
95/// calls a function with arguments that do not match any of the declared types,
96/// DataFusion will attempt to automatically coerce (add casts to) function
97/// arguments so they match the [`TypeSignature`]. See the [`type_coercion`] module
98/// for more details
99///
100/// # Example: Numeric Functions
101/// For example, a function like `cos` may only provide an implementation for
102/// [`DataType::Float64`]. When users call `cos` with a different argument type,
103/// such as `cos(int_column)`, and type coercion automatically adds a cast such
104/// as `cos(CAST int_column AS DOUBLE)` during planning.
105///
106/// [`type_coercion`]: crate::type_coercion
107///
108/// ## Example: Strings
109///
110/// There are several different string types in Arrow, such as
111/// [`DataType::Utf8`], [`DataType::LargeUtf8`], and [`DataType::Utf8View`].
112///
113/// Some functions may have specialized implementations for these types, while others
114/// may be able to handle only one of them. For example, a function that
115/// only works with [`DataType::Utf8View`] would have the following signature:
116///
117/// ```
118/// # use arrow::datatypes::DataType;
119/// # use datafusion_expr_common::signature::{TypeSignature};
120/// // Declares the function must be invoked with a single argument of type `Utf8View`.
121/// // if a user calls the function with `Utf8` or `LargeUtf8`, DataFusion will
122/// // automatically add a cast to `Utf8View` during planning.
123/// let type_signature = TypeSignature::Exact(vec![DataType::Utf8View]);
124/// ```
125///
126/// # Example: Timestamps
127///
128/// Types to match are represented using Arrow's [`DataType`].  [`DataType::Timestamp`] has an optional variable
129/// timezone specification. To specify a function can handle a timestamp with *ANY* timezone, use
130/// the [`TIMEZONE_WILDCARD`]. For example:
131///
132/// ```
133/// # use arrow::datatypes::{DataType, TimeUnit};
134/// # use datafusion_expr_common::signature::{TIMEZONE_WILDCARD, TypeSignature};
135/// let type_signature = TypeSignature::Exact(vec![
136///     // A nanosecond precision timestamp with ANY timezone
137///     // matches  Timestamp(Nanosecond, Some("+0:00"))
138///     // matches  Timestamp(Nanosecond, Some("+5:00"))
139///     // does not match  Timestamp(Nanosecond, None)
140///     DataType::Timestamp(TimeUnit::Nanosecond, Some(TIMEZONE_WILDCARD.into())),
141/// ]);
142/// ```
143#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
144pub enum TypeSignature {
145    /// One or more arguments of a common type out of a list of valid types.
146    ///
147    /// For functions that take no arguments (e.g. `random()`), see [`TypeSignature::Nullary`].
148    ///
149    /// # Examples
150    ///
151    /// A function such as `concat` is `Variadic(vec![DataType::Utf8,
152    /// DataType::LargeUtf8])`
153    Variadic(Vec<DataType>),
154    /// The acceptable signature and coercions rules are special for this
155    /// function.
156    ///
157    /// If this signature is specified,
158    /// DataFusion will call [`ScalarUDFImpl::coerce_types`] to prepare argument types.
159    ///
160    /// [`ScalarUDFImpl::coerce_types`]: https://docs.rs/datafusion/latest/datafusion/logical_expr/trait.ScalarUDFImpl.html#method.coerce_types
161    UserDefined,
162    /// One or more arguments with arbitrary types
163    VariadicAny,
164    /// One or more arguments of an arbitrary but equal type out of a list of valid types.
165    ///
166    /// # Examples
167    ///
168    /// 1. A function of one argument of f64 is `Uniform(1, vec![DataType::Float64])`
169    /// 2. A function of one argument of f64 or f32 is `Uniform(1, vec![DataType::Float32, DataType::Float64])`
170    Uniform(usize, Vec<DataType>),
171    /// One or more arguments with exactly the specified types in order.
172    ///
173    /// For functions that take no arguments (e.g. `random()`), use [`TypeSignature::Nullary`].
174    Exact(Vec<DataType>),
175    /// One or more arguments belonging to the [`TypeSignatureClass`], in order.
176    ///
177    /// [`Coercion`] contains not only the desired type but also the allowed
178    /// casts. For example, if you expect a function has string type, but you
179    /// also allow it to be casted from binary type.
180    ///
181    /// For functions that take no arguments (e.g. `random()`), see [`TypeSignature::Nullary`].
182    Coercible(Vec<Coercion>),
183    /// One or more arguments coercible to a single, comparable type.
184    ///
185    /// Each argument will be coerced to a single type using the
186    /// coercion rules described in [`comparison_coercion`].
187    ///
188    /// # Examples
189    ///
190    /// If the `nullif(1, 2)` function is called with `i32` and `i64` arguments
191    /// the types will both be coerced to `i64` before the function is invoked.
192    ///
193    /// If the `nullif('1', 2)` function is called with `Utf8` and `i64` arguments
194    /// the types will both be coerced to `Int64` before the function is invoked
195    /// (numeric is preferred over string).
196    ///
197    /// Note:
198    /// - For functions that take no arguments (e.g. `random()`), see [`TypeSignature::Nullary`].
199    /// - If all arguments have type [`DataType::Null`], they are coerced to `Utf8`
200    ///
201    /// [`comparison_coercion`]: crate::type_coercion::binary::comparison_coercion
202    Comparable(usize),
203    /// One or more arguments of arbitrary types.
204    ///
205    /// For functions that take no arguments (e.g. `random()`), use [`TypeSignature::Nullary`].
206    Any(usize),
207    /// Matches exactly one of a list of [`TypeSignature`]s.
208    ///
209    /// Coercion is attempted to match the signatures in order, and stops after
210    /// the first success, if any.
211    ///
212    /// # Examples
213    ///
214    /// Since `make_array` takes 0 or more arguments with arbitrary types, its `TypeSignature`
215    /// is `OneOf(vec![Any(0), VariadicAny])`.
216    OneOf(Vec<TypeSignature>),
217    /// A function that has an [`ArrayFunctionSignature`]
218    ArraySignature(ArrayFunctionSignature),
219    /// One or more arguments of numeric types, coerced to a common numeric type.
220    ///
221    /// See [`NativeType::is_numeric`] to know which type is considered numeric
222    ///
223    /// For functions that take no arguments (e.g. `random()`), use [`TypeSignature::Nullary`].
224    ///
225    /// [`NativeType::is_numeric`]: datafusion_common::types::NativeType::is_numeric
226    Numeric(usize),
227    /// One or arguments of all the same string types.
228    ///
229    /// The precedence of type from high to low is Utf8View, LargeUtf8 and Utf8.
230    /// Null is considered as `Utf8` by default
231    /// Dictionary with string value type is also handled.
232    ///
233    /// For example, if a function is called with (utf8, large_utf8), all
234    /// arguments will be coerced to  `LargeUtf8`
235    ///
236    /// For functions that take no arguments (e.g. `random()`), use [`TypeSignature::Nullary`].
237    String(usize),
238    /// No arguments
239    Nullary,
240}
241
242impl TypeSignature {
243    #[inline]
244    pub fn is_one_of(&self) -> bool {
245        matches!(self, TypeSignature::OneOf(_))
246    }
247
248    /// Returns the arity (expected number of arguments) for this type signature.
249    ///
250    /// Returns `Arity::Fixed(n)` for signatures with a specific argument count,
251    /// or `Arity::Variable` for variable-arity signatures like `Variadic`, `VariadicAny`, `UserDefined`.
252    ///
253    /// # Examples
254    ///
255    /// ```
256    /// # use datafusion_expr_common::signature::{TypeSignature, Arity};
257    /// # use arrow::datatypes::DataType;
258    /// // Exact signature has fixed arity
259    /// let sig = TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]);
260    /// assert_eq!(sig.arity(), Arity::Fixed(2));
261    ///
262    /// // Variadic signature has variable arity
263    /// let sig = TypeSignature::VariadicAny;
264    /// assert_eq!(sig.arity(), Arity::Variable);
265    /// ```
266    pub fn arity(&self) -> Arity {
267        match self {
268            TypeSignature::Exact(types) => Arity::Fixed(types.len()),
269            TypeSignature::Uniform(count, _) => Arity::Fixed(*count),
270            TypeSignature::Numeric(count) => Arity::Fixed(*count),
271            TypeSignature::String(count) => Arity::Fixed(*count),
272            TypeSignature::Comparable(count) => Arity::Fixed(*count),
273            TypeSignature::Any(count) => Arity::Fixed(*count),
274            TypeSignature::Coercible(types) => Arity::Fixed(types.len()),
275            TypeSignature::Nullary => Arity::Fixed(0),
276            TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
277                arguments,
278                ..
279            }) => Arity::Fixed(arguments.len()),
280            TypeSignature::ArraySignature(ArrayFunctionSignature::RecursiveArray) => {
281                Arity::Fixed(1)
282            }
283            TypeSignature::ArraySignature(ArrayFunctionSignature::MapArray) => {
284                Arity::Fixed(1)
285            }
286            TypeSignature::OneOf(variants) => {
287                // If any variant is Variable, the whole OneOf is Variable
288                let has_variable = variants.iter().any(|v| v.arity() == Arity::Variable);
289                if has_variable {
290                    return Arity::Variable;
291                }
292                // Otherwise, get max arity from all fixed arity variants
293                let max_arity = variants
294                    .iter()
295                    .filter_map(|v| match v.arity() {
296                        Arity::Fixed(n) => Some(n),
297                        Arity::Variable => None,
298                    })
299                    .max();
300                match max_arity {
301                    Some(n) => Arity::Fixed(n),
302                    None => Arity::Variable,
303                }
304            }
305            TypeSignature::Variadic(_)
306            | TypeSignature::VariadicAny
307            | TypeSignature::UserDefined => Arity::Variable,
308        }
309    }
310}
311
312impl Display for TypeSignature {
313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314        match self {
315            TypeSignature::Variadic(types) => {
316                write!(f, "Variadic({})", types.iter().join(", "))
317            }
318            TypeSignature::UserDefined => write!(f, "UserDefined"),
319            TypeSignature::VariadicAny => write!(f, "VariadicAny"),
320            TypeSignature::Uniform(count, types) => {
321                write!(f, "Uniform({count}, [{}])", types.iter().join(", "))
322            }
323            TypeSignature::Exact(types) => {
324                write!(f, "Exact({})", types.iter().join(", "))
325            }
326            TypeSignature::Coercible(coercions) => {
327                write!(f, "Coercible({})", coercions.iter().join(", "))
328            }
329            TypeSignature::Comparable(count) => write!(f, "Comparable({count})"),
330            TypeSignature::Any(count) => write!(f, "Any({count})"),
331            TypeSignature::OneOf(sigs) => {
332                write!(f, "OneOf(")?;
333                for (i, sig) in sigs.iter().enumerate() {
334                    if i > 0 {
335                        write!(f, ", ")?;
336                    }
337                    write!(f, "{sig}")?;
338                }
339                write!(f, ")")
340            }
341            TypeSignature::ArraySignature(sig) => write!(f, "ArraySignature({sig})"),
342            TypeSignature::Numeric(count) => write!(f, "Numeric({count})"),
343            TypeSignature::String(count) => write!(f, "String({count})"),
344            TypeSignature::Nullary => write!(f, "Nullary"),
345        }
346    }
347}
348
349/// Represents the class of types that can be used in a function signature.
350///
351/// This is used to specify what types are valid for function arguments in a more flexible way than
352/// just listing specific DataTypes. For example, TypeSignatureClass::Timestamp matches any timestamp
353/// type regardless of timezone or precision.
354///
355/// Used primarily with [`TypeSignature::Coercible`] to define function signatures that can accept
356/// arguments that can be coerced to a particular class of types.
357#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Hash)]
358pub enum TypeSignatureClass {
359    /// Allows an arbitrary type argument without coercing the argument.
360    Any,
361    /// Timestamps, allowing arbitrary (or no) timezones
362    Timestamp,
363    /// All time types
364    Time,
365    /// All interval types
366    Interval,
367    /// All duration types
368    Duration,
369    /// A specific native type
370    Native(LogicalTypeRef),
371    /// Signed and unsigned integers
372    Integer,
373    /// All float types
374    Float,
375    /// All decimal types, allowing arbitrary precision & scale
376    Decimal,
377    /// Integers, floats and decimals
378    Numeric,
379    /// Encompasses both the native Binary/LargeBinary types as well as arbitrarily sized FixedSizeBinary types
380    Binary,
381}
382
383impl Display for TypeSignatureClass {
384    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
385        match self {
386            Self::Any => write!(f, "Any"),
387            Self::Timestamp => write!(f, "Timestamp"),
388            Self::Time => write!(f, "Time"),
389            Self::Interval => write!(f, "Interval"),
390            Self::Duration => write!(f, "Duration"),
391            Self::Native(logical_type) => write!(f, "{logical_type}"),
392            Self::Integer => write!(f, "Integer"),
393            Self::Float => write!(f, "Float"),
394            Self::Decimal => write!(f, "Decimal"),
395            Self::Numeric => write!(f, "Numeric"),
396            Self::Binary => write!(f, "Binary"),
397        }
398    }
399}
400
401impl TypeSignatureClass {
402    /// Get example acceptable types for this `TypeSignatureClass`
403    ///
404    /// This is used for `information_schema` and can be used to generate
405    /// documentation or error messages.
406    // Deprecated, remove with `get_example_types`
407    fn get_example_types(&self) -> Vec<DataType> {
408        match self {
409            TypeSignatureClass::Any => vec![],
410            TypeSignatureClass::Native(l) => get_data_types(l.native()),
411            TypeSignatureClass::Timestamp => {
412                vec![
413                    DataType::Timestamp(TimeUnit::Nanosecond, None),
414                    DataType::Timestamp(
415                        TimeUnit::Nanosecond,
416                        Some(TIMEZONE_WILDCARD.into()),
417                    ),
418                ]
419            }
420            TypeSignatureClass::Time => {
421                vec![DataType::Time64(TimeUnit::Nanosecond)]
422            }
423            TypeSignatureClass::Interval => {
424                vec![DataType::Interval(IntervalUnit::DayTime)]
425            }
426            TypeSignatureClass::Duration => {
427                vec![DataType::Duration(TimeUnit::Nanosecond)]
428            }
429            TypeSignatureClass::Integer => {
430                vec![DataType::Int64]
431            }
432            TypeSignatureClass::Binary => {
433                vec![DataType::Binary]
434            }
435            TypeSignatureClass::Decimal => vec![Decimal128Type::DEFAULT_TYPE],
436            TypeSignatureClass::Float => vec![DataType::Float64],
437            TypeSignatureClass::Numeric => vec![
438                DataType::Float64,
439                DataType::Int64,
440                Decimal128Type::DEFAULT_TYPE,
441            ],
442        }
443    }
444
445    /// Get example acceptable types for this `TypeSignatureClass`
446    ///
447    /// This is used for `information_schema` and can be used to generate
448    /// documentation or error messages.
449    fn get_representative_types(&self) -> Vec<NativeType> {
450        match self {
451            TypeSignatureClass::Any => vec![],
452            TypeSignatureClass::Native(l) => vec![l.native().clone()],
453            TypeSignatureClass::Timestamp => {
454                vec![
455                    NativeType::Timestamp(TimeUnit::Nanosecond, None),
456                    NativeType::Timestamp(
457                        TimeUnit::Nanosecond,
458                        Some(TIMEZONE_WILDCARD.into()),
459                    ),
460                ]
461            }
462            TypeSignatureClass::Time => {
463                vec![NativeType::Time(TimeUnit::Nanosecond)]
464            }
465            TypeSignatureClass::Interval => {
466                vec![NativeType::Interval(IntervalUnit::DayTime)]
467            }
468            TypeSignatureClass::Duration => {
469                vec![NativeType::Duration(TimeUnit::Nanosecond)]
470            }
471            TypeSignatureClass::Integer => {
472                vec![NativeType::Int64]
473            }
474            TypeSignatureClass::Binary => {
475                vec![NativeType::Binary]
476            }
477            TypeSignatureClass::Decimal => vec![Decimal128Type::DEFAULT_TYPE.into()],
478            TypeSignatureClass::Float => vec![NativeType::Float64],
479            TypeSignatureClass::Numeric => {
480                vec![
481                    NativeType::Float64,
482                    NativeType::Int64,
483                    Decimal128Type::DEFAULT_TYPE.into(),
484                ]
485            }
486        }
487    }
488
489    /// Does the specified `NativeType` match this type signature class?
490    pub fn matches_native_type(&self, logical_type: &NativeType) -> bool {
491        if logical_type == &NativeType::Null {
492            return true;
493        }
494
495        match self {
496            TypeSignatureClass::Any => true,
497            TypeSignatureClass::Native(t) if t.native() == logical_type => true,
498            TypeSignatureClass::Timestamp if logical_type.is_timestamp() => true,
499            TypeSignatureClass::Time if logical_type.is_time() => true,
500            TypeSignatureClass::Interval if logical_type.is_interval() => true,
501            TypeSignatureClass::Duration if logical_type.is_duration() => true,
502            TypeSignatureClass::Integer if logical_type.is_integer() => true,
503            TypeSignatureClass::Binary if logical_type.is_binary() => true,
504            TypeSignatureClass::Decimal if logical_type.is_decimal() => true,
505            TypeSignatureClass::Float if logical_type.is_float() => true,
506            TypeSignatureClass::Numeric if logical_type.is_numeric() => true,
507            _ => false,
508        }
509    }
510
511    /// What type would `origin_type` be casted to when casting to the specified native type?
512    pub fn default_casted_type(
513        &self,
514        native_type: &NativeType,
515        origin_type: &DataType,
516    ) -> Result<DataType> {
517        match self {
518            TypeSignatureClass::Any => Ok(origin_type.to_owned()),
519            TypeSignatureClass::Native(logical_type) => {
520                logical_type.native().default_cast_for(origin_type)
521            }
522            // If the given type is already a timestamp, we don't change the unit and timezone
523            TypeSignatureClass::Timestamp if native_type.is_timestamp() => {
524                Ok(origin_type.to_owned())
525            }
526            TypeSignatureClass::Time if native_type.is_time() => {
527                Ok(origin_type.to_owned())
528            }
529            TypeSignatureClass::Interval if native_type.is_interval() => {
530                Ok(origin_type.to_owned())
531            }
532            TypeSignatureClass::Duration if native_type.is_duration() => {
533                Ok(origin_type.to_owned())
534            }
535            TypeSignatureClass::Integer if native_type.is_integer() => {
536                Ok(origin_type.to_owned())
537            }
538            TypeSignatureClass::Binary if native_type.is_binary() => {
539                Ok(origin_type.to_owned())
540            }
541            // Binary has an unambiguous default, unlike Timestamp; cast NULL rather
542            // than letting the generic arm below pass DataType::Null downstream.
543            TypeSignatureClass::Binary if native_type.is_null() => Ok(DataType::Binary),
544            TypeSignatureClass::Decimal if native_type.is_decimal() => {
545                Ok(origin_type.to_owned())
546            }
547            TypeSignatureClass::Float if native_type.is_float() => {
548                Ok(origin_type.to_owned())
549            }
550            TypeSignatureClass::Numeric if native_type.is_numeric() => {
551                Ok(origin_type.to_owned())
552            }
553            _ if native_type.is_null() => Ok(origin_type.to_owned()),
554            _ => internal_err!("May miss the matching logic in `matches_native_type`"),
555        }
556    }
557}
558
559#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
560pub enum ArrayFunctionSignature {
561    /// A function takes at least one List/LargeList/FixedSizeList argument.
562    Array {
563        /// A full list of the arguments accepted by this function.
564        arguments: Vec<ArrayFunctionArgument>,
565        /// Additional information about how array arguments should be coerced.
566        array_coercion: Option<ListCoercion>,
567    },
568    /// A function takes a single argument that must be a List/LargeList/FixedSizeList
569    /// which gets coerced to List, with element type recursively coerced to List too if it is list-like.
570    RecursiveArray,
571    /// Specialized Signature for MapArray
572    /// The function takes a single argument that must be a MapArray
573    MapArray,
574}
575
576impl Display for ArrayFunctionSignature {
577    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
578        match self {
579            ArrayFunctionSignature::Array { arguments, .. } => {
580                for (idx, argument) in arguments.iter().enumerate() {
581                    write!(f, "{argument}")?;
582                    if idx != arguments.len() - 1 {
583                        write!(f, ", ")?;
584                    }
585                }
586                Ok(())
587            }
588            ArrayFunctionSignature::RecursiveArray => {
589                write!(f, "recursive_array")
590            }
591            ArrayFunctionSignature::MapArray => {
592                write!(f, "map_array")
593            }
594        }
595    }
596}
597
598#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
599pub enum ArrayFunctionArgument {
600    /// A non-list or list argument. The list dimensions should be one less than the Array's list
601    /// dimensions.
602    Element,
603    /// An Int64 index argument.
604    Index,
605    /// An argument of type List/LargeList/FixedSizeList. All Array arguments must be coercible
606    /// to the same type.
607    Array,
608    // A Utf8 argument.
609    String,
610}
611
612impl Display for ArrayFunctionArgument {
613    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
614        match self {
615            ArrayFunctionArgument::Element => {
616                write!(f, "element")
617            }
618            ArrayFunctionArgument::Index => {
619                write!(f, "index")
620            }
621            ArrayFunctionArgument::Array => {
622                write!(f, "array")
623            }
624            ArrayFunctionArgument::String => {
625                write!(f, "string")
626            }
627        }
628    }
629}
630
631// Deprecated, remove with `get_example_types`
632static NUMERICS: &[DataType] = &[
633    DataType::Int8,
634    DataType::Int16,
635    DataType::Int32,
636    DataType::Int64,
637    DataType::UInt8,
638    DataType::UInt16,
639    DataType::UInt32,
640    DataType::UInt64,
641    DataType::Float16,
642    DataType::Float32,
643    DataType::Float64,
644];
645
646impl TypeSignature {
647    pub fn to_string_repr(&self) -> Vec<String> {
648        match self {
649            TypeSignature::Nullary => {
650                vec!["NullAry()".to_string()]
651            }
652            TypeSignature::Variadic(types) => {
653                vec![format!("{}, ..", Self::join_types(types, "/"))]
654            }
655            TypeSignature::Uniform(arg_count, valid_types) => {
656                vec![
657                    std::iter::repeat_n(Self::join_types(valid_types, "/"), *arg_count)
658                        .collect::<Vec<String>>()
659                        .join(", "),
660                ]
661            }
662            TypeSignature::String(num) => {
663                vec![format!("String({num})")]
664            }
665            TypeSignature::Numeric(num) => {
666                vec![format!("Numeric({num})")]
667            }
668            TypeSignature::Comparable(num) => {
669                vec![format!("Comparable({num})")]
670            }
671            TypeSignature::Coercible(coercions) => {
672                vec![Self::join_types(coercions, ", ")]
673            }
674            TypeSignature::Exact(types) => {
675                vec![Self::join_types(types, ", ")]
676            }
677            TypeSignature::Any(arg_count) => {
678                vec![
679                    std::iter::repeat_n("Any", *arg_count)
680                        .collect::<Vec<&str>>()
681                        .join(", "),
682                ]
683            }
684            TypeSignature::UserDefined => {
685                vec!["UserDefined".to_string()]
686            }
687            TypeSignature::VariadicAny => vec!["Any, .., Any".to_string()],
688            TypeSignature::OneOf(sigs) => {
689                sigs.iter().flat_map(|s| s.to_string_repr()).collect()
690            }
691            TypeSignature::ArraySignature(array_signature) => {
692                vec![array_signature.to_string()]
693            }
694        }
695    }
696
697    /// Return string representation of the function signature with parameter names.
698    ///
699    /// This method is similar to [`Self::to_string_repr`] but uses parameter names
700    /// instead of types when available. This is useful for generating more helpful
701    /// error messages.
702    ///
703    /// # Arguments
704    /// * `parameter_names` - Optional slice of parameter names. When provided, these
705    ///   names will be used instead of type names in the output.
706    ///
707    /// # Examples
708    /// ```
709    /// # use datafusion_expr_common::signature::TypeSignature;
710    /// # use arrow::datatypes::DataType;
711    /// let sig = TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]);
712    ///
713    /// // Without names: shows types only
714    /// assert_eq!(sig.to_string_repr_with_names(None), vec!["Int32, Utf8"]);
715    ///
716    /// // With names: shows parameter names with types
717    /// assert_eq!(
718    ///     sig.to_string_repr_with_names(Some(&["id".to_string(), "name".to_string()])),
719    ///     vec!["id: Int32, name: Utf8"]
720    /// );
721    /// ```
722    pub fn to_string_repr_with_names(
723        &self,
724        parameter_names: Option<&[String]>,
725    ) -> Vec<String> {
726        match self {
727            TypeSignature::Exact(types) => {
728                if let Some(names) = parameter_names {
729                    vec![
730                        names
731                            .iter()
732                            .zip(types.iter())
733                            .map(|(name, typ)| format!("{name}: {typ}"))
734                            .collect::<Vec<_>>()
735                            .join(", "),
736                    ]
737                } else {
738                    vec![Self::join_types(types, ", ")]
739                }
740            }
741            TypeSignature::Any(count) => {
742                if let Some(names) = parameter_names {
743                    vec![
744                        names
745                            .iter()
746                            .take(*count)
747                            .map(|name| format!("{name}: Any"))
748                            .collect::<Vec<_>>()
749                            .join(", "),
750                    ]
751                } else {
752                    vec![
753                        std::iter::repeat_n("Any", *count)
754                            .collect::<Vec<&str>>()
755                            .join(", "),
756                    ]
757                }
758            }
759            TypeSignature::Uniform(count, types) => {
760                if let Some(names) = parameter_names {
761                    let type_str = Self::join_types(types, "/");
762                    vec![
763                        names
764                            .iter()
765                            .take(*count)
766                            .map(|name| format!("{name}: {type_str}"))
767                            .collect::<Vec<_>>()
768                            .join(", "),
769                    ]
770                } else {
771                    self.to_string_repr()
772                }
773            }
774            TypeSignature::Coercible(coercions) => {
775                if let Some(names) = parameter_names {
776                    vec![
777                        names
778                            .iter()
779                            .zip(coercions.iter())
780                            .map(|(name, coercion)| format!("{name}: {coercion}"))
781                            .collect::<Vec<_>>()
782                            .join(", "),
783                    ]
784                } else {
785                    vec![Self::join_types(coercions, ", ")]
786                }
787            }
788            TypeSignature::Comparable(count) => {
789                if let Some(names) = parameter_names {
790                    vec![
791                        names
792                            .iter()
793                            .take(*count)
794                            .map(|name| format!("{name}: Comparable"))
795                            .collect::<Vec<_>>()
796                            .join(", "),
797                    ]
798                } else {
799                    self.to_string_repr()
800                }
801            }
802            TypeSignature::Numeric(count) => {
803                if let Some(names) = parameter_names {
804                    vec![
805                        names
806                            .iter()
807                            .take(*count)
808                            .map(|name| format!("{name}: Numeric"))
809                            .collect::<Vec<_>>()
810                            .join(", "),
811                    ]
812                } else {
813                    self.to_string_repr()
814                }
815            }
816            TypeSignature::String(count) => {
817                if let Some(names) = parameter_names {
818                    vec![
819                        names
820                            .iter()
821                            .take(*count)
822                            .map(|name| format!("{name}: String"))
823                            .collect::<Vec<_>>()
824                            .join(", "),
825                    ]
826                } else {
827                    self.to_string_repr()
828                }
829            }
830            TypeSignature::Nullary => self.to_string_repr(),
831            TypeSignature::ArraySignature(array_sig) => {
832                if let Some(names) = parameter_names {
833                    match array_sig {
834                        ArrayFunctionSignature::Array { arguments, .. } => {
835                            vec![
836                                names
837                                    .iter()
838                                    .zip(arguments.iter())
839                                    .map(|(name, arg_type)| format!("{name}: {arg_type}"))
840                                    .collect::<Vec<_>>()
841                                    .join(", "),
842                            ]
843                        }
844                        ArrayFunctionSignature::RecursiveArray => {
845                            vec![
846                                names
847                                    .iter()
848                                    .take(1)
849                                    .map(|name| format!("{name}: recursive_array"))
850                                    .collect::<Vec<_>>()
851                                    .join(", "),
852                            ]
853                        }
854                        ArrayFunctionSignature::MapArray => {
855                            vec![
856                                names
857                                    .iter()
858                                    .take(1)
859                                    .map(|name| format!("{name}: map_array"))
860                                    .collect::<Vec<_>>()
861                                    .join(", "),
862                            ]
863                        }
864                    }
865                } else {
866                    self.to_string_repr()
867                }
868            }
869            TypeSignature::OneOf(sigs) => sigs
870                .iter()
871                .flat_map(|s| s.to_string_repr_with_names(parameter_names))
872                .collect(),
873            TypeSignature::UserDefined => {
874                if let Some(names) = parameter_names {
875                    vec![names.join(", ")]
876                } else {
877                    self.to_string_repr()
878                }
879            }
880            // Variable arity signatures cannot use parameter names
881            TypeSignature::Variadic(_) | TypeSignature::VariadicAny => {
882                self.to_string_repr()
883            }
884        }
885    }
886
887    /// Helper function to join types with specified delimiter.
888    pub fn join_types<T: Display>(types: &[T], delimiter: &str) -> String {
889        types
890            .iter()
891            .map(|t| t.to_string())
892            .collect::<Vec<String>>()
893            .join(delimiter)
894    }
895
896    /// Check whether 0 input argument is valid for given `TypeSignature`
897    pub fn supports_zero_argument(&self) -> bool {
898        match &self {
899            TypeSignature::Exact(vec) => vec.is_empty(),
900            TypeSignature::Nullary => true,
901            TypeSignature::OneOf(types) => types
902                .iter()
903                .any(|type_sig| type_sig.supports_zero_argument()),
904            _ => false,
905        }
906    }
907
908    /// Returns true if the signature currently supports or used to supported 0
909    /// input arguments in a previous version of DataFusion.
910    pub fn used_to_support_zero_arguments(&self) -> bool {
911        match &self {
912            TypeSignature::Any(num) => *num == 0,
913            _ => self.supports_zero_argument(),
914        }
915    }
916
917    /// Return example acceptable types for this `TypeSignature`'
918    ///
919    /// Returns a `Vec<DataType>` for each argument to the function
920    ///
921    /// This is used for `information_schema` and can be used to generate
922    /// documentation or error messages.
923    #[deprecated(since = "55.0.0", note = "See get_representative_types instead")]
924    pub fn get_example_types(&self) -> Vec<Vec<DataType>> {
925        match self {
926            TypeSignature::Exact(types) => vec![types.clone()],
927            TypeSignature::OneOf(types) => types
928                .iter()
929                .flat_map(|type_sig| type_sig.get_example_types())
930                .collect(),
931            TypeSignature::Uniform(arg_count, types) => types
932                .iter()
933                .cloned()
934                .map(|data_type| vec![data_type; *arg_count])
935                .collect(),
936            TypeSignature::Coercible(coercions) => coercions
937                .iter()
938                .map(|c| {
939                    let mut all_types: IndexSet<DataType> =
940                        c.desired_type().get_example_types().into_iter().collect();
941
942                    if let Some(implicit_coercion) = c.implicit_coercion() {
943                        let allowed_casts: Vec<DataType> = implicit_coercion
944                            .allowed_source_types
945                            .iter()
946                            .flat_map(|t| t.get_example_types())
947                            .collect();
948                        all_types.extend(allowed_casts);
949                    }
950
951                    all_types.into_iter().collect::<Vec<_>>()
952                })
953                .multi_cartesian_product()
954                .collect(),
955            TypeSignature::Variadic(types) => types
956                .iter()
957                .cloned()
958                .map(|data_type| vec![data_type])
959                .collect(),
960            TypeSignature::Numeric(arg_count) => NUMERICS
961                .iter()
962                .cloned()
963                .map(|numeric_type| vec![numeric_type; *arg_count])
964                .collect(),
965            TypeSignature::String(arg_count) => get_data_types(&NativeType::String)
966                .into_iter()
967                .map(|dt| vec![dt; *arg_count])
968                .collect::<Vec<_>>(),
969            // TODO: Implement for other types
970            TypeSignature::Any(_)
971            | TypeSignature::Comparable(_)
972            | TypeSignature::Nullary
973            | TypeSignature::VariadicAny
974            | TypeSignature::ArraySignature(_)
975            | TypeSignature::UserDefined => vec![],
976        }
977    }
978
979    /// Return example acceptable types for this `TypeSignature'
980    ///
981    /// Returns a `Vec<NativeType>` for each argument to the function
982    ///
983    /// This is used for `information_schema` and can be used to generate
984    /// documentation or error messages. The returned types are the types a caller may pass.
985    /// Callers computing return types must apply coercion themselves.
986    pub fn get_representative_types(&self) -> Vec<Vec<NativeType>> {
987        match self {
988            TypeSignature::Exact(types) => vec![
989                types
990                    .iter()
991                    .map(|data_type| NativeType::from(data_type.clone()))
992                    .collect(),
993            ],
994            TypeSignature::OneOf(types) => types
995                .iter()
996                .flat_map(|type_sig| type_sig.get_representative_types())
997                .collect(),
998            TypeSignature::Uniform(arg_count, types) => types
999                .iter()
1000                .cloned()
1001                .map(|data_type| vec![data_type.into(); *arg_count])
1002                .collect(),
1003            TypeSignature::Coercible(coercions) => coercions
1004                .iter()
1005                .map(|c| {
1006                    let mut all_types: IndexSet<NativeType> = c
1007                        .desired_type()
1008                        .get_representative_types()
1009                        .into_iter()
1010                        .collect();
1011
1012                    if let Some(implicit_coercion) = c.implicit_coercion() {
1013                        let allowed_casts: Vec<NativeType> = implicit_coercion
1014                            .allowed_source_types
1015                            .iter()
1016                            .flat_map(|t| t.get_representative_types())
1017                            .collect();
1018                        all_types.extend(allowed_casts);
1019                    }
1020
1021                    all_types.into_iter().collect::<Vec<_>>()
1022                })
1023                .multi_cartesian_product()
1024                .collect(),
1025            TypeSignature::Variadic(types) => types
1026                .iter()
1027                .cloned()
1028                .map(|data_type| vec![data_type.into()])
1029                .collect(),
1030            TypeSignature::Numeric(arg_count) => TypeSignatureClass::Numeric
1031                .get_representative_types()
1032                .into_iter()
1033                .map(|t| vec![t; *arg_count])
1034                .collect(),
1035            TypeSignature::String(arg_count) => {
1036                vec![vec![NativeType::String; *arg_count]]
1037            }
1038            // TODO: Implement for other types
1039            TypeSignature::Any(_)
1040            | TypeSignature::Comparable(_)
1041            | TypeSignature::Nullary
1042            | TypeSignature::VariadicAny
1043            | TypeSignature::ArraySignature(_)
1044            | TypeSignature::UserDefined => vec![],
1045        }
1046    }
1047}
1048
1049// Deprecated, remove with get_data_types
1050fn get_data_types(native_type: &NativeType) -> Vec<DataType> {
1051    match native_type {
1052        NativeType::Null => vec![DataType::Null],
1053        NativeType::Boolean => vec![DataType::Boolean],
1054        NativeType::Int8 => vec![DataType::Int8],
1055        NativeType::Int16 => vec![DataType::Int16],
1056        NativeType::Int32 => vec![DataType::Int32],
1057        NativeType::Int64 => vec![DataType::Int64],
1058        NativeType::UInt8 => vec![DataType::UInt8],
1059        NativeType::UInt16 => vec![DataType::UInt16],
1060        NativeType::UInt32 => vec![DataType::UInt32],
1061        NativeType::UInt64 => vec![DataType::UInt64],
1062        NativeType::Float16 => vec![DataType::Float16],
1063        NativeType::Float32 => vec![DataType::Float32],
1064        NativeType::Float64 => vec![DataType::Float64],
1065        NativeType::Date => vec![DataType::Date32, DataType::Date64],
1066        NativeType::Binary => vec![
1067            DataType::Binary,
1068            DataType::LargeBinary,
1069            DataType::BinaryView,
1070        ],
1071        NativeType::String => {
1072            vec![DataType::Utf8, DataType::LargeUtf8, DataType::Utf8View]
1073        }
1074        NativeType::Decimal(precision, scale) => {
1075            // We assume incoming NativeType is valid already, in terms of precision & scale
1076            let mut types = vec![DataType::Decimal256(*precision, *scale)];
1077            if *precision <= DECIMAL32_MAX_PRECISION {
1078                types.push(DataType::Decimal32(*precision, *scale));
1079            }
1080            if *precision <= DECIMAL64_MAX_PRECISION {
1081                types.push(DataType::Decimal64(*precision, *scale));
1082            }
1083            if *precision <= DECIMAL128_MAX_PRECISION {
1084                types.push(DataType::Decimal128(*precision, *scale));
1085            }
1086            types
1087        }
1088        NativeType::Timestamp(time_unit, timezone) => {
1089            vec![DataType::Timestamp(*time_unit, timezone.to_owned())]
1090        }
1091        NativeType::Time(TimeUnit::Second) => vec![DataType::Time32(TimeUnit::Second)],
1092        NativeType::Time(TimeUnit::Millisecond) => {
1093            vec![DataType::Time32(TimeUnit::Millisecond)]
1094        }
1095        NativeType::Time(TimeUnit::Microsecond) => {
1096            vec![DataType::Time64(TimeUnit::Microsecond)]
1097        }
1098        NativeType::Time(TimeUnit::Nanosecond) => {
1099            vec![DataType::Time64(TimeUnit::Nanosecond)]
1100        }
1101        NativeType::Duration(time_unit) => vec![DataType::Duration(*time_unit)],
1102        NativeType::Interval(interval_unit) => vec![DataType::Interval(*interval_unit)],
1103        NativeType::FixedSizeBinary(size) => vec![DataType::FixedSizeBinary(*size)],
1104        NativeType::FixedSizeList(logical_field, size) => {
1105            get_data_types(logical_field.logical_type.native())
1106                .iter()
1107                .map(|child_dt| {
1108                    let field = Field::new(
1109                        logical_field.name.clone(),
1110                        child_dt.clone(),
1111                        logical_field.nullable,
1112                    );
1113                    DataType::FixedSizeList(Arc::new(field), *size)
1114                })
1115                .collect()
1116        }
1117        // TODO: implement for nested types
1118        NativeType::List(_)
1119        | NativeType::Struct(_)
1120        | NativeType::Union(_)
1121        | NativeType::Map(_) => {
1122            vec![]
1123        }
1124    }
1125}
1126
1127/// Represents type coercion rules for function arguments, specifying both the desired type
1128/// and optional implicit coercion rules for source types.
1129///
1130/// # Examples
1131///
1132/// ```
1133/// use datafusion_common::types::{logical_binary, logical_string};
1134/// use datafusion_expr_common::signature::{Coercion, TypeSignatureClass};
1135///
1136/// // Exact coercion that only accepts timestamp types
1137/// let exact = Coercion::new_exact(TypeSignatureClass::Timestamp);
1138///
1139/// // Implicit coercion that accepts string types but can coerce from binary types
1140/// let implicit = Coercion::new_implicit_native(
1141///     logical_string(),
1142///     vec![TypeSignatureClass::Native(logical_binary())],
1143/// );
1144/// ```
1145///
1146/// There are two variants:
1147///
1148/// * `Exact` - Only accepts arguments that exactly match the desired type
1149/// * `Implicit` - Accepts the desired type and can coerce from specified source types
1150#[derive(Debug, Clone, Eq, PartialOrd)]
1151pub enum Coercion {
1152    /// Coercion that only accepts arguments exactly matching the desired type.
1153    Exact {
1154        /// The required type for the argument
1155        desired_type: TypeSignatureClass,
1156        /// Physical encoding preservation requested by the function.
1157        encoding_preservation: EncodingPreservation,
1158    },
1159
1160    /// Coercion that accepts the desired type and can implicitly coerce from other types.
1161    Implicit {
1162        /// The primary desired type for the argument
1163        desired_type: TypeSignatureClass,
1164        /// Rules for implicit coercion from other types
1165        implicit_coercion: ImplicitCoercion,
1166        /// Physical encoding preservation requested by the function.
1167        encoding_preservation: EncodingPreservation,
1168    },
1169}
1170
1171/// Controls whether a [`Coercion`] preserves an argument's physical encoding
1172/// (e.g. dictionary) instead of materializing it to the coerced value type.
1173#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Hash)]
1174pub struct EncodingPreservation {
1175    preserve_dictionary: bool,
1176}
1177
1178impl EncodingPreservation {
1179    /// Preserve dictionary encoding and coerce only the dictionary values.
1180    pub const fn dictionary() -> Self {
1181        Self {
1182            preserve_dictionary: true,
1183        }
1184    }
1185
1186    /// Preserve dictionary encoding and coerce only the dictionary values.
1187    pub const fn with_dictionary(mut self) -> Self {
1188        self.preserve_dictionary = true;
1189        self
1190    }
1191
1192    /// Returns whether dictionary encoding should be preserved.
1193    pub const fn preserve_dictionary(self) -> bool {
1194        self.preserve_dictionary
1195    }
1196}
1197
1198impl Coercion {
1199    pub fn new_exact(desired_type: TypeSignatureClass) -> Self {
1200        Self::Exact {
1201            desired_type,
1202            encoding_preservation: EncodingPreservation::default(),
1203        }
1204    }
1205
1206    /// Create a new coercion with implicit coercion rules.
1207    ///
1208    /// `allowed_source_types` defines the possible types that can be coerced to `desired_type`.
1209    /// `default_casted_type` is the default type to be used for coercion if we cast from other types via `allowed_source_types`.
1210    pub fn new_implicit(
1211        desired_type: TypeSignatureClass,
1212        allowed_source_types: Vec<TypeSignatureClass>,
1213        default_casted_type: NativeType,
1214    ) -> Self {
1215        Self::Implicit {
1216            desired_type,
1217            implicit_coercion: ImplicitCoercion {
1218                allowed_source_types,
1219                default_casted_type,
1220            },
1221            encoding_preservation: EncodingPreservation::default(),
1222        }
1223    }
1224
1225    /// Create a new coercion to a native logical type with implicit coercion rules.
1226    ///
1227    /// This is a convenience method for coercing to a specific logical type,
1228    /// avoiding the need to separately pass the matching native default cast type.
1229    ///
1230    /// The native type of `desired_type` is used as the default type when coercing
1231    /// from `allowed_source_types`.
1232    pub fn new_implicit_native(
1233        desired_type: LogicalTypeRef,
1234        allowed_source_types: Vec<TypeSignatureClass>,
1235    ) -> Self {
1236        let default_casted_type = desired_type.native().clone();
1237        Self::new_implicit(
1238            TypeSignatureClass::Native(desired_type),
1239            allowed_source_types,
1240            default_casted_type,
1241        )
1242    }
1243
1244    pub fn with_encoding_preservation(
1245        mut self,
1246        encoding_preservation: EncodingPreservation,
1247    ) -> Self {
1248        match &mut self {
1249            Coercion::Exact {
1250                encoding_preservation: current,
1251                ..
1252            }
1253            | Coercion::Implicit {
1254                encoding_preservation: current,
1255                ..
1256            } => *current = encoding_preservation,
1257        }
1258        self
1259    }
1260
1261    pub fn encoding_preservation(&self) -> EncodingPreservation {
1262        match self {
1263            Coercion::Exact {
1264                encoding_preservation,
1265                ..
1266            }
1267            | Coercion::Implicit {
1268                encoding_preservation,
1269                ..
1270            } => *encoding_preservation,
1271        }
1272    }
1273
1274    pub fn allowed_source_types(&self) -> &[TypeSignatureClass] {
1275        match self {
1276            Coercion::Exact { .. } => &[],
1277            Coercion::Implicit {
1278                implicit_coercion, ..
1279            } => implicit_coercion.allowed_source_types.as_slice(),
1280        }
1281    }
1282
1283    pub fn default_casted_type(&self) -> Option<&NativeType> {
1284        match self {
1285            Coercion::Exact { .. } => None,
1286            Coercion::Implicit {
1287                implicit_coercion, ..
1288            } => Some(&implicit_coercion.default_casted_type),
1289        }
1290    }
1291
1292    pub fn desired_type(&self) -> &TypeSignatureClass {
1293        match self {
1294            Coercion::Exact { desired_type, .. } => desired_type,
1295            Coercion::Implicit { desired_type, .. } => desired_type,
1296        }
1297    }
1298
1299    pub fn implicit_coercion(&self) -> Option<&ImplicitCoercion> {
1300        match self {
1301            Coercion::Exact { .. } => None,
1302            Coercion::Implicit {
1303                implicit_coercion, ..
1304            } => Some(implicit_coercion),
1305        }
1306    }
1307}
1308
1309impl Display for Coercion {
1310    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1311        write!(f, "{}", self.desired_type())
1312    }
1313}
1314
1315impl PartialEq for Coercion {
1316    fn eq(&self, other: &Self) -> bool {
1317        self.desired_type() == other.desired_type()
1318            && self.implicit_coercion() == other.implicit_coercion()
1319            && self.encoding_preservation() == other.encoding_preservation()
1320    }
1321}
1322
1323impl Hash for Coercion {
1324    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1325        self.desired_type().hash(state);
1326        self.implicit_coercion().hash(state);
1327        self.encoding_preservation().hash(state);
1328    }
1329}
1330
1331/// Defines rules for implicit type coercion, specifying which source types can be
1332/// coerced and the default type to use when coercing.
1333///
1334/// This is used by functions to specify which types they can accept via implicit
1335/// coercion in addition to their primary desired type.
1336///
1337/// # Examples
1338///
1339/// ```
1340/// use arrow::datatypes::TimeUnit;
1341///
1342/// use datafusion_expr_common::signature::{Coercion, ImplicitCoercion, TypeSignatureClass};
1343/// use datafusion_common::types::{NativeType, logical_binary};
1344///
1345/// // Allow coercing from binary types to timestamp, coerce to specific timestamp unit and timezone
1346/// let implicit = Coercion::new_implicit(
1347///     TypeSignatureClass::Timestamp,
1348///     vec![TypeSignatureClass::Native(logical_binary())],
1349///     NativeType::Timestamp(TimeUnit::Second, None),
1350/// );
1351/// ```
1352#[derive(Debug, Clone, Eq, PartialOrd)]
1353pub struct ImplicitCoercion {
1354    /// The types that can be coerced from via implicit casting
1355    allowed_source_types: Vec<TypeSignatureClass>,
1356
1357    /// The default type to use when coercing from allowed source types.
1358    /// This is particularly important for types like Timestamp that have multiple
1359    /// possible configurations (different time units and timezones).
1360    default_casted_type: NativeType,
1361}
1362
1363impl Display for ImplicitCoercion {
1364    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1365        write!(f, "ImplicitCoercion(")?;
1366        for (i, source_type) in self.allowed_source_types.iter().enumerate() {
1367            if i > 0 {
1368                write!(f, ", ")?;
1369            }
1370            write!(f, "{source_type}")?;
1371        }
1372        write!(f, "; default={}", self.default_casted_type)
1373    }
1374}
1375
1376impl PartialEq for ImplicitCoercion {
1377    fn eq(&self, other: &Self) -> bool {
1378        self.allowed_source_types == other.allowed_source_types
1379            && self.default_casted_type == other.default_casted_type
1380    }
1381}
1382
1383impl Hash for ImplicitCoercion {
1384    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1385        self.allowed_source_types.hash(state);
1386        self.default_casted_type.hash(state);
1387    }
1388}
1389
1390/// Provides  information necessary for calling a function.
1391///
1392/// - [`TypeSignature`] defines the argument types that a function has implementations
1393///   for.
1394///
1395/// - [`Volatility`] defines how the output of the function changes with the input.
1396#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
1397pub struct Signature {
1398    /// The data types that the function accepts. See [TypeSignature] for more information.
1399    pub type_signature: TypeSignature,
1400    /// The volatility of the function. See [Volatility] for more information.
1401    pub volatility: Volatility,
1402    /// Optional parameter names for the function arguments.
1403    ///
1404    /// If provided, enables named argument notation for function calls (e.g., `func(a => 1, b => 2)`).
1405    /// The length must match the number of arguments defined by `type_signature`.
1406    ///
1407    /// Defaults to `None`, meaning only positional arguments are supported.
1408    pub parameter_names: Option<Vec<String>>,
1409}
1410
1411impl Signature {
1412    /// Creates a new Signature from a given type signature and volatility.
1413    pub fn new(type_signature: TypeSignature, volatility: Volatility) -> Self {
1414        Signature {
1415            type_signature,
1416            volatility,
1417            parameter_names: None,
1418        }
1419    }
1420    /// An arbitrary number of arguments with the same type, from those listed in `common_types`.
1421    pub fn variadic(common_types: Vec<DataType>, volatility: Volatility) -> Self {
1422        Self {
1423            type_signature: TypeSignature::Variadic(common_types),
1424            volatility,
1425            parameter_names: None,
1426        }
1427    }
1428    /// User-defined coercion rules for the function.
1429    pub fn user_defined(volatility: Volatility) -> Self {
1430        Self {
1431            type_signature: TypeSignature::UserDefined,
1432            volatility,
1433            parameter_names: None,
1434        }
1435    }
1436
1437    /// A specified number of numeric arguments
1438    pub fn numeric(arg_count: usize, volatility: Volatility) -> Self {
1439        Self {
1440            type_signature: TypeSignature::Numeric(arg_count),
1441            volatility,
1442            parameter_names: None,
1443        }
1444    }
1445
1446    /// A specified number of string arguments
1447    pub fn string(arg_count: usize, volatility: Volatility) -> Self {
1448        Self {
1449            type_signature: TypeSignature::String(arg_count),
1450            volatility,
1451            parameter_names: None,
1452        }
1453    }
1454
1455    /// An arbitrary number of arguments of any type.
1456    pub fn variadic_any(volatility: Volatility) -> Self {
1457        Self {
1458            type_signature: TypeSignature::VariadicAny,
1459            volatility,
1460            parameter_names: None,
1461        }
1462    }
1463    /// A fixed number of arguments of the same type, from those listed in `valid_types`.
1464    pub fn uniform(
1465        arg_count: usize,
1466        valid_types: Vec<DataType>,
1467        volatility: Volatility,
1468    ) -> Self {
1469        Self {
1470            type_signature: TypeSignature::Uniform(arg_count, valid_types),
1471            volatility,
1472            parameter_names: None,
1473        }
1474    }
1475    /// Exactly matches the types in `exact_types`, in order.
1476    pub fn exact(exact_types: Vec<DataType>, volatility: Volatility) -> Self {
1477        Signature {
1478            type_signature: TypeSignature::Exact(exact_types),
1479            volatility,
1480            parameter_names: None,
1481        }
1482    }
1483
1484    /// Target coerce types in order
1485    pub fn coercible(target_types: Vec<Coercion>, volatility: Volatility) -> Self {
1486        Self {
1487            type_signature: TypeSignature::Coercible(target_types),
1488            volatility,
1489            parameter_names: None,
1490        }
1491    }
1492
1493    /// Used for function that expects comparable data types, it will try to coerced all the types into single final one.
1494    pub fn comparable(arg_count: usize, volatility: Volatility) -> Self {
1495        Self {
1496            type_signature: TypeSignature::Comparable(arg_count),
1497            volatility,
1498            parameter_names: None,
1499        }
1500    }
1501
1502    pub fn nullary(volatility: Volatility) -> Self {
1503        Signature {
1504            type_signature: TypeSignature::Nullary,
1505            volatility,
1506            parameter_names: None,
1507        }
1508    }
1509
1510    /// A specified number of arguments of any type
1511    pub fn any(arg_count: usize, volatility: Volatility) -> Self {
1512        Signature {
1513            type_signature: TypeSignature::Any(arg_count),
1514            volatility,
1515            parameter_names: None,
1516        }
1517    }
1518
1519    /// Any one of a list of [TypeSignature]s.
1520    pub fn one_of(type_signatures: Vec<TypeSignature>, volatility: Volatility) -> Self {
1521        Signature {
1522            type_signature: TypeSignature::OneOf(type_signatures),
1523            volatility,
1524            parameter_names: None,
1525        }
1526    }
1527
1528    /// Specialized [Signature] for ArrayAppend and similar functions.
1529    pub fn array_and_element(volatility: Volatility) -> Self {
1530        Signature {
1531            type_signature: TypeSignature::ArraySignature(
1532                ArrayFunctionSignature::Array {
1533                    arguments: vec![
1534                        ArrayFunctionArgument::Array,
1535                        ArrayFunctionArgument::Element,
1536                    ],
1537                    array_coercion: Some(ListCoercion::FixedSizedListToList),
1538                },
1539            ),
1540            volatility,
1541            parameter_names: None,
1542        }
1543    }
1544
1545    /// Specialized [Signature] for ArrayPrepend and similar functions.
1546    pub fn element_and_array(volatility: Volatility) -> Self {
1547        Signature {
1548            type_signature: TypeSignature::ArraySignature(
1549                ArrayFunctionSignature::Array {
1550                    arguments: vec![
1551                        ArrayFunctionArgument::Element,
1552                        ArrayFunctionArgument::Array,
1553                    ],
1554                    array_coercion: Some(ListCoercion::FixedSizedListToList),
1555                },
1556            ),
1557            volatility,
1558            parameter_names: None,
1559        }
1560    }
1561
1562    /// Specialized [Signature] for functions that take a fixed number of arrays.
1563    pub fn arrays(
1564        n: usize,
1565        coercion: Option<ListCoercion>,
1566        volatility: Volatility,
1567    ) -> Self {
1568        Signature {
1569            type_signature: TypeSignature::ArraySignature(
1570                ArrayFunctionSignature::Array {
1571                    arguments: vec![ArrayFunctionArgument::Array; n],
1572                    array_coercion: coercion,
1573                },
1574            ),
1575            volatility,
1576            parameter_names: None,
1577        }
1578    }
1579
1580    /// Specialized [Signature] for Array functions with an optional index.
1581    pub fn array_and_element_and_optional_index(volatility: Volatility) -> Self {
1582        Signature {
1583            type_signature: TypeSignature::OneOf(vec![
1584                TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
1585                    arguments: vec![
1586                        ArrayFunctionArgument::Array,
1587                        ArrayFunctionArgument::Element,
1588                    ],
1589                    array_coercion: Some(ListCoercion::FixedSizedListToList),
1590                }),
1591                TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
1592                    arguments: vec![
1593                        ArrayFunctionArgument::Array,
1594                        ArrayFunctionArgument::Element,
1595                        ArrayFunctionArgument::Index,
1596                    ],
1597                    array_coercion: Some(ListCoercion::FixedSizedListToList),
1598                }),
1599            ]),
1600            volatility,
1601            parameter_names: None,
1602        }
1603    }
1604
1605    /// Specialized [Signature] for ArrayElement and similar functions.
1606    pub fn array_and_index(volatility: Volatility) -> Self {
1607        Signature {
1608            type_signature: TypeSignature::ArraySignature(
1609                ArrayFunctionSignature::Array {
1610                    arguments: vec![
1611                        ArrayFunctionArgument::Array,
1612                        ArrayFunctionArgument::Index,
1613                    ],
1614                    array_coercion: Some(ListCoercion::FixedSizedListToList),
1615                },
1616            ),
1617            volatility,
1618            parameter_names: None,
1619        }
1620    }
1621
1622    /// Specialized [Signature] for ArrayEmpty and similar functions.
1623    pub fn array(volatility: Volatility) -> Self {
1624        Signature::arrays(1, Some(ListCoercion::FixedSizedListToList), volatility)
1625    }
1626
1627    /// Add parameter names to this signature, enabling named argument notation.
1628    ///
1629    /// # Example
1630    /// ```
1631    /// # use datafusion_expr_common::signature::{Signature, Volatility};
1632    /// # use arrow::datatypes::DataType;
1633    /// let sig =
1634    ///     Signature::exact(vec![DataType::Int32, DataType::Utf8], Volatility::Immutable)
1635    ///         .with_parameter_names(vec!["count".to_string(), "name".to_string()]);
1636    /// ```
1637    ///
1638    /// # Errors
1639    /// Returns an error if the number of parameter names doesn't match the signature's arity.
1640    /// For signatures with variable arity (e.g., `Variadic`, `VariadicAny`), parameter names
1641    /// cannot be specified.
1642    pub fn with_parameter_names(mut self, names: Vec<impl Into<String>>) -> Result<Self> {
1643        let names = names.into_iter().map(Into::into).collect::<Vec<String>>();
1644        // Validate that the number of names matches the signature
1645        self.validate_parameter_names(&names)?;
1646        self.parameter_names = Some(names);
1647        Ok(self)
1648    }
1649
1650    /// Validate that parameter names are compatible with this signature
1651    fn validate_parameter_names(&self, names: &[String]) -> Result<()> {
1652        match self.type_signature.arity() {
1653            Arity::Fixed(expected) => {
1654                if names.len() != expected {
1655                    return plan_err!(
1656                        "Parameter names count ({}) does not match signature arity ({})",
1657                        names.len(),
1658                        expected
1659                    );
1660                }
1661            }
1662            Arity::Variable => {
1663                // For UserDefined signatures, allow parameter names
1664                // The function implementer is responsible for validating the names match the actual arguments
1665                if self.type_signature != TypeSignature::UserDefined {
1666                    return plan_err!(
1667                        "Cannot specify parameter names for variable arity signature: {:?}",
1668                        self.type_signature
1669                    );
1670                }
1671            }
1672        }
1673
1674        let mut seen = std::collections::HashSet::with_capacity(names.len());
1675        for name in names {
1676            if !seen.insert(name) {
1677                return plan_err!("Duplicate parameter name: '{}'", name);
1678            }
1679        }
1680
1681        Ok(())
1682    }
1683}
1684
1685#[cfg(test)]
1686mod tests {
1687    use datafusion_common::types::{
1688        NativeType, logical_float64, logical_int32, logical_int64, logical_string,
1689    };
1690
1691    use super::*;
1692    use crate::signature::{
1693        ArrayFunctionArgument, ArrayFunctionSignature, Coercion, TypeSignatureClass,
1694    };
1695
1696    #[test]
1697    fn supports_zero_argument_tests() {
1698        // Testing `TypeSignature`s which supports 0 arg
1699        let positive_cases = vec![
1700            TypeSignature::Exact(vec![]),
1701            TypeSignature::OneOf(vec![
1702                TypeSignature::Exact(vec![DataType::Int8]),
1703                TypeSignature::Nullary,
1704                TypeSignature::Uniform(1, vec![DataType::Int8]),
1705            ]),
1706            TypeSignature::Nullary,
1707        ];
1708
1709        for case in positive_cases {
1710            assert!(
1711                case.supports_zero_argument(),
1712                "Expected {case:?} to support zero arguments"
1713            );
1714        }
1715
1716        // Testing `TypeSignature`s which doesn't support 0 arg
1717        let negative_cases = vec![
1718            TypeSignature::Exact(vec![DataType::Utf8]),
1719            TypeSignature::Uniform(1, vec![DataType::Float64]),
1720            TypeSignature::Any(1),
1721            TypeSignature::VariadicAny,
1722            TypeSignature::OneOf(vec![
1723                TypeSignature::Exact(vec![DataType::Int8]),
1724                TypeSignature::Uniform(1, vec![DataType::Int8]),
1725            ]),
1726        ];
1727
1728        for case in negative_cases {
1729            assert!(
1730                !case.supports_zero_argument(),
1731                "Expected {case:?} not to support zero arguments"
1732            );
1733        }
1734    }
1735
1736    #[test]
1737    fn type_signature_partial_ord() {
1738        // Test validates that partial ord is defined for TypeSignature and Signature.
1739        assert!(TypeSignature::UserDefined < TypeSignature::VariadicAny);
1740        assert!(TypeSignature::UserDefined < TypeSignature::Any(1));
1741
1742        assert!(
1743            TypeSignature::Uniform(1, vec![DataType::Null])
1744                < TypeSignature::Uniform(1, vec![DataType::Boolean])
1745        );
1746        assert!(
1747            TypeSignature::Uniform(1, vec![DataType::Null])
1748                < TypeSignature::Uniform(2, vec![DataType::Null])
1749        );
1750        assert!(
1751            TypeSignature::Uniform(usize::MAX, vec![DataType::Null])
1752                < TypeSignature::Exact(vec![DataType::Null])
1753        );
1754    }
1755
1756    // Remove with get_example_types
1757    #[test]
1758    #[expect(deprecated)]
1759    fn test_get_example_types() {
1760        let type_signature = TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]);
1761        let possible_types = type_signature.get_example_types();
1762        assert_eq!(possible_types, vec![vec![DataType::Int32, DataType::Int64]]);
1763
1764        let type_signature = TypeSignature::OneOf(vec![
1765            TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]),
1766            TypeSignature::Exact(vec![DataType::Float32, DataType::Float64]),
1767        ]);
1768        let possible_types = type_signature.get_example_types();
1769        assert_eq!(
1770            possible_types,
1771            vec![
1772                vec![DataType::Int32, DataType::Int64],
1773                vec![DataType::Float32, DataType::Float64]
1774            ]
1775        );
1776
1777        let type_signature = TypeSignature::OneOf(vec![
1778            TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]),
1779            TypeSignature::Exact(vec![DataType::Float32, DataType::Float64]),
1780            TypeSignature::Exact(vec![DataType::Utf8]),
1781        ]);
1782        let possible_types = type_signature.get_example_types();
1783        assert_eq!(
1784            possible_types,
1785            vec![
1786                vec![DataType::Int32, DataType::Int64],
1787                vec![DataType::Float32, DataType::Float64],
1788                vec![DataType::Utf8]
1789            ]
1790        );
1791
1792        let type_signature =
1793            TypeSignature::Uniform(2, vec![DataType::Float32, DataType::Int64]);
1794        let possible_types = type_signature.get_example_types();
1795        assert_eq!(
1796            possible_types,
1797            vec![
1798                vec![DataType::Float32, DataType::Float32],
1799                vec![DataType::Int64, DataType::Int64]
1800            ]
1801        );
1802
1803        let type_signature = TypeSignature::Coercible(vec![
1804            Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
1805            Coercion::new_exact(TypeSignatureClass::Native(logical_int64())),
1806        ]);
1807        let possible_types = type_signature.get_example_types();
1808        assert_eq!(
1809            possible_types,
1810            vec![
1811                vec![DataType::Utf8, DataType::Int64],
1812                vec![DataType::LargeUtf8, DataType::Int64],
1813                vec![DataType::Utf8View, DataType::Int64]
1814            ]
1815        );
1816
1817        let type_signature =
1818            TypeSignature::Variadic(vec![DataType::Int32, DataType::Int64]);
1819        let possible_types = type_signature.get_example_types();
1820        assert_eq!(
1821            possible_types,
1822            vec![vec![DataType::Int32], vec![DataType::Int64]]
1823        );
1824
1825        let type_signature = TypeSignature::Numeric(2);
1826        let possible_types = type_signature.get_example_types();
1827        assert_eq!(
1828            possible_types,
1829            vec![
1830                vec![DataType::Int8, DataType::Int8],
1831                vec![DataType::Int16, DataType::Int16],
1832                vec![DataType::Int32, DataType::Int32],
1833                vec![DataType::Int64, DataType::Int64],
1834                vec![DataType::UInt8, DataType::UInt8],
1835                vec![DataType::UInt16, DataType::UInt16],
1836                vec![DataType::UInt32, DataType::UInt32],
1837                vec![DataType::UInt64, DataType::UInt64],
1838                vec![DataType::Float16, DataType::Float16],
1839                vec![DataType::Float32, DataType::Float32],
1840                vec![DataType::Float64, DataType::Float64]
1841            ]
1842        );
1843
1844        let type_signature = TypeSignature::String(2);
1845        let possible_types = type_signature.get_example_types();
1846        assert_eq!(
1847            possible_types,
1848            vec![
1849                vec![DataType::Utf8, DataType::Utf8],
1850                vec![DataType::LargeUtf8, DataType::LargeUtf8],
1851                vec![DataType::Utf8View, DataType::Utf8View]
1852            ]
1853        );
1854    }
1855
1856    #[test]
1857    fn test_get_representative_types() {
1858        let type_signature = TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]);
1859        let types = type_signature.get_representative_types();
1860        assert_eq!(types, vec![vec![NativeType::Int32, NativeType::Int64]]);
1861
1862        let type_signature = TypeSignature::OneOf(vec![
1863            TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]),
1864            TypeSignature::Exact(vec![DataType::Float32, DataType::Float64]),
1865        ]);
1866        let types = type_signature.get_representative_types();
1867        assert_eq!(
1868            types,
1869            vec![
1870                vec![NativeType::Int32, NativeType::Int64],
1871                vec![NativeType::Float32, NativeType::Float64]
1872            ]
1873        );
1874
1875        let type_signature = TypeSignature::OneOf(vec![
1876            TypeSignature::Exact(vec![DataType::Int32, DataType::Int64]),
1877            TypeSignature::Exact(vec![DataType::Float32, DataType::Float64]),
1878            TypeSignature::Exact(vec![DataType::Utf8]),
1879        ]);
1880        let types = type_signature.get_representative_types();
1881        assert_eq!(
1882            types,
1883            vec![
1884                vec![NativeType::Int32, NativeType::Int64],
1885                vec![NativeType::Float32, NativeType::Float64],
1886                vec![NativeType::String]
1887            ]
1888        );
1889
1890        let type_signature =
1891            TypeSignature::Uniform(2, vec![DataType::Float32, DataType::Int64]);
1892        let types = type_signature.get_representative_types();
1893        assert_eq!(
1894            types,
1895            vec![
1896                vec![NativeType::Float32, NativeType::Float32],
1897                vec![NativeType::Int64, NativeType::Int64]
1898            ]
1899        );
1900
1901        let type_signature = TypeSignature::Coercible(vec![
1902            Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
1903            Coercion::new_exact(TypeSignatureClass::Native(logical_int64())),
1904        ]);
1905        let types = type_signature.get_representative_types();
1906        assert_eq!(types, vec![vec![NativeType::String, NativeType::Int64]]);
1907
1908        let type_signature =
1909            TypeSignature::Variadic(vec![DataType::Int32, DataType::Int64]);
1910        let types = type_signature.get_representative_types();
1911        assert_eq!(
1912            types,
1913            vec![vec![NativeType::Int32], vec![NativeType::Int64]]
1914        );
1915
1916        let type_signature = TypeSignature::Numeric(2);
1917        let types = type_signature.get_representative_types();
1918        assert_eq!(
1919            types,
1920            vec![
1921                vec![NativeType::Float64, NativeType::Float64],
1922                vec![NativeType::Int64, NativeType::Int64],
1923                vec![
1924                    Decimal128Type::DEFAULT_TYPE.into(),
1925                    Decimal128Type::DEFAULT_TYPE.into()
1926                ],
1927            ]
1928        );
1929
1930        let type_signature = TypeSignature::String(2);
1931        let possible_types = type_signature.get_representative_types();
1932        assert_eq!(
1933            possible_types,
1934            vec![vec![NativeType::String, NativeType::String],]
1935        );
1936    }
1937
1938    #[test]
1939    fn test_signature_with_parameter_names() {
1940        let sig = Signature::exact(
1941            vec![DataType::Int32, DataType::Utf8],
1942            Volatility::Immutable,
1943        )
1944        .with_parameter_names(vec!["count".to_string(), "name".to_string()])
1945        .unwrap();
1946
1947        assert_eq!(
1948            sig.parameter_names,
1949            Some(vec!["count".to_string(), "name".to_string()])
1950        );
1951        assert_eq!(
1952            sig.type_signature,
1953            TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8])
1954        );
1955    }
1956
1957    #[test]
1958    fn test_signature_parameter_names_wrong_count() {
1959        let result = Signature::exact(
1960            vec![DataType::Int32, DataType::Utf8],
1961            Volatility::Immutable,
1962        )
1963        .with_parameter_names(vec!["count".to_string()]); // Only 1 name for 2 args
1964
1965        assert!(result.is_err());
1966        assert!(
1967            result
1968                .unwrap_err()
1969                .to_string()
1970                .contains("does not match signature arity")
1971        );
1972    }
1973
1974    #[test]
1975    fn test_signature_parameter_names_duplicate() {
1976        let result = Signature::exact(
1977            vec![DataType::Int32, DataType::Int32],
1978            Volatility::Immutable,
1979        )
1980        .with_parameter_names(vec!["count".to_string(), "count".to_string()]);
1981
1982        assert!(result.is_err());
1983        assert!(
1984            result
1985                .unwrap_err()
1986                .to_string()
1987                .contains("Duplicate parameter name")
1988        );
1989    }
1990
1991    #[test]
1992    fn test_signature_parameter_names_variadic() {
1993        let result = Signature::variadic(vec![DataType::Int32], Volatility::Immutable)
1994            .with_parameter_names(vec!["arg".to_string()]);
1995
1996        assert!(result.is_err());
1997        assert!(
1998            result
1999                .unwrap_err()
2000                .to_string()
2001                .contains("variable arity signature")
2002        );
2003    }
2004
2005    #[test]
2006    fn test_signature_without_parameter_names() {
2007        let sig = Signature::exact(
2008            vec![DataType::Int32, DataType::Utf8],
2009            Volatility::Immutable,
2010        );
2011
2012        assert_eq!(sig.parameter_names, None);
2013    }
2014
2015    #[test]
2016    fn test_signature_uniform_with_parameter_names() {
2017        let sig = Signature::uniform(3, vec![DataType::Float64], Volatility::Immutable)
2018            .with_parameter_names(vec!["x".to_string(), "y".to_string(), "z".to_string()])
2019            .unwrap();
2020
2021        assert_eq!(
2022            sig.parameter_names,
2023            Some(vec!["x".to_string(), "y".to_string(), "z".to_string()])
2024        );
2025    }
2026
2027    #[test]
2028    fn test_signature_numeric_with_parameter_names() {
2029        let sig = Signature::numeric(2, Volatility::Immutable)
2030            .with_parameter_names(vec!["a".to_string(), "b".to_string()])
2031            .unwrap();
2032
2033        assert_eq!(
2034            sig.parameter_names,
2035            Some(vec!["a".to_string(), "b".to_string()])
2036        );
2037    }
2038
2039    #[test]
2040    fn test_signature_nullary_with_empty_names() {
2041        let sig = Signature::nullary(Volatility::Immutable)
2042            .with_parameter_names(Vec::<String>::new())
2043            .unwrap();
2044
2045        assert_eq!(sig.parameter_names, Some(vec![]));
2046    }
2047
2048    #[test]
2049    fn test_to_string_repr_with_names_exact() {
2050        let sig = TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]);
2051
2052        assert_eq!(sig.to_string_repr_with_names(None), vec!["Int32, Utf8"]);
2053
2054        let names = vec!["id".to_string(), "name".to_string()];
2055        assert_eq!(
2056            sig.to_string_repr_with_names(Some(&names)),
2057            vec!["id: Int32, name: Utf8"]
2058        );
2059    }
2060
2061    #[test]
2062    fn test_to_string_repr_with_names_any() {
2063        let sig = TypeSignature::Any(3);
2064
2065        assert_eq!(sig.to_string_repr_with_names(None), vec!["Any, Any, Any"]);
2066
2067        let names = vec!["x".to_string(), "y".to_string(), "z".to_string()];
2068        assert_eq!(
2069            sig.to_string_repr_with_names(Some(&names)),
2070            vec!["x: Any, y: Any, z: Any"]
2071        );
2072    }
2073
2074    #[test]
2075    fn test_to_string_repr_with_names_one_of() {
2076        let sig =
2077            TypeSignature::OneOf(vec![TypeSignature::Any(2), TypeSignature::Any(3)]);
2078
2079        assert_eq!(
2080            sig.to_string_repr_with_names(None),
2081            vec!["Any, Any", "Any, Any, Any"]
2082        );
2083
2084        let names = vec![
2085            "str".to_string(),
2086            "start_pos".to_string(),
2087            "length".to_string(),
2088        ];
2089        assert_eq!(
2090            sig.to_string_repr_with_names(Some(&names)),
2091            vec![
2092                "str: Any, start_pos: Any",
2093                "str: Any, start_pos: Any, length: Any"
2094            ]
2095        );
2096    }
2097
2098    #[test]
2099    fn test_to_string_repr_with_names_partial() {
2100        // This simulates providing max arity names for a OneOf signature
2101        let sig = TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]);
2102
2103        // Provide 3 names for 2-parameter signature (extra name is ignored via zip)
2104        let names = vec!["a".to_string(), "b".to_string(), "c".to_string()];
2105        assert_eq!(
2106            sig.to_string_repr_with_names(Some(&names)),
2107            vec!["a: Int32, b: Utf8"]
2108        );
2109    }
2110
2111    #[test]
2112    fn test_to_string_repr_with_names_uniform() {
2113        let sig = TypeSignature::Uniform(2, vec![DataType::Float64]);
2114
2115        assert_eq!(
2116            sig.to_string_repr_with_names(None),
2117            vec!["Float64, Float64"]
2118        );
2119
2120        let names = vec!["x".to_string(), "y".to_string()];
2121        assert_eq!(
2122            sig.to_string_repr_with_names(Some(&names)),
2123            vec!["x: Float64, y: Float64"]
2124        );
2125    }
2126
2127    #[test]
2128    fn test_to_string_repr_with_names_coercible() {
2129        let sig = TypeSignature::Coercible(vec![
2130            Coercion::new_exact(TypeSignatureClass::Native(logical_int32())),
2131            Coercion::new_exact(TypeSignatureClass::Native(logical_int32())),
2132        ]);
2133
2134        let names = vec!["a".to_string(), "b".to_string()];
2135        let result = sig.to_string_repr_with_names(Some(&names));
2136        // Check that it contains the parameter names with type annotations
2137        assert_eq!(result.len(), 1);
2138        assert!(result[0].starts_with("a: "));
2139        assert!(result[0].contains(", b: "));
2140    }
2141
2142    #[test]
2143    fn test_to_string_repr_with_names_comparable_numeric_string() {
2144        let comparable = TypeSignature::Comparable(3);
2145        let numeric = TypeSignature::Numeric(2);
2146        let string_sig = TypeSignature::String(2);
2147
2148        let names = vec!["a".to_string(), "b".to_string(), "c".to_string()];
2149
2150        // All should show parameter names with type annotations
2151        assert_eq!(
2152            comparable.to_string_repr_with_names(Some(&names)),
2153            vec!["a: Comparable, b: Comparable, c: Comparable"]
2154        );
2155        assert_eq!(
2156            numeric.to_string_repr_with_names(Some(&names)),
2157            vec!["a: Numeric, b: Numeric"]
2158        );
2159        assert_eq!(
2160            string_sig.to_string_repr_with_names(Some(&names)),
2161            vec!["a: String, b: String"]
2162        );
2163    }
2164
2165    #[test]
2166    fn test_to_string_repr_with_names_variadic_fallback() {
2167        let variadic = TypeSignature::Variadic(vec![DataType::Utf8, DataType::LargeUtf8]);
2168        let names = vec!["x".to_string()];
2169        assert_eq!(
2170            variadic.to_string_repr_with_names(Some(&names)),
2171            variadic.to_string_repr()
2172        );
2173
2174        let variadic_any = TypeSignature::VariadicAny;
2175        assert_eq!(
2176            variadic_any.to_string_repr_with_names(Some(&names)),
2177            variadic_any.to_string_repr()
2178        );
2179
2180        // UserDefined now shows parameter names when available
2181        let user_defined = TypeSignature::UserDefined;
2182        assert_eq!(
2183            user_defined.to_string_repr_with_names(Some(&names)),
2184            vec!["x"]
2185        );
2186        assert_eq!(
2187            user_defined.to_string_repr_with_names(None),
2188            user_defined.to_string_repr()
2189        );
2190    }
2191
2192    #[test]
2193    fn test_to_string_repr_with_names_nullary() {
2194        let sig = TypeSignature::Nullary;
2195        let names = vec!["x".to_string()];
2196
2197        // Should return empty representation, names don't apply
2198        assert_eq!(
2199            sig.to_string_repr_with_names(Some(&names)),
2200            vec!["NullAry()"]
2201        );
2202        assert_eq!(sig.to_string_repr_with_names(None), vec!["NullAry()"]);
2203    }
2204
2205    #[test]
2206    fn test_to_string_repr_with_names_array_signature() {
2207        let sig = TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
2208            arguments: vec![
2209                ArrayFunctionArgument::Array,
2210                ArrayFunctionArgument::Index,
2211                ArrayFunctionArgument::Element,
2212            ],
2213            array_coercion: None,
2214        });
2215
2216        assert_eq!(
2217            sig.to_string_repr_with_names(None),
2218            vec!["array, index, element"]
2219        );
2220
2221        let names = vec!["arr".to_string(), "idx".to_string(), "val".to_string()];
2222        assert_eq!(
2223            sig.to_string_repr_with_names(Some(&names)),
2224            vec!["arr: array, idx: index, val: element"]
2225        );
2226
2227        let recursive =
2228            TypeSignature::ArraySignature(ArrayFunctionSignature::RecursiveArray);
2229        let names = vec!["array".to_string()];
2230        assert_eq!(
2231            recursive.to_string_repr_with_names(Some(&names)),
2232            vec!["array: recursive_array"]
2233        );
2234
2235        // Test MapArray (1 argument)
2236        let map_array = TypeSignature::ArraySignature(ArrayFunctionSignature::MapArray);
2237        let names = vec!["map".to_string()];
2238        assert_eq!(
2239            map_array.to_string_repr_with_names(Some(&names)),
2240            vec!["map: map_array"]
2241        );
2242    }
2243
2244    #[test]
2245    fn test_type_signature_arity_exact() {
2246        let sig = TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]);
2247        assert_eq!(sig.arity(), Arity::Fixed(2));
2248
2249        let sig = TypeSignature::Exact(vec![]);
2250        assert_eq!(sig.arity(), Arity::Fixed(0));
2251    }
2252
2253    #[test]
2254    fn test_type_signature_arity_uniform() {
2255        let sig = TypeSignature::Uniform(3, vec![DataType::Float64]);
2256        assert_eq!(sig.arity(), Arity::Fixed(3));
2257
2258        let sig = TypeSignature::Uniform(1, vec![DataType::Int32]);
2259        assert_eq!(sig.arity(), Arity::Fixed(1));
2260    }
2261
2262    #[test]
2263    fn test_type_signature_arity_numeric() {
2264        let sig = TypeSignature::Numeric(2);
2265        assert_eq!(sig.arity(), Arity::Fixed(2));
2266    }
2267
2268    #[test]
2269    fn test_type_signature_arity_string() {
2270        let sig = TypeSignature::String(3);
2271        assert_eq!(sig.arity(), Arity::Fixed(3));
2272    }
2273
2274    #[test]
2275    fn test_type_signature_arity_comparable() {
2276        let sig = TypeSignature::Comparable(2);
2277        assert_eq!(sig.arity(), Arity::Fixed(2));
2278    }
2279
2280    #[test]
2281    fn test_type_signature_arity_any() {
2282        let sig = TypeSignature::Any(4);
2283        assert_eq!(sig.arity(), Arity::Fixed(4));
2284    }
2285
2286    #[test]
2287    fn test_type_signature_arity_coercible() {
2288        let sig = TypeSignature::Coercible(vec![
2289            Coercion::new_exact(TypeSignatureClass::Native(logical_int32())),
2290            Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
2291        ]);
2292        assert_eq!(sig.arity(), Arity::Fixed(2));
2293    }
2294
2295    #[test]
2296    fn test_type_signature_arity_nullary() {
2297        let sig = TypeSignature::Nullary;
2298        assert_eq!(sig.arity(), Arity::Fixed(0));
2299    }
2300
2301    #[test]
2302    fn test_type_signature_arity_array_signature() {
2303        // Test Array variant with 2 arguments
2304        let sig = TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
2305            arguments: vec![ArrayFunctionArgument::Array, ArrayFunctionArgument::Index],
2306            array_coercion: None,
2307        });
2308        assert_eq!(sig.arity(), Arity::Fixed(2));
2309
2310        // Test Array variant with 3 arguments
2311        let sig = TypeSignature::ArraySignature(ArrayFunctionSignature::Array {
2312            arguments: vec![
2313                ArrayFunctionArgument::Array,
2314                ArrayFunctionArgument::Element,
2315                ArrayFunctionArgument::Index,
2316            ],
2317            array_coercion: None,
2318        });
2319        assert_eq!(sig.arity(), Arity::Fixed(3));
2320
2321        // Test RecursiveArray variant
2322        let sig = TypeSignature::ArraySignature(ArrayFunctionSignature::RecursiveArray);
2323        assert_eq!(sig.arity(), Arity::Fixed(1));
2324
2325        // Test MapArray variant
2326        let sig = TypeSignature::ArraySignature(ArrayFunctionSignature::MapArray);
2327        assert_eq!(sig.arity(), Arity::Fixed(1));
2328    }
2329
2330    #[test]
2331    fn test_type_signature_arity_one_of_fixed() {
2332        // OneOf with all fixed arity variants should return max arity
2333        let sig = TypeSignature::OneOf(vec![
2334            TypeSignature::Exact(vec![DataType::Int32]),
2335            TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]),
2336            TypeSignature::Exact(vec![
2337                DataType::Int32,
2338                DataType::Utf8,
2339                DataType::Float64,
2340            ]),
2341        ]);
2342        assert_eq!(sig.arity(), Arity::Fixed(3));
2343    }
2344
2345    #[test]
2346    fn test_type_signature_arity_one_of_variable() {
2347        // OneOf with variable arity variant should return Variable
2348        let sig = TypeSignature::OneOf(vec![
2349            TypeSignature::Exact(vec![DataType::Int32]),
2350            TypeSignature::VariadicAny,
2351        ]);
2352        assert_eq!(sig.arity(), Arity::Variable);
2353    }
2354
2355    #[test]
2356    fn test_type_signature_arity_variadic() {
2357        let sig = TypeSignature::Variadic(vec![DataType::Int32]);
2358        assert_eq!(sig.arity(), Arity::Variable);
2359
2360        let sig = TypeSignature::VariadicAny;
2361        assert_eq!(sig.arity(), Arity::Variable);
2362    }
2363
2364    #[test]
2365    fn test_type_signature_arity_user_defined() {
2366        let sig = TypeSignature::UserDefined;
2367        assert_eq!(sig.arity(), Arity::Variable);
2368    }
2369
2370    #[test]
2371    fn test_type_signature_display() {
2372        use insta::assert_snapshot;
2373
2374        assert_snapshot!(TypeSignature::Nullary, @"Nullary");
2375        assert_snapshot!(TypeSignature::Any(2), @"Any(2)");
2376        assert_snapshot!(TypeSignature::Numeric(3), @"Numeric(3)");
2377        assert_snapshot!(TypeSignature::String(1), @"String(1)");
2378        assert_snapshot!(TypeSignature::Comparable(2), @"Comparable(2)");
2379        assert_snapshot!(TypeSignature::VariadicAny, @"VariadicAny");
2380        assert_snapshot!(TypeSignature::UserDefined, @"UserDefined");
2381
2382        assert_snapshot!(
2383            TypeSignature::Exact(vec![DataType::Int32, DataType::Utf8]),
2384            @"Exact(Int32, Utf8)"
2385        );
2386        assert_snapshot!(
2387            TypeSignature::Variadic(vec![DataType::Utf8, DataType::LargeUtf8]),
2388            @"Variadic(Utf8, LargeUtf8)"
2389        );
2390        assert_snapshot!(
2391            TypeSignature::Uniform(2, vec![DataType::Float32, DataType::Float64]),
2392            @"Uniform(2, [Float32, Float64])"
2393        );
2394
2395        assert_snapshot!(
2396            TypeSignature::Coercible(vec![
2397                Coercion::new_exact(TypeSignatureClass::Native(logical_float64())),
2398                Coercion::new_exact(TypeSignatureClass::Native(logical_int32())),
2399            ]),
2400            @"Coercible(Float64, Int32)"
2401        );
2402
2403        assert_snapshot!(
2404            TypeSignature::OneOf(vec![
2405                TypeSignature::Nullary,
2406                TypeSignature::VariadicAny,
2407            ]),
2408            @"OneOf(Nullary, VariadicAny)"
2409        );
2410    }
2411
2412    #[test]
2413    fn test_type_signature_class_display() {
2414        use insta::assert_snapshot;
2415
2416        assert_snapshot!(TypeSignatureClass::Any, @"Any");
2417        assert_snapshot!(TypeSignatureClass::Numeric, @"Numeric");
2418        assert_snapshot!(TypeSignatureClass::Integer, @"Integer");
2419        assert_snapshot!(TypeSignatureClass::Float, @"Float");
2420        assert_snapshot!(TypeSignatureClass::Decimal, @"Decimal");
2421        assert_snapshot!(TypeSignatureClass::Timestamp, @"Timestamp");
2422        assert_snapshot!(TypeSignatureClass::Time, @"Time");
2423        assert_snapshot!(TypeSignatureClass::Interval, @"Interval");
2424        assert_snapshot!(TypeSignatureClass::Duration, @"Duration");
2425        assert_snapshot!(TypeSignatureClass::Binary, @"Binary");
2426        assert_snapshot!(TypeSignatureClass::Native(logical_int32()), @"Int32");
2427        assert_snapshot!(TypeSignatureClass::Native(logical_string()), @"String");
2428    }
2429
2430    #[test]
2431    fn test_coercion_display() {
2432        use insta::assert_snapshot;
2433
2434        let exact_int = Coercion::new_exact(TypeSignatureClass::Native(logical_int32()));
2435        assert_snapshot!(exact_int, @"Int32");
2436
2437        let exact_numeric = Coercion::new_exact(TypeSignatureClass::Numeric);
2438        assert_snapshot!(exact_numeric, @"Numeric");
2439
2440        let implicit = Coercion::new_implicit(
2441            TypeSignatureClass::Native(logical_float64()),
2442            vec![TypeSignatureClass::Numeric],
2443            NativeType::Float64,
2444        );
2445        assert_snapshot!(implicit, @"Float64");
2446
2447        let implicit_with_multiple_sources = Coercion::new_implicit(
2448            TypeSignatureClass::Native(logical_int64()),
2449            vec![TypeSignatureClass::Integer, TypeSignatureClass::Numeric],
2450            NativeType::Int64,
2451        );
2452        assert_snapshot!(implicit_with_multiple_sources, @"Int64");
2453    }
2454
2455    #[test]
2456    fn test_new_implicit_native() {
2457        let allowed_source_types = vec![TypeSignatureClass::Numeric];
2458
2459        assert_eq!(
2460            Coercion::new_implicit_native(
2461                logical_float64(),
2462                allowed_source_types.clone(),
2463            ),
2464            Coercion::new_implicit(
2465                TypeSignatureClass::Native(logical_float64()),
2466                allowed_source_types,
2467                NativeType::Float64,
2468            )
2469        );
2470    }
2471
2472    #[test]
2473    fn test_coercion_encoding_preservation_affects_equality() {
2474        assert!(!EncodingPreservation::default().preserve_dictionary());
2475        let preserve_dictionary = EncodingPreservation::dictionary();
2476        assert!(preserve_dictionary.preserve_dictionary());
2477
2478        let default = Coercion::new_exact(TypeSignatureClass::Native(logical_string()));
2479        let preserving = default
2480            .clone()
2481            .with_encoding_preservation(preserve_dictionary);
2482
2483        assert_ne!(default, preserving);
2484    }
2485
2486    #[test]
2487    fn test_to_string_repr_coercible() {
2488        use insta::assert_snapshot;
2489
2490        // Simulates a function like round(Float64, Int64) with coercion
2491        let sig = TypeSignature::Coercible(vec![
2492            Coercion::new_implicit(
2493                TypeSignatureClass::Native(logical_float64()),
2494                vec![TypeSignatureClass::Numeric],
2495                NativeType::Float64,
2496            ),
2497            Coercion::new_implicit(
2498                TypeSignatureClass::Native(logical_int64()),
2499                vec![TypeSignatureClass::Integer],
2500                NativeType::Int64,
2501            ),
2502        ]);
2503        let repr = sig.to_string_repr();
2504        assert_eq!(repr.len(), 1);
2505        assert_snapshot!(repr[0], @"Float64, Int64");
2506    }
2507
2508    #[test]
2509    fn test_to_string_repr_coercible_exact() {
2510        use insta::assert_snapshot;
2511
2512        let sig = TypeSignature::Coercible(vec![
2513            Coercion::new_exact(TypeSignatureClass::Native(logical_string())),
2514            Coercion::new_exact(TypeSignatureClass::Native(logical_int64())),
2515        ]);
2516        let repr = sig.to_string_repr();
2517        assert_eq!(repr.len(), 1);
2518        assert_snapshot!(repr[0], @"String, Int64");
2519    }
2520}