Skip to main content

datafusion_physical_expr/
scalar_function.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Declaration of built-in (scalar) functions.
6//! This module contains built-in functions' enumeration and metadata.
7//!
8//! Generally, a function has:
9//! * a signature
10//! * a return type, that is a function of the incoming argument's types
11//! * the computation, that must accept each valid signature
12//!
13//! * Signature: see `Signature`
14//! * Return type: a function `(arg_types) -> return_type`. E.g. for sqrt, ([f32]) -> f32, ([f64]) -> f64.
15//!
16//! This module also has a set of coercion rules to improve user experience: if an argument i32 is passed
17//! to a function that supports f64, it is coerced to f64.
18
19use std::fmt::{self, Debug, Formatter};
20use std::hash::{Hash, Hasher};
21use std::sync::Arc;
22
23use crate::PhysicalExpr;
24use crate::expressions::Literal;
25
26use arrow::array::{Array, RecordBatch};
27use arrow::datatypes::{DataType, FieldRef, Schema};
28use datafusion_common::config::{ConfigEntry, ConfigOptions};
29use datafusion_common::{Result, ScalarValue, internal_err};
30use datafusion_expr::interval_arithmetic::Interval;
31use datafusion_expr::sort_properties::ExprProperties;
32use datafusion_expr::type_coercion::functions::fields_with_udf;
33use datafusion_expr::{
34    ColumnarValue, ExpressionPlacement, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF,
35    ScalarUDFImpl, Volatility, expr_vec_fmt,
36};
37
38/// Physical expression of a scalar function
39pub struct ScalarFunctionExpr {
40    fun: Arc<ScalarUDF>,
41    name: String,
42    args: Vec<Arc<dyn PhysicalExpr>>,
43    return_field: FieldRef,
44    config_options: Arc<ConfigOptions>,
45}
46
47impl Debug for ScalarFunctionExpr {
48    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
49        f.debug_struct("ScalarFunctionExpr")
50            .field("fun", &"<FUNC>")
51            .field("name", &self.name)
52            .field("args", &self.args)
53            .field("return_field", &self.return_field)
54            .finish()
55    }
56}
57
58impl ScalarFunctionExpr {
59    /// Create a new Scalar function
60    pub fn new(
61        name: &str,
62        fun: Arc<ScalarUDF>,
63        args: Vec<Arc<dyn PhysicalExpr>>,
64        return_field: FieldRef,
65        config_options: Arc<ConfigOptions>,
66    ) -> Self {
67        Self {
68            fun,
69            name: name.to_owned(),
70            args,
71            return_field,
72            config_options,
73        }
74    }
75
76    /// Create a new Scalar function
77    pub fn try_new(
78        fun: Arc<ScalarUDF>,
79        args: Vec<Arc<dyn PhysicalExpr>>,
80        schema: &Schema,
81        config_options: Arc<ConfigOptions>,
82    ) -> Result<Self> {
83        let name = fun.name().to_string();
84        let arg_fields = args
85            .iter()
86            .map(|e| e.return_field(schema))
87            .collect::<Result<Vec<_>>>()?;
88
89        // verify that input data types is consistent with function's `TypeSignature`
90        fields_with_udf(&arg_fields, fun.as_ref())?;
91
92        let arguments = args
93            .iter()
94            .map(|e| e.downcast_ref::<Literal>().map(|literal| literal.value()))
95            .collect::<Vec<_>>();
96        let ret_args = ReturnFieldArgs {
97            arg_fields: &arg_fields,
98            scalar_arguments: &arguments,
99        };
100        let return_field = fun.return_field_from_args(ret_args)?;
101        Ok(Self {
102            fun,
103            name,
104            args,
105            return_field,
106            config_options,
107        })
108    }
109
110    /// Get the scalar function implementation
111    pub fn fun(&self) -> &ScalarUDF {
112        &self.fun
113    }
114
115    /// The name for this expression
116    pub fn name(&self) -> &str {
117        &self.name
118    }
119
120    /// Input arguments
121    pub fn args(&self) -> &[Arc<dyn PhysicalExpr>] {
122        &self.args
123    }
124
125    /// Data type produced by this expression
126    pub fn return_type(&self) -> &DataType {
127        self.return_field.data_type()
128    }
129
130    pub fn with_nullable(mut self, nullable: bool) -> Self {
131        self.return_field = self
132            .return_field
133            .as_ref()
134            .clone()
135            .with_nullable(nullable)
136            .into();
137        self
138    }
139
140    pub fn nullable(&self) -> bool {
141        self.return_field.is_nullable()
142    }
143
144    pub fn config_options(&self) -> &ConfigOptions {
145        &self.config_options
146    }
147
148    /// Returns whether this function expression's argument types and literal
149    /// values have been audited as candidates for range-key locality analysis.
150    ///
151    /// See [`ScalarUDFImpl::supports_range_key_locality_analysis`] for the safety
152    /// requirements.
153    pub(crate) fn supports_range_key_locality_analysis(
154        &self,
155        input_schema: &Schema,
156    ) -> Result<bool> {
157        let argument_types = self
158            .args
159            .iter()
160            .map(|argument| argument.data_type(input_schema))
161            .collect::<Result<Vec<_>>>()?;
162        let literal_arguments = self
163            .args
164            .iter()
165            .map(|argument| argument.downcast_ref::<Literal>().map(Literal::value))
166            .collect::<Vec<_>>();
167        Ok(self
168            .fun
169            .supports_range_key_locality_analysis(&argument_types, &literal_arguments))
170    }
171
172    /// Given an arbitrary PhysicalExpr attempt to downcast it to a ScalarFunctionExpr
173    /// and verify that its inner function is of type T.
174    /// If the downcast fails, or the function is not of type T, returns `None`.
175    /// Otherwise returns `Some(ScalarFunctionExpr)`.
176    pub fn try_downcast_func<T>(expr: &dyn PhysicalExpr) -> Option<&ScalarFunctionExpr>
177    where
178        T: ScalarUDFImpl,
179    {
180        match expr.downcast_ref::<ScalarFunctionExpr>() {
181            Some(scalar_expr) if scalar_expr.fun().inner().is::<T>() => Some(scalar_expr),
182            _ => None,
183        }
184    }
185}
186
187impl fmt::Display for ScalarFunctionExpr {
188    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
189        write!(f, "{}({})", self.name, expr_vec_fmt!(self.args))
190    }
191}
192
193impl PartialEq for ScalarFunctionExpr {
194    fn eq(&self, o: &Self) -> bool {
195        if std::ptr::eq(self, o) {
196            // The equality implementation is somewhat expensive, so let's short-circuit when possible.
197            return true;
198        }
199        let Self {
200            fun,
201            name,
202            args,
203            return_field,
204            config_options,
205        } = self;
206        fun.eq(&o.fun)
207            && name.eq(&o.name)
208            && args.eq(&o.args)
209            && return_field.eq(&o.return_field)
210            && (Arc::ptr_eq(config_options, &o.config_options)
211                || sorted_config_entries(config_options)
212                    == sorted_config_entries(&o.config_options))
213    }
214}
215impl Eq for ScalarFunctionExpr {}
216impl Hash for ScalarFunctionExpr {
217    fn hash<H: Hasher>(&self, state: &mut H) {
218        let Self {
219            fun,
220            name,
221            args,
222            return_field,
223            config_options: _, // expensive to hash, and often equal
224        } = self;
225        fun.hash(state);
226        name.hash(state);
227        args.hash(state);
228        return_field.hash(state);
229    }
230}
231
232fn sorted_config_entries(config_options: &ConfigOptions) -> Vec<ConfigEntry> {
233    let mut entries = config_options.entries();
234    entries.sort_by(|l, r| l.key.cmp(&r.key));
235    entries
236}
237
238impl PhysicalExpr for ScalarFunctionExpr {
239    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
240        Ok(self.return_field.data_type().clone())
241    }
242
243    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
244        Ok(self.return_field.is_nullable())
245    }
246
247    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
248        let args = self
249            .args
250            .iter()
251            .map(|e| e.evaluate(batch))
252            .collect::<Result<Vec<_>>>()?;
253
254        let arg_fields = self
255            .args
256            .iter()
257            .map(|e| e.return_field(batch.schema_ref()))
258            .collect::<Result<Vec<_>>>()?;
259
260        let input_empty = args.is_empty();
261        let input_all_scalar = args
262            .iter()
263            .all(|arg| matches!(arg, ColumnarValue::Scalar(_)));
264
265        // evaluate the function
266        let output = self.fun.invoke_with_args(ScalarFunctionArgs {
267            args,
268            arg_fields,
269            number_rows: batch.num_rows(),
270            return_field: Arc::clone(&self.return_field),
271            config_options: Arc::clone(&self.config_options),
272        })?;
273
274        if let ColumnarValue::Array(array) = &output
275            && array.len() != batch.num_rows()
276        {
277            // If the arguments are a non-empty slice of scalar values, we can assume that
278            // returning a one-element array is equivalent to returning a scalar.
279            let preserve_scalar = array.len() == 1 && !input_empty && input_all_scalar;
280            return if preserve_scalar {
281                ScalarValue::try_from_array(array, 0).map(ColumnarValue::Scalar)
282            } else {
283                internal_err!(
284                    "UDF {} returned a different number of rows than expected. Expected: {}, Got: {}",
285                    self.name,
286                    batch.num_rows(),
287                    array.len()
288                )
289            };
290        }
291        Ok(output)
292    }
293
294    fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
295        Ok(Arc::clone(&self.return_field))
296    }
297
298    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
299        self.args.iter().collect()
300    }
301
302    fn with_new_children(
303        self: Arc<Self>,
304        children: Vec<Arc<dyn PhysicalExpr>>,
305    ) -> Result<Arc<dyn PhysicalExpr>> {
306        Ok(Arc::new(ScalarFunctionExpr::new(
307            &self.name,
308            Arc::clone(&self.fun),
309            children,
310            Arc::clone(&self.return_field),
311            Arc::clone(&self.config_options),
312        )))
313    }
314
315    fn evaluate_bounds(&self, children: &[&Interval]) -> Result<Interval> {
316        self.fun.evaluate_bounds(children)
317    }
318
319    fn propagate_constraints(
320        &self,
321        interval: &Interval,
322        children: &[&Interval],
323    ) -> Result<Option<Vec<Interval>>> {
324        self.fun.propagate_constraints(interval, children)
325    }
326
327    fn get_properties(&self, children: &[ExprProperties]) -> Result<ExprProperties> {
328        let sort_properties = self.fun.output_ordering(children)?;
329        let preserves_lex_ordering = self.fun.preserves_lex_ordering(children)?;
330        let strictly_order_preserving = self.fun.strictly_order_preserving(children)?;
331        let children_range = children
332            .iter()
333            .map(|props| &props.range)
334            .collect::<Vec<_>>();
335        let range = self.fun().evaluate_bounds(&children_range)?;
336        // Unbounded Null bounds carry no type information, even from an override.
337        // Recover the resolved output type while preserving all other intervals.
338        let range = if range.data_type() == DataType::Null && range.is_unbounded() {
339            Interval::make_unbounded(self.return_type()).unwrap_or(range)
340        } else {
341            range
342        };
343
344        Ok(ExprProperties {
345            sort_properties,
346            range,
347            preserves_lex_ordering,
348            strictly_order_preserving,
349        })
350    }
351
352    fn fmt_sql(&self, f: &mut Formatter<'_>) -> fmt::Result {
353        write!(f, "{}(", self.name)?;
354        for (i, expr) in self.args.iter().enumerate() {
355            if i > 0 {
356                write!(f, ", ")?;
357            }
358            expr.fmt_sql(f)?;
359        }
360        write!(f, ")")
361    }
362
363    fn is_volatile_node(&self) -> bool {
364        self.fun.signature().volatility == Volatility::Volatile
365    }
366
367    fn placement(&self) -> ExpressionPlacement {
368        let arg_placements: Vec<_> =
369            self.args.iter().map(|arg| arg.placement()).collect();
370        self.fun.placement(&arg_placements)
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use crate::expressions::Column;
378    use arrow::datatypes::{Field, IntervalUnit, TimeUnit};
379    use datafusion_expr::sort_properties::SortProperties;
380    use datafusion_expr::{ScalarUDFImpl, Signature};
381    use datafusion_physical_expr_common::physical_expr::is_volatile;
382
383    /// Test UDF with configurable volatility and return type, using default bounds.
384    #[derive(Debug, PartialEq, Eq, Hash)]
385    struct MockScalarUDF {
386        signature: Signature,
387        return_type: DataType,
388    }
389
390    impl ScalarUDFImpl for MockScalarUDF {
391        fn name(&self) -> &str {
392            "mock_function"
393        }
394
395        fn signature(&self) -> &Signature {
396            &self.signature
397        }
398
399        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
400            Ok(self.return_type.clone())
401        }
402
403        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
404            Ok(ColumnarValue::Scalar(ScalarValue::try_from(
405                &self.return_type,
406            )?))
407        }
408    }
409
410    /// Builds `date_bin(stride, ts)` and checks whether locality analysis is allowed.
411    fn date_bin_supports_locality_with_stride(
412        function: Arc<ScalarUDF>,
413        stride: Arc<dyn PhysicalExpr>,
414    ) -> Result<bool> {
415        let schema = Schema::new(vec![
416            Field::new(
417                "stride",
418                DataType::Interval(IntervalUnit::MonthDayNano),
419                true,
420            ),
421            Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),
422        ]);
423        let expr = ScalarFunctionExpr::try_new(
424            function,
425            vec![stride, Arc::new(Column::new("ts", 1))],
426            &schema,
427            Arc::new(ConfigOptions::default()),
428        )?;
429        expr.supports_range_key_locality_analysis(&schema)
430    }
431
432    #[test]
433    fn range_key_locality_analysis_receives_literal_values() -> Result<()> {
434        let function = datafusion_functions::datetime::date_bin();
435        let hour = Arc::new(Literal::new(ScalarValue::new_interval_mdn(
436            0,
437            0,
438            3_600_000_000_000,
439        )));
440        let month = Arc::new(Literal::new(ScalarValue::new_interval_mdn(1, 0, 0)));
441
442        assert!(date_bin_supports_locality_with_stride(
443            Arc::clone(&function),
444            hour
445        )?);
446        assert!(!date_bin_supports_locality_with_stride(function, month)?);
447        Ok(())
448    }
449
450    #[test]
451    fn range_key_locality_analysis_preserves_aliases() -> Result<()> {
452        let date_bin = datafusion_functions::datetime::date_bin();
453        let function =
454            Arc::new(date_bin.as_ref().clone().with_aliases(["date_bin_alias"]));
455        let hour = Arc::new(Literal::new(ScalarValue::new_interval_mdn(
456            0,
457            0,
458            3_600_000_000_000,
459        )));
460        let month = Arc::new(Literal::new(ScalarValue::new_interval_mdn(1, 0, 0)));
461
462        assert!(date_bin_supports_locality_with_stride(
463            Arc::clone(&function),
464            hour
465        )?);
466        assert!(!date_bin_supports_locality_with_stride(function, month)?);
467        Ok(())
468    }
469
470    #[test]
471    fn range_key_locality_analysis_rejects_non_literal_parameters() -> Result<()> {
472        use crate::expressions::CastExpr;
473
474        let function = datafusion_functions::datetime::date_bin();
475        let column = Arc::new(Column::new("stride", 0));
476        let hour = Arc::new(Literal::new(ScalarValue::new_interval_mdn(
477            0,
478            0,
479            3_600_000_000_000,
480        )));
481        let cast = Arc::new(CastExpr::new(
482            hour,
483            DataType::Interval(IntervalUnit::MonthDayNano),
484            None,
485        ));
486
487        assert!(!date_bin_supports_locality_with_stride(
488            Arc::clone(&function),
489            column
490        )?);
491        assert!(!date_bin_supports_locality_with_stride(function, cast)?);
492        Ok(())
493    }
494
495    #[test]
496    fn range_key_locality_analysis_accepts_date_trunc() -> Result<()> {
497        let schema = Schema::new(vec![Field::new(
498            "ts",
499            DataType::Timestamp(TimeUnit::Nanosecond, None),
500            true,
501        )]);
502        let expr = ScalarFunctionExpr::try_new(
503            datafusion_functions::datetime::date_trunc(),
504            vec![
505                Arc::new(Literal::new(ScalarValue::from("hour"))),
506                Arc::new(Column::new("ts", 0)),
507            ],
508            &schema,
509            Arc::new(ConfigOptions::default()),
510        )?;
511        assert!(expr.supports_range_key_locality_analysis(&schema)?);
512        Ok(())
513    }
514
515    fn default_bounds_expr(return_type: DataType) -> ScalarFunctionExpr {
516        ScalarFunctionExpr::try_new(
517            Arc::new(ScalarUDF::from(MockScalarUDF {
518                signature: Signature::exact(vec![], Volatility::Immutable),
519                return_type,
520            })),
521            vec![],
522            &Schema::empty(),
523            Arc::new(ConfigOptions::default()),
524        )
525        .unwrap()
526    }
527
528    #[test]
529    fn properties_recover_return_type_without_changing_bounds_evaluation() {
530        for data_type in [
531            DataType::Null,
532            DataType::Boolean,
533            DataType::Int32,
534            DataType::UInt64,
535            DataType::Float64,
536            DataType::Utf8,
537            DataType::Timestamp(TimeUnit::Second, None),
538            DataType::Timestamp(TimeUnit::Nanosecond, Some("America/Goose_Bay".into())),
539            DataType::Time32(TimeUnit::Millisecond),
540            DataType::Time64(TimeUnit::Microsecond),
541            DataType::List(Arc::new(Field::new("item", DataType::Int32, true))),
542        ] {
543            let expr = default_bounds_expr(data_type.clone());
544            let properties = expr.get_properties(&[]).unwrap();
545            assert_eq!(
546                properties.range,
547                Interval::make_unbounded(&data_type).unwrap()
548            );
549            assert_eq!(properties.sort_properties, SortProperties::Unordered);
550            assert!(!properties.preserves_lex_ordering);
551            assert!(!properties.strictly_order_preserving);
552            // Direct bounds evaluation does not use the property-analysis fallback.
553            assert_eq!(
554                expr.evaluate_bounds(&[]).unwrap(),
555                Interval::make_unbounded(&DataType::Null).unwrap()
556            );
557        }
558    }
559
560    #[test]
561    fn properties_keep_unknown_bounds_for_unsupported_return_type() {
562        // This unit is not supported for Time32 by ScalarValue/Interval.
563        let data_type = DataType::Time32(TimeUnit::Nanosecond);
564        assert!(Interval::make_unbounded(&data_type).is_err());
565        let properties = default_bounds_expr(data_type).get_properties(&[]).unwrap();
566        assert_eq!(
567            properties.range,
568            Interval::make_unbounded(&DataType::Null).unwrap()
569        );
570    }
571
572    #[test]
573    fn datetime_properties_use_resolved_return_types() {
574        use datafusion_functions::datetime::date_bin::DateBinFunc;
575        use datafusion_functions::datetime::from_unixtime::FromUnixtimeFunc;
576
577        for source_type in [
578            DataType::Timestamp(TimeUnit::Second, None),
579            DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
580            DataType::Time32(TimeUnit::Millisecond),
581            DataType::Time64(TimeUnit::Microsecond),
582        ] {
583            let expr = ScalarFunctionExpr::try_new(
584                Arc::new(ScalarUDF::from(DateBinFunc::new())),
585                vec![
586                    Arc::new(Literal::new(ScalarValue::new_interval_mdn(
587                        0,
588                        0,
589                        60_000_000_000,
590                    ))),
591                    Arc::new(Column::new("ts", 0)),
592                ],
593                &Schema::new(vec![Field::new("ts", source_type.clone(), true)]),
594                Arc::new(ConfigOptions::default()),
595            )
596            .unwrap();
597            let properties = expr
598                .get_properties(&[
599                    ExprProperties::new_unknown().with_order(SortProperties::Singleton),
600                    ExprProperties::new_unknown()
601                        .with_range(Interval::make_unbounded(&source_type).unwrap()),
602                ])
603                .unwrap();
604            assert_eq!(
605                properties.range,
606                Interval::make_unbounded(&source_type).unwrap()
607            );
608        }
609
610        for (session_tz, explicit_tz, expected_tz) in [
611            (None, None, None),
612            (Some("America/Denver"), None, Some("America/Denver")),
613            (
614                Some("America/Denver"),
615                Some("America/Goose_Bay"),
616                Some("America/Goose_Bay"),
617            ),
618        ] {
619            let mut config = ConfigOptions::default();
620            config.execution.time_zone = session_tz.map(|tz| tz.parse().unwrap());
621            let udf = FromUnixtimeFunc::new_with_config(&config);
622            let mut args: Vec<Arc<dyn PhysicalExpr>> =
623                vec![Arc::new(Column::new("c", 0))];
624            if let Some(tz) = explicit_tz {
625                args.push(Arc::new(Literal::new(ScalarValue::from(tz))));
626            }
627            let children = vec![ExprProperties::new_unknown(); args.len()];
628            let expr = ScalarFunctionExpr::try_new(
629                Arc::new(ScalarUDF::from(udf)),
630                args,
631                &Schema::new(vec![Field::new("c", DataType::Int64, true)]),
632                Arc::new(config),
633            )
634            .unwrap();
635            // The literal's timezone was resolved during construction, even
636            // though the child intervals here contain no value information.
637            let expected =
638                DataType::Timestamp(TimeUnit::Second, expected_tz.map(Into::into));
639            assert_eq!(
640                expr.get_properties(&children).unwrap().range,
641                Interval::make_unbounded(&expected).unwrap()
642            );
643        }
644    }
645
646    #[test]
647    fn checked_time_arithmetic_uses_recovered_function_type() -> Result<()> {
648        use crate::expressions::BinaryExpr;
649        use arrow::compute::SortOptions;
650        use datafusion_expr::Operator;
651        use datafusion_functions::datetime::date_trunc::DateTruncFunc;
652
653        let time_type = DataType::Time64(TimeUnit::Nanosecond);
654        let precision = Arc::new(Literal::new(ScalarValue::from("hour")));
655        let precision_properties = precision.get_properties(&[])?;
656        let date_trunc = ScalarFunctionExpr::try_new(
657            Arc::new(ScalarUDF::from(DateTruncFunc::new())),
658            vec![precision, Arc::new(Column::new("t", 0))],
659            &Schema::new(vec![Field::new("t", time_type.clone(), true)]),
660            Arc::new(ConfigOptions::default()),
661        )?;
662        let time_properties = ExprProperties::new_unknown()
663            .with_order(SortProperties::Ordered(SortOptions::default()))
664            .with_range(Interval::make_unbounded(&time_type)?);
665        let truncated_properties =
666            date_trunc.get_properties(&[precision_properties, time_properties])?;
667        assert_eq!(
668            truncated_properties.range,
669            Interval::make_unbounded(&time_type)?
670        );
671        assert_eq!(
672            truncated_properties.sort_properties,
673            SortProperties::Ordered(SortOptions::default())
674        );
675        let interval = Arc::new(Literal::new(ScalarValue::new_interval_mdn(
676            0,
677            0,
678            7_200_000_000_000,
679        )));
680        let interval_properties = interval.get_properties(&[])?;
681        let shifted = BinaryExpr::new(Arc::new(date_trunc), Operator::Plus, interval)
682            .with_fail_on_overflow(true);
683
684        // Checked arithmetic still wraps time-of-day across midnight. Recovering
685        // the function's type is necessary to recognize this non-monotonic case.
686        assert_eq!(
687            shifted
688                .get_properties(&[truncated_properties, interval_properties])?
689                .sort_properties,
690            SortProperties::Unordered
691        );
692        Ok(())
693    }
694
695    #[derive(Debug, PartialEq, Eq, Hash)]
696    struct BoundsUDF {
697        inner: MockScalarUDF,
698        fail: bool,
699    }
700
701    impl ScalarUDFImpl for BoundsUDF {
702        fn name(&self) -> &str {
703            "bounds_function"
704        }
705
706        fn signature(&self) -> &Signature {
707            self.inner.signature()
708        }
709
710        fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
711            self.inner.return_type(arg_types)
712        }
713
714        fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
715            self.inner.invoke_with_args(args)
716        }
717
718        fn evaluate_bounds(&self, inputs: &[&Interval]) -> Result<Interval> {
719            if self.fail {
720                return internal_err!("bounds evaluation failed");
721            }
722            Ok(inputs[0].clone())
723        }
724    }
725
726    fn bounds_expr(fail: bool) -> ScalarFunctionExpr {
727        ScalarFunctionExpr::try_new(
728            Arc::new(ScalarUDF::from(BoundsUDF {
729                inner: MockScalarUDF {
730                    signature: Signature::exact(
731                        vec![DataType::Int32],
732                        Volatility::Immutable,
733                    ),
734                    return_type: DataType::Int32,
735                },
736                fail,
737            })),
738            vec![Arc::new(Column::new("a", 0))],
739            &Schema::new(vec![Field::new("a", DataType::Int32, true)]),
740            Arc::new(ConfigOptions::default()),
741        )
742        .unwrap()
743    }
744
745    #[test]
746    fn properties_preserve_udf_bounds() {
747        let expr = bounds_expr(false);
748        for (lower, upper) in [
749            (Some(0), Some(100)),
750            (Some(1), Some(1)),
751            (None, Some(100)),
752            (Some(0), None),
753            (None, None),
754        ] {
755            let bounds = Interval::make::<i32>(lower, upper).unwrap();
756            let child = ExprProperties::new_unknown().with_range(bounds.clone());
757            assert_eq!(expr.get_properties(&[child]).unwrap().range, bounds);
758            assert_eq!(expr.evaluate_bounds(&[&bounds]).unwrap(), bounds);
759        }
760    }
761
762    #[test]
763    fn properties_recover_type_from_explicit_unknown_bounds() {
764        let expr = bounds_expr(false);
765        let bounds = Interval::make_unbounded(&DataType::Null).unwrap();
766        let child = ExprProperties::new_unknown().with_range(bounds.clone());
767        assert_eq!(
768            expr.get_properties(&[child]).unwrap().range,
769            Interval::make_unbounded(&DataType::Int32).unwrap()
770        );
771        assert_eq!(expr.evaluate_bounds(&[&bounds]).unwrap(), bounds);
772    }
773
774    #[test]
775    fn properties_propagate_udf_bounds_errors() {
776        let expr = bounds_expr(true);
777        let bounds = Interval::make::<i32>(Some(0), Some(100)).unwrap();
778        let child = ExprProperties::new_unknown().with_range(bounds.clone());
779        assert!(
780            expr.get_properties(&[child])
781                .unwrap_err()
782                .to_string()
783                .contains("bounds evaluation failed")
784        );
785        assert!(
786            expr.evaluate_bounds(&[&bounds])
787                .unwrap_err()
788                .to_string()
789                .contains("bounds evaluation failed")
790        );
791    }
792
793    #[test]
794    fn test_scalar_function_volatile_node() {
795        // Create a volatile UDF
796        let volatile_udf = Arc::new(ScalarUDF::from(MockScalarUDF {
797            return_type: DataType::Int32,
798            signature: Signature::uniform(
799                1,
800                vec![DataType::Float32],
801                Volatility::Volatile,
802            ),
803        }));
804
805        // Create a non-volatile UDF
806        let stable_udf = Arc::new(ScalarUDF::from(MockScalarUDF {
807            return_type: DataType::Int32,
808            signature: Signature::uniform(1, vec![DataType::Float32], Volatility::Stable),
809        }));
810
811        let schema = Schema::new(vec![Field::new("a", DataType::Float32, false)]);
812        let args = vec![Arc::new(Column::new("a", 0)) as Arc<dyn PhysicalExpr>];
813        let config_options = Arc::new(ConfigOptions::new());
814
815        // Test volatile function
816        let volatile_expr = ScalarFunctionExpr::try_new(
817            volatile_udf,
818            args.clone(),
819            &schema,
820            Arc::clone(&config_options),
821        )
822        .unwrap();
823
824        assert!(volatile_expr.is_volatile_node());
825        let volatile_arc: Arc<dyn PhysicalExpr> = Arc::new(volatile_expr);
826        assert!(is_volatile(&volatile_arc));
827
828        // Test non-volatile function
829        let stable_expr =
830            ScalarFunctionExpr::try_new(stable_udf, args, &schema, config_options)
831                .unwrap();
832
833        assert!(!stable_expr.is_volatile_node());
834        let stable_arc: Arc<dyn PhysicalExpr> = Arc::new(stable_expr);
835        assert!(!is_volatile(&stable_arc));
836    }
837}