Skip to main content

datafusion_expr_common/
columnar_value.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//! [`ColumnarValue`] represents the result of evaluating an expression.
6
7use arrow::{
8    array::{
9        Array, ArrayRef, Date32Array, Date64Array, NullArray, TimestampMicrosecondArray,
10        TimestampMillisecondArray, TimestampNanosecondArray, TimestampSecondArray,
11    },
12    compute::{CastOptions, kernels, max, min},
13    datatypes::{DataType, TimeUnit},
14    util::pretty::pretty_format_columns,
15};
16use datafusion_common::internal_datafusion_err;
17use datafusion_common::{
18    Result, ScalarValue,
19    format::DEFAULT_CAST_OPTIONS,
20    internal_err,
21    scalar::{
22        date_to_timestamp_multiplier, ensure_timestamp_in_bounds,
23        timestamp_to_timestamp_multiplier,
24    },
25};
26use std::fmt;
27use std::sync::Arc;
28
29/// The result of evaluating an expression.
30///
31/// [`ColumnarValue::Scalar`] represents a single value repeated any number of
32/// times. This is an important performance optimization for handling values
33/// that do not change across rows.
34///
35/// [`ColumnarValue::Array`] represents a column of data, stored as an  Arrow
36/// [`ArrayRef`]
37///
38/// A slice of `ColumnarValue`s logically represents a table, with each column
39/// having the same number of rows. This means that all `Array`s are the same
40/// length.
41///
42/// # Example
43///
44/// A `ColumnarValue::Array` with an array of 5 elements and a
45/// `ColumnarValue::Scalar` with the value 100
46///
47/// ```text
48/// ┌──────────────┐
49/// │ ┌──────────┐ │
50/// │ │   "A"    │ │
51/// │ ├──────────┤ │
52/// │ │   "B"    │ │
53/// │ ├──────────┤ │
54/// │ │   "C"    │ │
55/// │ ├──────────┤ │
56/// │ │   "D"    │ │        ┌──────────────┐
57/// │ ├──────────┤ │        │ ┌──────────┐ │
58/// │ │   "E"    │ │        │ │   100    │ │
59/// │ └──────────┘ │        │ └──────────┘ │
60/// └──────────────┘        └──────────────┘
61///
62///  ColumnarValue::        ColumnarValue::
63///       Array                 Scalar
64/// ```
65///
66/// Logically represents the following table:
67///
68/// | Column 1| Column 2 |
69/// | ------- | -------- |
70/// | A | 100 |
71/// | B | 100 |
72/// | C | 100 |
73/// | D | 100 |
74/// | E | 100 |
75///
76/// # Performance Notes
77///
78/// When implementing functions or operators, it is important to consider the
79/// performance implications of handling scalar values.
80///
81/// Because all functions must handle [`ArrayRef`], it is
82/// convenient to convert [`ColumnarValue::Scalar`]s using
83/// [`Self::into_array`]. For example,  [`ColumnarValue::values_to_arrays`]
84/// converts multiple columnar values into arrays of the same length.
85///
86/// However, it is often much more performant to provide a different,
87/// implementation that handles scalar values differently
88#[derive(Clone, Debug)]
89pub enum ColumnarValue {
90    /// Array of values
91    Array(ArrayRef),
92    /// A single value
93    Scalar(ScalarValue),
94}
95
96impl From<ArrayRef> for ColumnarValue {
97    fn from(value: ArrayRef) -> Self {
98        ColumnarValue::Array(value)
99    }
100}
101
102impl From<ScalarValue> for ColumnarValue {
103    fn from(value: ScalarValue) -> Self {
104        ColumnarValue::Scalar(value)
105    }
106}
107
108impl ColumnarValue {
109    pub fn data_type(&self) -> DataType {
110        match self {
111            ColumnarValue::Array(array_value) => array_value.data_type().clone(),
112            ColumnarValue::Scalar(scalar_value) => scalar_value.data_type(),
113        }
114    }
115
116    /// Convert any [`Self::Scalar`] into an Arrow [`ArrayRef`] with the specified
117    /// number of rows  by repeating the same scalar multiple times,
118    /// which is not as efficient as handling the scalar directly.
119    /// [`Self::Array`] will just be returned as is.
120    ///
121    /// See [`Self::into_array_of_size`] if you need to validate the length of the output array.
122    ///
123    /// See [`Self::values_to_arrays`] to convert multiple columnar values into
124    /// arrays of the same length.
125    ///
126    /// # Errors
127    ///
128    /// Errors if `self` is a Scalar that fails to be converted into an array of size
129    pub fn into_array(self, num_rows: usize) -> Result<ArrayRef> {
130        Ok(match self {
131            ColumnarValue::Array(array) => array,
132            ColumnarValue::Scalar(scalar) => scalar.to_array_of_size(num_rows)?,
133        })
134    }
135
136    /// Convert a columnar value into an Arrow [`ArrayRef`] with the specified
137    /// number of rows. [`Self::Scalar`] is converted by repeating the same
138    /// scalar multiple times which is not as efficient as handling the scalar
139    /// directly.
140    /// This validates that if this is [`Self::Array`], it has the expected length.
141    ///
142    /// See [`Self::values_to_arrays`] to convert multiple columnar values into
143    /// arrays of the same length.
144    ///
145    /// # Errors
146    ///
147    /// Errors if `self` is a Scalar that fails to be converted into an array of size or
148    /// if the array length does not match the expected length
149    pub fn into_array_of_size(self, num_rows: usize) -> Result<ArrayRef> {
150        match self {
151            ColumnarValue::Array(array) => {
152                if array.len() == num_rows {
153                    Ok(array)
154                } else {
155                    internal_err!(
156                        "Array length {} does not match expected length {}",
157                        array.len(),
158                        num_rows
159                    )
160                }
161            }
162            ColumnarValue::Scalar(scalar) => scalar.to_array_of_size(num_rows),
163        }
164    }
165
166    /// Convert any [`Self::Scalar`] into an Arrow [`ArrayRef`] with the specified
167    /// number of rows  by repeating the same scalar multiple times,
168    /// which is not as efficient as handling the scalar directly.
169    /// [`Self::Array`] will just be returned as is.
170    ///
171    /// See [`Self::to_array_of_size`] if you need to validate the length of the output array.
172    ///
173    /// See [`Self::values_to_arrays`] to convert multiple columnar values into
174    /// arrays of the same length.
175    ///
176    /// # Errors
177    ///
178    /// Errors if `self` is a Scalar that fails to be converted into an array of size
179    pub fn to_array(&self, num_rows: usize) -> Result<ArrayRef> {
180        Ok(match self {
181            ColumnarValue::Array(array) => Arc::clone(array),
182            ColumnarValue::Scalar(scalar) => scalar.to_array_of_size(num_rows)?,
183        })
184    }
185
186    /// Convert a columnar value into an Arrow [`ArrayRef`] with the specified
187    /// number of rows. [`Self::Scalar`] is converted by repeating the same
188    /// scalar multiple times which is not as efficient as handling the scalar
189    /// directly.
190    /// This validates that if this is [`Self::Array`], it has the expected length.
191    ///
192    /// See [`Self::values_to_arrays`] to convert multiple columnar values into
193    /// arrays of the same length.
194    ///
195    /// # Errors
196    ///
197    /// Errors if `self` is a Scalar that fails to be converted into an array of size or
198    /// if the array length does not match the expected length
199    pub fn to_array_of_size(&self, num_rows: usize) -> Result<ArrayRef> {
200        match self {
201            ColumnarValue::Array(array) => {
202                if array.len() == num_rows {
203                    Ok(Arc::clone(array))
204                } else {
205                    internal_err!(
206                        "Array length {} does not match expected length {}",
207                        array.len(),
208                        num_rows
209                    )
210                }
211            }
212            ColumnarValue::Scalar(scalar) => scalar.to_array_of_size(num_rows),
213        }
214    }
215
216    /// Null columnar values are implemented as a null array in order to pass batch
217    /// num_rows
218    pub fn create_null_array(num_rows: usize) -> Self {
219        ColumnarValue::Array(Arc::new(NullArray::new(num_rows)))
220    }
221
222    /// Converts  [`ColumnarValue`]s to [`ArrayRef`]s with the same length.
223    ///
224    /// # Performance Note
225    ///
226    /// This function expands any [`ScalarValue`] to an array. This expansion
227    /// permits using a single function in terms of arrays, but it can be
228    /// inefficient compared to handling the scalar value directly.
229    ///
230    /// Thus, it is recommended to provide specialized implementations for
231    /// scalar values if performance is a concern.
232    ///
233    /// # Errors
234    ///
235    /// If there are multiple array arguments that have different lengths
236    pub fn values_to_arrays(args: &[ColumnarValue]) -> Result<Vec<ArrayRef>> {
237        if args.is_empty() {
238            return Ok(vec![]);
239        }
240
241        let mut array_len = None;
242        for arg in args {
243            array_len = match (arg, array_len) {
244                (ColumnarValue::Array(a), None) => Some(a.len()),
245                (ColumnarValue::Array(a), Some(array_len)) => {
246                    if array_len == a.len() {
247                        Some(array_len)
248                    } else {
249                        return internal_err!(
250                            "Arguments has mixed length. Expected length: {array_len}, found length: {}",
251                            a.len()
252                        );
253                    }
254                }
255                (ColumnarValue::Scalar(_), array_len) => array_len,
256            }
257        }
258
259        // If array_len is none, it means there are only scalars, so make a 1 element array
260        let inferred_length = array_len.unwrap_or(1);
261
262        let args = args
263            .iter()
264            .map(|arg| arg.to_array(inferred_length))
265            .collect::<Result<Vec<_>>>()?;
266
267        Ok(args)
268    }
269
270    /// Cast this [ColumnarValue] to the specified `DataType`
271    ///
272    /// # Struct Casting Behavior
273    ///
274    /// When casting struct types, fields are matched **by name** rather than position:
275    /// - Source fields are matched to target fields using case-sensitive name comparison
276    /// - Fields are reordered to match the target schema
277    /// - Missing target fields are filled with null arrays
278    /// - Extra source fields are ignored
279    ///
280    /// For non-struct types, uses Arrow's standard positional casting.
281    pub fn cast_to(
282        &self,
283        cast_type: &DataType,
284        cast_options: Option<&CastOptions<'_>>,
285    ) -> Result<ColumnarValue> {
286        let cast_options = cast_options.cloned().unwrap_or(DEFAULT_CAST_OPTIONS);
287        match self {
288            ColumnarValue::Array(array) => {
289                let casted = cast_array_by_name(array, cast_type, &cast_options)?;
290                Ok(ColumnarValue::Array(casted))
291            }
292            ColumnarValue::Scalar(scalar) => Ok(ColumnarValue::Scalar(
293                scalar.cast_to_with_options(cast_type, &cast_options)?,
294            )),
295        }
296    }
297}
298
299fn cast_array_by_name(
300    array: &ArrayRef,
301    cast_type: &DataType,
302    cast_options: &CastOptions<'_>,
303) -> Result<ArrayRef> {
304    // If types are already equal, no cast needed
305    if array.data_type() == cast_type {
306        return Ok(Arc::clone(array));
307    }
308
309    if datafusion_common::nested_struct::requires_nested_struct_cast(
310        array.data_type(),
311        cast_type,
312    ) {
313        datafusion_common::nested_struct::cast_column(array, cast_type, cast_options)
314    } else {
315        if !cast_options.safe {
316            ensure_temporal_array_timestamp_bounds(array, cast_type)?;
317        }
318        Ok(kernels::cast::cast_with_options(
319            array,
320            cast_type,
321            cast_options,
322        )?)
323    }
324}
325
326fn ensure_temporal_array_timestamp_bounds(
327    array: &ArrayRef,
328    cast_type: &DataType,
329) -> Result<()> {
330    let source_type = array.data_type().clone();
331    let Some(multiplier) = date_to_timestamp_multiplier(&source_type, cast_type)
332        .or_else(|| timestamp_to_timestamp_multiplier(&source_type, cast_type))
333    else {
334        return Ok(());
335    };
336
337    if multiplier <= 1 {
338        return Ok(());
339    }
340
341    // Use compute kernels to find min/max instead of iterating all elements
342    let (min_val, max_val): (Option<i64>, Option<i64>) = match &source_type {
343        DataType::Date32 => {
344            let arr = array
345                .as_any()
346                .downcast_ref::<Date32Array>()
347                .ok_or_else(|| {
348                    internal_datafusion_err!(
349                        "Expected Date32Array but found {}",
350                        array.data_type()
351                    )
352                })?;
353            (min(arr).map(|v| v as i64), max(arr).map(|v| v as i64))
354        }
355        DataType::Date64 => {
356            let arr = array
357                .as_any()
358                .downcast_ref::<Date64Array>()
359                .ok_or_else(|| {
360                    internal_datafusion_err!(
361                        "Expected Date64Array but found {}",
362                        array.data_type()
363                    )
364                })?;
365            (min(arr), max(arr))
366        }
367        DataType::Timestamp(TimeUnit::Second, _) => {
368            let arr = array
369                .as_any()
370                .downcast_ref::<TimestampSecondArray>()
371                .ok_or_else(|| {
372                    internal_datafusion_err!(
373                        "Expected TimestampSecondArray but found {}",
374                        array.data_type()
375                    )
376                })?;
377            (min(arr), max(arr))
378        }
379        DataType::Timestamp(TimeUnit::Millisecond, _) => {
380            let arr = array
381                .as_any()
382                .downcast_ref::<TimestampMillisecondArray>()
383                .ok_or_else(|| {
384                    internal_datafusion_err!(
385                        "Expected TimestampMillisecondArray but found {}",
386                        array.data_type()
387                    )
388                })?;
389            (min(arr), max(arr))
390        }
391        DataType::Timestamp(TimeUnit::Microsecond, _) => {
392            let arr = array
393                .as_any()
394                .downcast_ref::<TimestampMicrosecondArray>()
395                .ok_or_else(|| {
396                    internal_datafusion_err!(
397                        "Expected TimestampMicrosecondArray but found {}",
398                        array.data_type()
399                    )
400                })?;
401            (min(arr), max(arr))
402        }
403        DataType::Timestamp(TimeUnit::Nanosecond, _) => {
404            let arr = array
405                .as_any()
406                .downcast_ref::<TimestampNanosecondArray>()
407                .ok_or_else(|| {
408                    internal_datafusion_err!(
409                        "Expected TimestampNanosecondArray but found {}",
410                        array.data_type()
411                    )
412                })?;
413            (min(arr), max(arr))
414        }
415        _ => return Ok(()), // Not a temporal type that needs checking.
416    };
417
418    // Only validate the min and max values instead of all elements
419    if let Some(min) = min_val {
420        ensure_timestamp_in_bounds(min, multiplier, &source_type, cast_type)?;
421    }
422    if let Some(max) = max_val {
423        ensure_timestamp_in_bounds(max, multiplier, &source_type, cast_type)?;
424    }
425
426    Ok(())
427}
428
429// Implement Display trait for ColumnarValue
430impl fmt::Display for ColumnarValue {
431    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
432        let formatted = match self {
433            ColumnarValue::Array(array) => {
434                pretty_format_columns("ColumnarValue(ArrayRef)", &[Arc::clone(array)])
435            }
436            ColumnarValue::Scalar(_) => {
437                if let Ok(array) = self.to_array(1) {
438                    pretty_format_columns("ColumnarValue(ScalarValue)", &[array])
439                } else {
440                    return write!(f, "Error formatting columnar value");
441                }
442            }
443        };
444
445        if let Ok(formatted) = formatted {
446            write!(f, "{formatted}")
447        } else {
448            write!(f, "Error formatting columnar value")
449        }
450    }
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456    use arrow::{
457        array::{Date64Array, Int32Array, StructArray},
458        datatypes::{Field, Fields, TimeUnit},
459    };
460
461    #[test]
462    fn into_array_of_size() {
463        // Array case
464        let arr = make_array(1, 3);
465        let arr_columnar_value = ColumnarValue::Array(Arc::clone(&arr));
466        assert_eq!(&arr_columnar_value.into_array_of_size(3).unwrap(), &arr);
467
468        // Scalar case
469        let scalar_columnar_value = ColumnarValue::Scalar(ScalarValue::Int32(Some(42)));
470        let expected_array = make_array(42, 100);
471        assert_eq!(
472            &scalar_columnar_value.into_array_of_size(100).unwrap(),
473            &expected_array
474        );
475
476        // Array case with wrong size
477        let arr = make_array(1, 3);
478        let arr_columnar_value = ColumnarValue::Array(Arc::clone(&arr));
479        let result = arr_columnar_value.into_array_of_size(5);
480        let err = result.unwrap_err();
481        assert!(
482            err.to_string().starts_with(
483                "Internal error: Array length 3 does not match expected length 5"
484            ),
485            "Found: {err}"
486        );
487    }
488
489    #[test]
490    fn values_to_arrays() {
491        // (input, expected)
492        let cases = vec![
493            // empty
494            TestCase {
495                input: vec![],
496                expected: vec![],
497            },
498            // one array of length 3
499            TestCase {
500                input: vec![ColumnarValue::Array(make_array(1, 3))],
501                expected: vec![make_array(1, 3)],
502            },
503            // two arrays length 3
504            TestCase {
505                input: vec![
506                    ColumnarValue::Array(make_array(1, 3)),
507                    ColumnarValue::Array(make_array(2, 3)),
508                ],
509                expected: vec![make_array(1, 3), make_array(2, 3)],
510            },
511            // array and scalar
512            TestCase {
513                input: vec![
514                    ColumnarValue::Array(make_array(1, 3)),
515                    ColumnarValue::Scalar(ScalarValue::Int32(Some(100))),
516                ],
517                expected: vec![
518                    make_array(1, 3),
519                    make_array(100, 3), // scalar is expanded
520                ],
521            },
522            // scalar and array
523            TestCase {
524                input: vec![
525                    ColumnarValue::Scalar(ScalarValue::Int32(Some(100))),
526                    ColumnarValue::Array(make_array(1, 3)),
527                ],
528                expected: vec![
529                    make_array(100, 3), // scalar is expanded
530                    make_array(1, 3),
531                ],
532            },
533            // multiple scalars and array
534            TestCase {
535                input: vec![
536                    ColumnarValue::Scalar(ScalarValue::Int32(Some(100))),
537                    ColumnarValue::Array(make_array(1, 3)),
538                    ColumnarValue::Scalar(ScalarValue::Int32(Some(200))),
539                ],
540                expected: vec![
541                    make_array(100, 3), // scalar is expanded
542                    make_array(1, 3),
543                    make_array(200, 3), // scalar is expanded
544                ],
545            },
546        ];
547        for case in cases {
548            case.run();
549        }
550    }
551
552    #[test]
553    #[should_panic(
554        expected = "Arguments has mixed length. Expected length: 3, found length: 4"
555    )]
556    fn values_to_arrays_mixed_length() {
557        ColumnarValue::values_to_arrays(&[
558            ColumnarValue::Array(make_array(1, 3)),
559            ColumnarValue::Array(make_array(2, 4)),
560        ])
561        .unwrap();
562    }
563
564    #[test]
565    #[should_panic(
566        expected = "Arguments has mixed length. Expected length: 3, found length: 7"
567    )]
568    fn values_to_arrays_mixed_length_and_scalar() {
569        ColumnarValue::values_to_arrays(&[
570            ColumnarValue::Array(make_array(1, 3)),
571            ColumnarValue::Scalar(ScalarValue::Int32(Some(100))),
572            ColumnarValue::Array(make_array(2, 7)),
573        ])
574        .unwrap();
575    }
576
577    struct TestCase {
578        input: Vec<ColumnarValue>,
579        expected: Vec<ArrayRef>,
580    }
581
582    impl TestCase {
583        fn run(self) {
584            let Self { input, expected } = self;
585
586            assert_eq!(
587                ColumnarValue::values_to_arrays(&input).unwrap(),
588                expected,
589                "\ninput: {input:?}\nexpected: {expected:?}"
590            );
591        }
592    }
593
594    /// Makes an array of length `len` with all elements set to `val`
595    fn make_array(val: i32, len: usize) -> ArrayRef {
596        Arc::new(Int32Array::from(vec![val; len]))
597    }
598
599    #[test]
600    fn test_display_scalar() {
601        let column = ColumnarValue::from(ScalarValue::from("foo"));
602        assert_eq!(
603            column.to_string(),
604            concat!(
605                "+----------------------------+\n",
606                "| ColumnarValue(ScalarValue) |\n",
607                "+----------------------------+\n",
608                "| foo                        |\n",
609                "+----------------------------+"
610            )
611        );
612    }
613
614    #[test]
615    fn test_display_array() {
616        let array: ArrayRef = Arc::new(Int32Array::from_iter_values(vec![1, 2, 3]));
617        let column = ColumnarValue::from(array);
618        assert_eq!(
619            column.to_string(),
620            concat!(
621                "+-------------------------+\n",
622                "| ColumnarValue(ArrayRef) |\n",
623                "+-------------------------+\n",
624                "| 1                       |\n",
625                "| 2                       |\n",
626                "| 3                       |\n",
627                "+-------------------------+"
628            )
629        );
630    }
631
632    #[test]
633    fn cast_struct_by_field_name() {
634        let source_fields = Fields::from(vec![
635            Field::new("b", DataType::Int32, true),
636            Field::new("a", DataType::Int32, true),
637        ]);
638
639        let target_fields = Fields::from(vec![
640            Field::new("a", DataType::Int32, true),
641            Field::new("b", DataType::Int32, true),
642        ]);
643
644        let struct_array = StructArray::new(
645            source_fields,
646            vec![
647                Arc::new(Int32Array::from(vec![Some(3)])),
648                Arc::new(Int32Array::from(vec![Some(4)])),
649            ],
650            None,
651        );
652
653        let value = ColumnarValue::Array(Arc::new(struct_array));
654        let casted = value
655            .cast_to(&DataType::Struct(target_fields.clone()), None)
656            .expect("struct cast should succeed");
657
658        let ColumnarValue::Array(arr) = casted else {
659            panic!("expected array after cast");
660        };
661
662        let struct_array = arr
663            .as_any()
664            .downcast_ref::<StructArray>()
665            .expect("expected StructArray");
666
667        let field_a = struct_array
668            .column_by_name("a")
669            .expect("expected field a in cast result");
670        let field_b = struct_array
671            .column_by_name("b")
672            .expect("expected field b in cast result");
673
674        assert_eq!(
675            field_a
676                .as_any()
677                .downcast_ref::<Int32Array>()
678                .expect("expected Int32 array")
679                .value(0),
680            4
681        );
682        assert_eq!(
683            field_b
684                .as_any()
685                .downcast_ref::<Int32Array>()
686                .expect("expected Int32 array")
687                .value(0),
688            3
689        );
690    }
691
692    #[test]
693    fn cast_struct_missing_field_inserts_nulls() {
694        let source_fields = Fields::from(vec![Field::new("a", DataType::Int32, true)]);
695
696        let target_fields = Fields::from(vec![
697            Field::new("a", DataType::Int32, true),
698            Field::new("b", DataType::Int32, true),
699        ]);
700
701        let struct_array = StructArray::new(
702            source_fields,
703            vec![Arc::new(Int32Array::from(vec![Some(5)]))],
704            None,
705        );
706
707        let value = ColumnarValue::Array(Arc::new(struct_array));
708        let casted = value
709            .cast_to(&DataType::Struct(target_fields.clone()), None)
710            .expect("struct cast should succeed");
711
712        let ColumnarValue::Array(arr) = casted else {
713            panic!("expected array after cast");
714        };
715
716        let struct_array = arr
717            .as_any()
718            .downcast_ref::<StructArray>()
719            .expect("expected StructArray");
720
721        let field_b = struct_array
722            .column_by_name("b")
723            .expect("expected missing field to be added");
724
725        assert!(field_b.is_null(0));
726    }
727
728    #[test]
729    fn cast_date64_array_to_timestamp_overflow() {
730        let overflow_value = i64::MAX / 1_000_000 + 1;
731        let array: ArrayRef = Arc::new(Date64Array::from(vec![Some(overflow_value)]));
732        let value = ColumnarValue::Array(array);
733        let result =
734            value.cast_to(&DataType::Timestamp(TimeUnit::Nanosecond, None), None);
735        let err = result.expect_err("expected overflow to be detected");
736        assert!(
737            err.to_string()
738                .contains("converted value exceeds the representable i64 range"),
739            "unexpected error: {err}"
740        );
741    }
742
743    #[test]
744    fn cast_timestamp_array_to_timestamp_overflow() {
745        let overflow_value = i64::MAX / 1_000_000_000 + 1;
746        let array: ArrayRef =
747            Arc::new(TimestampSecondArray::from(vec![Some(overflow_value)]));
748        let value = ColumnarValue::Array(array);
749        let result =
750            value.cast_to(&DataType::Timestamp(TimeUnit::Nanosecond, None), None);
751        let err = result.expect_err("expected overflow to be detected");
752        assert!(
753            err.to_string()
754                .contains("converted value exceeds the representable i64 range"),
755            "unexpected error: {err}"
756        );
757    }
758
759    #[test]
760    fn safe_cast_timestamp_array_to_timestamp_overflow_returns_null() {
761        let overflow_value = i64::MAX / 1_000_000_000 + 1;
762        let array: ArrayRef =
763            Arc::new(TimestampSecondArray::from(vec![Some(overflow_value)]));
764        let value = ColumnarValue::Array(array);
765        let safe_options = CastOptions {
766            safe: true,
767            ..DEFAULT_CAST_OPTIONS
768        };
769
770        let casted = value
771            .cast_to(
772                &DataType::Timestamp(TimeUnit::Nanosecond, None),
773                Some(&safe_options),
774            )
775            .expect("expected safe cast to return null");
776
777        let ColumnarValue::Array(array) = casted else {
778            panic!("expected array after cast");
779        };
780        let array = array
781            .as_any()
782            .downcast_ref::<TimestampNanosecondArray>()
783            .expect("expected TimestampNanosecondArray");
784        assert!(array.is_null(0));
785    }
786}