Skip to main content

datafusion_physical_expr/expressions/
cast.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
5use std::fmt;
6use std::hash::Hash;
7use std::sync::Arc;
8
9use crate::physical_expr::PhysicalExpr;
10
11use arrow::compute::{CastOptions, can_cast_types};
12use arrow::datatypes::{DataType, DataType::*, Field, FieldRef, Metadata, Schema};
13use arrow::record_batch::RecordBatch;
14use arrow::util::display::{ArrayFormatterFactory, DurationFormat, FormatOptions};
15use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
16use datafusion_common::datatype::DataTypeExt;
17use datafusion_common::format::DEFAULT_FORMAT_OPTIONS;
18use datafusion_common::nested_struct::{
19    requires_nested_struct_cast, validate_data_type_compatibility,
20};
21use datafusion_common::{Result, not_impl_err};
22use datafusion_expr_common::columnar_value::ColumnarValue;
23use datafusion_expr_common::interval_arithmetic::Interval;
24use datafusion_expr_common::sort_properties::ExprProperties;
25
26const DEFAULT_CAST_OPTIONS: CastOptions<'static> = CastOptions {
27    safe: false,
28    format_options: DEFAULT_FORMAT_OPTIONS,
29};
30
31const DEFAULT_SAFE_CAST_OPTIONS: CastOptions<'static> = CastOptions {
32    safe: true,
33    format_options: DEFAULT_FORMAT_OPTIONS,
34};
35
36/// Owns Arrow's borrowed format strings so protobuf decoding does not leak them.
37#[derive(Debug, Clone)]
38struct OwnedCastOptions {
39    safe: bool,
40    format_safe: bool,
41    null: String,
42    date_format: Option<String>,
43    datetime_format: Option<String>,
44    timestamp_format: Option<String>,
45    timestamp_tz_format: Option<String>,
46    time_format: Option<String>,
47    duration_format: DurationFormat,
48    types_info: bool,
49    quoted_strings: bool,
50    formatter_factory: Option<&'static dyn ArrayFormatterFactory>,
51}
52
53impl From<CastOptions<'static>> for OwnedCastOptions {
54    fn from(options: CastOptions<'static>) -> Self {
55        let CastOptions {
56            safe,
57            format_options,
58        } = options;
59        Self {
60            safe,
61            format_safe: format_options.safe(),
62            null: format_options.null().to_owned(),
63            date_format: format_options.date_format().map(str::to_owned),
64            datetime_format: format_options.datetime_format().map(str::to_owned),
65            timestamp_format: format_options.timestamp_format().map(str::to_owned),
66            timestamp_tz_format: format_options.timestamp_tz_format().map(str::to_owned),
67            time_format: format_options.time_format().map(str::to_owned),
68            duration_format: format_options.duration_format(),
69            types_info: format_options.types_info(),
70            quoted_strings: format_options.quoted_strings(),
71            formatter_factory: format_options.formatter_factory(),
72        }
73    }
74}
75
76impl OwnedCastOptions {
77    fn as_arrow(&self) -> CastOptions<'_> {
78        let Self {
79            safe,
80            format_safe,
81            null,
82            date_format,
83            datetime_format,
84            timestamp_format,
85            timestamp_tz_format,
86            time_format,
87            duration_format,
88            types_info,
89            quoted_strings,
90            formatter_factory,
91        } = self;
92        CastOptions {
93            safe: *safe,
94            format_options: FormatOptions::new()
95                .with_display_error(*format_safe)
96                .with_null(null)
97                .with_date_format(date_format.as_deref())
98                .with_datetime_format(datetime_format.as_deref())
99                .with_timestamp_format(timestamp_format.as_deref())
100                .with_timestamp_tz_format(timestamp_tz_format.as_deref())
101                .with_time_format(time_format.as_deref())
102                .with_duration_format(*duration_format)
103                .with_types_info(*types_info)
104                .with_quoted_strings(*quoted_strings)
105                .with_formatter_factory(*formatter_factory),
106        }
107    }
108}
109
110impl PartialEq for OwnedCastOptions {
111    fn eq(&self, other: &Self) -> bool {
112        self.as_arrow() == other.as_arrow()
113    }
114}
115
116impl Eq for OwnedCastOptions {}
117
118impl Hash for OwnedCastOptions {
119    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
120        self.as_arrow().hash(state);
121    }
122}
123
124/// Check if name-based struct casting is allowed by validating field compatibility.
125///
126/// This function applies the same validation rules as execution time to ensure
127/// planning-time validation matches runtime validation, enabling fail-fast behavior
128/// instead of deferring errors to execution. Handles structs at any nesting level
129/// (e.g., `List<Struct>`, `Dictionary<_, Struct>`).
130fn can_cast_named_struct_types(source: &DataType, target: &DataType) -> bool {
131    validate_data_type_compatibility("", source, target).is_ok()
132}
133
134/// CAST expression casts an expression to a specific data type and returns a runtime error on invalid cast
135#[derive(Debug, Clone, Eq)]
136pub struct CastExpr {
137    /// The expression to cast
138    pub expr: Arc<dyn PhysicalExpr>,
139    /// The target field.
140    ///
141    /// For a type-only cast (see [`CastExpr::new`]) this is a field synthesized
142    /// from the target data type alone and only its data type is meaningful.
143    /// For a cast built from an explicit field (see
144    /// [`CastExpr::new_with_target_field`]) its metadata and nullability are
145    /// applied to the output field as-is.
146    target_field: FieldRef,
147    /// Whether `target_field` was supplied by the caller (as opposed to being
148    /// synthesized from a `DataType`), and therefore whether its metadata and
149    /// nullability describe the output field exactly.
150    explicit_target: bool,
151    /// Cast options
152    cast_options: OwnedCastOptions,
153}
154
155// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
156impl PartialEq for CastExpr {
157    fn eq(&self, other: &Self) -> bool {
158        // Compare the semantically meaningful parts of the target field only:
159        // the field name never affects the output of this expression.
160        self.expr.eq(&other.expr)
161            && self.cast_type().eq(other.cast_type())
162            && self.target_metadata().eq(&other.target_metadata())
163            && self.target_nullable().eq(&other.target_nullable())
164            && self.cast_options.eq(&other.cast_options)
165    }
166}
167
168impl Hash for CastExpr {
169    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
170        self.expr.hash(state);
171        self.cast_type().hash(state);
172        // Hash the metadata by iterating over sorted keys for deterministic ordering
173        if let Some(metadata) = self.target_metadata() {
174            let mut entries: Vec<_> = metadata.iter().collect();
175            entries.sort_by_key(|(k, _)| *k);
176            for (k, v) in entries {
177                k.hash(state);
178                v.hash(state);
179            }
180        }
181        self.target_nullable().hash(state);
182        self.cast_options.hash(state);
183    }
184}
185
186impl CastExpr {
187    /// Create a new `CastExpr` using only a `DataType`.
188    ///
189    /// This constructor creates a type-only cast where metadata and nullability
190    /// are passed through from the source expression (with extension type keys
191    /// stripped from metadata). This is the most common use case when you only
192    /// need to change the data type.
193    ///
194    /// For explicit control over the output field's metadata and nullability,
195    /// use [`CastExpr::new_with_target_field`] or the individual builder methods.
196    pub fn new(
197        expr: Arc<dyn PhysicalExpr>,
198        cast_type: DataType,
199        cast_options: Option<CastOptions<'static>>,
200    ) -> Self {
201        Self {
202            expr,
203            target_field: cast_type.into_nullable_field_ref(),
204            explicit_target: false,
205            cast_options: cast_options.unwrap_or(DEFAULT_CAST_OPTIONS).into(),
206        }
207    }
208
209    /// Create a new `CastExpr` with an explicit target `FieldRef`.
210    ///
211    /// The provided `target_field` determines the output characteristics:
212    /// - The field's data type becomes the cast target type
213    /// - The field's metadata is used exactly as provided
214    /// - The field's nullability is preserved
215    ///
216    /// This is the preferred constructor when the caller has explicit field
217    /// information that should be used exactly (for example, during schema
218    /// enforcement or adapter layers).
219    ///
220    /// See [`CastExpr::new`] for type-only casts where source metadata should
221    /// pass through.
222    pub fn new_with_target_field(
223        expr: Arc<dyn PhysicalExpr>,
224        target_field: FieldRef,
225        cast_options: Option<CastOptions<'static>>,
226    ) -> Self {
227        Self {
228            expr,
229            target_field,
230            explicit_target: true,
231            cast_options: cast_options.unwrap_or(DEFAULT_CAST_OPTIONS).into(),
232        }
233    }
234
235    /// The expression to cast
236    pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
237        &self.expr
238    }
239
240    /// The data type to cast to
241    pub fn cast_type(&self) -> &DataType {
242        self.target_field.data_type()
243    }
244
245    /// Explicit metadata for the output field, or `None` to pass through source metadata.
246    pub fn target_metadata(&self) -> Option<&Metadata> {
247        self.explicit_target.then(|| self.target_field.metadata())
248    }
249
250    /// Explicit nullability for the output field, or `None` to pass through source nullability.
251    pub fn target_nullable(&self) -> Option<bool> {
252        self.explicit_target
253            .then(|| self.target_field.is_nullable())
254    }
255
256    /// The target field this cast was constructed with.
257    ///
258    /// For a type-only cast this is a field synthesized from the target data
259    /// type alone; only its data type is meaningful. Note that the returned
260    /// field may not match what `return_field()` returns when evaluated against
261    /// a schema, since `return_field()` may incorporate source field information.
262    ///
263    /// Prefer [`cast_type()`], [`target_metadata()`], and [`target_nullable()`]
264    /// for direct access to the individual components.
265    ///
266    /// [`cast_type()`]: CastExpr::cast_type
267    /// [`target_metadata()`]: CastExpr::target_metadata
268    /// [`target_nullable()`]: CastExpr::target_nullable
269    pub fn target_field(&self) -> &FieldRef {
270        &self.target_field
271    }
272
273    /// The cast options, borrowing custom format strings from this expression.
274    pub fn cast_options(&self) -> CastOptions<'_> {
275        self.cast_options.as_arrow()
276    }
277
278    /// Rebuild this cast with a new child and explicit target while preserving its options.
279    pub fn with_new_expr_and_target_field(
280        &self,
281        expr: Arc<dyn PhysicalExpr>,
282        target_field: FieldRef,
283    ) -> Self {
284        Self {
285            expr,
286            target_field,
287            explicit_target: true,
288            cast_options: self.cast_options.clone(),
289        }
290    }
291
292    /// Whether this cast has explicit metadata (vs pass-through from source).
293    pub fn has_explicit_metadata(&self) -> bool {
294        self.explicit_target
295    }
296
297    /// Whether this cast has explicit nullability (vs pass-through from source).
298    pub fn has_explicit_nullability(&self) -> bool {
299        self.explicit_target
300    }
301
302    fn resolved_target_field(&self, input_schema: &Schema) -> Result<FieldRef> {
303        // Try to get the source field for the name. If the target field is
304        // explicit, we can fall back to an empty name if the source lookup fails
305        // (e.g., for virtual row-index columns appended at scan time).
306        let source_result = self.expr.return_field(input_schema);
307
308        if self.explicit_target {
309            // Metadata and nullability come from the target field verbatim
310            let name = source_result
311                .as_ref()
312                .map(|f| f.name().to_string())
313                .unwrap_or_default();
314            return Ok(Arc::new(
315                Field::new(
316                    name,
317                    self.cast_type().clone(),
318                    self.target_field.is_nullable(),
319                )
320                .with_metadata(self.target_field.metadata().clone()),
321            ));
322        }
323
324        // Type-only cast: pass through the source metadata and nullability,
325        // stripping extension type keys (the cast is to a plain storage type).
326        source_result.map(|source_field| {
327            let mut metadata = source_field.metadata().clone();
328            metadata.remove(EXTENSION_TYPE_NAME_KEY);
329            metadata.remove(EXTENSION_TYPE_METADATA_KEY);
330
331            Arc::new(
332                source_field
333                    .as_ref()
334                    .clone()
335                    .with_data_type(self.cast_type().clone())
336                    .with_metadata(metadata),
337            )
338        })
339    }
340
341    /// Check if casting from the source type to the target type is known to be
342    /// lossless and strictly order-preserving for all source values, preserving nulls.
343    /// This includes widening casts (e.g. `Int8` or `UInt8` to `Int16`) and representation
344    /// conversions such as `Int32` to `Date32`, which interprets the same integer
345    /// as days since the epoch, or `Int64` to `Date64`, which interprets the same
346    /// integer as milliseconds since the epoch.
347    pub fn check_bigger_cast(cast_type: &DataType, src: &DataType) -> bool {
348        if cast_type.eq(src) {
349            return true;
350        }
351        matches!(
352            (src, cast_type),
353            (Int8, Int16 | Int32 | Int64)
354                | (Int16, Int32 | Int64)
355                | (Int32, Int64)
356                | (Int32, Date32)
357                | (Date32, Int32)
358                | (Int64, Date64)
359                | (Date64, Int64)
360                | (UInt8, UInt16 | UInt32 | UInt64 | Int16 | Int32 | Int64)
361                | (UInt16, UInt32 | UInt64 | Int32 | Int64)
362                | (UInt32, UInt64 | Int64)
363                | (Int8 | Int16 | UInt8 | UInt16, Float32)
364                | (Int8 | Int16 | Int32 | UInt8 | UInt16 | UInt32, Float64)
365                | (Utf8, LargeUtf8 | Utf8View)
366                | (Binary, LargeBinary | BinaryView)
367        )
368    }
369
370    /// Check if the cast is lossless and strictly order-preserving for all source
371    /// values, preserving nulls. See [`Self::check_bigger_cast`].
372    pub fn is_bigger_cast(&self, src: &DataType) -> bool {
373        Self::check_bigger_cast(self.cast_type(), src)
374    }
375}
376
377/// UTC and fixed offsets have no timezone transitions.
378fn is_fixed_offset(tz: &str) -> bool {
379    tz == "UTC" || tz.starts_with(['+', '-'])
380}
381
382/// Whether successful casts preserve order when conversion failures return errors.
383/// Unlike `check_bigger_cast`, this allows precision loss and is not sufficient
384/// for propagating distinct counts or the ordering of subsequent sort keys.
385fn is_order_preserving_cast(source_type: &DataType, target_type: &DataType) -> bool {
386    use arrow::datatypes::TimeUnit::*;
387    if source_type == target_type
388        || (source_type.is_numeric() || *source_type == Boolean)
389            && target_type.is_numeric()
390    {
391        return true;
392    }
393    // Temporal casts are not generally monotonic: extracting time-of-day wraps
394    // at midnight, and timezone transitions can reverse the local date.
395    match (source_type, target_type) {
396        (Date32 | Date64, Date32 | Date64)
397        | (Date32 | Date64, Timestamp(_, None))
398        | (Timestamp(_, None), Date32) => true,
399        (Timestamp(_, Some(tz)), Date32) => is_fixed_offset(tz),
400        // Arrow converts timestamps to Date64 by scaling the epoch value,
401        // whereas Date32 extracts the date in the timestamp's timezone.
402        (Timestamp(_, _), Date64) => true,
403        // Only admit scaling that cannot wrap on overflow. Time64 widening
404        // and narrowing to Time32 do not currently check overflow in Arrow.
405        (Time32(Second | Millisecond), Time32(Second | Millisecond))
406        | (Time32(Second | Millisecond), Time64(Microsecond | Nanosecond))
407        | (Time64(Nanosecond), Time64(Microsecond))
408        | (Duration(_), Duration(_)) => true,
409        (Timestamp(_, from_tz), Timestamp(_, to_tz)) => {
410            // Adding a timezone to naive timestamps interprets local times;
411            // other timezone changes only change metadata on the epoch value.
412            from_tz.is_some() || to_tz.as_deref().is_none_or(is_fixed_offset)
413        }
414        _ => false,
415    }
416}
417
418pub(crate) fn cast_expr_properties(
419    child: &ExprProperties,
420    target_type: &DataType,
421    null_on_failure: bool,
422) -> Result<ExprProperties> {
423    let unbounded = Interval::make_unbounded(target_type)?;
424    let source_type = child.range.data_type();
425    // A lossless cast recognized by check_bigger_cast is one-to-one, so it is
426    // strictly order-preserving; a narrowing cast may collapse distinct values,
427    // breaking the ordering of subsequent sort keys.
428    let bigger_cast = CastExpr::check_bigger_cast(target_type, &source_type);
429    // New NULLs from failed conversions may violate NULLS FIRST/LAST, even
430    // if the successfully converted values remain ordered.
431    if bigger_cast
432        || (!null_on_failure && is_order_preserving_cast(&source_type, target_type))
433    {
434        Ok(child
435            .clone()
436            .with_range(unbounded)
437            .with_strictly_order_preserving(
438                child.strictly_order_preserving && bigger_cast,
439            ))
440    } else {
441        Ok(ExprProperties::new_unknown().with_range(unbounded))
442    }
443}
444
445#[cfg(feature = "proto")]
446fn serialize_cast_options(
447    options: &OwnedCastOptions,
448) -> Result<Option<datafusion_proto_models::protobuf::PhysicalCastOptions>> {
449    use datafusion_proto_models::protobuf;
450
451    let options = options.as_arrow();
452    if options.format_options.formatter_factory().is_some() {
453        return not_impl_err!(
454            "CastExpr serialization does not support a custom formatter_factory"
455        );
456    }
457    if options == DEFAULT_CAST_OPTIONS {
458        return Ok(None);
459    }
460
461    let CastOptions {
462        safe,
463        format_options,
464    } = options;
465    let duration_format = match format_options.duration_format() {
466        DurationFormat::ISO8601 => protobuf::PhysicalDurationFormat::Iso8601,
467        DurationFormat::Pretty => protobuf::PhysicalDurationFormat::Pretty,
468        _ => {
469            return not_impl_err!(
470                "CastExpr serialization does not support this duration format"
471            );
472        }
473    };
474
475    Ok(Some(protobuf::PhysicalCastOptions {
476        safe,
477        format_options: Some(protobuf::PhysicalFormatOptions {
478            safe: format_options.safe(),
479            null: format_options.null().to_owned(),
480            date_format: format_options.date_format().map(str::to_owned),
481            datetime_format: format_options.datetime_format().map(str::to_owned),
482            timestamp_format: format_options.timestamp_format().map(str::to_owned),
483            timestamp_tz_format: format_options.timestamp_tz_format().map(str::to_owned),
484            time_format: format_options.time_format().map(str::to_owned),
485            duration_format: duration_format.into(),
486            types_info: format_options.types_info(),
487            quoted_strings: format_options.quoted_strings(),
488        }),
489    }))
490}
491
492#[cfg(feature = "proto")]
493fn deserialize_cast_options(
494    options: Option<&datafusion_proto_models::protobuf::PhysicalCastOptions>,
495) -> Result<OwnedCastOptions> {
496    use datafusion_common::internal_datafusion_err;
497    use datafusion_proto_models::protobuf;
498
499    let Some(options) = options else {
500        return Ok(DEFAULT_CAST_OPTIONS.into());
501    };
502    let protobuf::PhysicalCastOptions {
503        safe,
504        format_options,
505    } = options;
506    let format_options = format_options.as_ref().ok_or_else(|| {
507        internal_datafusion_err!(
508            "CastExpr cast_options is missing required field 'format_options'"
509        )
510    })?;
511    let protobuf::PhysicalFormatOptions {
512        safe: format_safe,
513        null,
514        date_format,
515        datetime_format,
516        timestamp_format,
517        timestamp_tz_format,
518        time_format,
519        duration_format,
520        types_info,
521        quoted_strings,
522    } = format_options;
523    let duration_format = match protobuf::PhysicalDurationFormat::try_from(
524        *duration_format,
525    )
526    .map_err(|_| {
527        internal_datafusion_err!(
528            "CastExpr has invalid duration format value {duration_format}"
529        )
530    })? {
531        protobuf::PhysicalDurationFormat::Iso8601 => DurationFormat::ISO8601,
532        protobuf::PhysicalDurationFormat::Pretty => DurationFormat::Pretty,
533    };
534
535    Ok(OwnedCastOptions {
536        safe: *safe,
537        format_safe: *format_safe,
538        null: null.clone(),
539        date_format: date_format.clone(),
540        datetime_format: datetime_format.clone(),
541        timestamp_format: timestamp_format.clone(),
542        timestamp_tz_format: timestamp_tz_format.clone(),
543        time_format: time_format.clone(),
544        duration_format,
545        types_info: *types_info,
546        quoted_strings: *quoted_strings,
547        // Runtime formatter factories have no protobuf representation; the
548        // encoder rejects them rather than silently dropping behavior.
549        formatter_factory: None,
550    })
551}
552
553impl fmt::Display for CastExpr {
554    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
555        write!(f, "CAST({} AS {}", self.expr, self.cast_type())?;
556        // A cast to an explicit field can change only the nullability (for
557        // example when a union aligns its inputs), so show it the way schemas
558        // do: `;N` marks a nullable field.
559        if self.explicit_target && self.target_field.is_nullable() {
560            write!(f, ";N")?;
561        }
562        write!(f, ")")
563    }
564}
565
566impl PhysicalExpr for CastExpr {
567    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
568        Ok(self.cast_type().clone())
569    }
570
571    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
572        // A cast is nullable if **either** the child is nullable or the
573        // target field allows nulls.  This conservative rule prevents
574        // optimizers from assuming a non-null result when a null input could
575        // still propagate.  `return_field()` continues to expose the exact
576        // target metadata separately.
577        let child_nullable = self.expr.nullable(input_schema)?;
578        let target_nullable = self.resolved_target_field(input_schema)?.is_nullable();
579        Ok(child_nullable || target_nullable)
580    }
581
582    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
583        let value = self.expr.evaluate(batch)?;
584        let cast_options = self.cast_options();
585        value
586            .cast_to(self.cast_type(), Some(&cast_options))
587            .map_err(|error| {
588                let source = self
589                    .expr
590                    .return_field(batch.schema().as_ref())
591                    .ok()
592                    .filter(|field| !field.name().is_empty())
593                    .map(|field| format!("field '{}'", field.name()))
594                    .unwrap_or_else(|| format!("expression '{}'", self.expr));
595                error.context(format!(
596                    "Failed to cast {source} from {} to {}",
597                    value.data_type(),
598                    self.cast_type()
599                ))
600            })
601    }
602
603    fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
604        self.resolved_target_field(input_schema)
605    }
606
607    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
608        vec![&self.expr]
609    }
610
611    fn with_new_children(
612        self: Arc<Self>,
613        children: Vec<Arc<dyn PhysicalExpr>>,
614    ) -> Result<Arc<dyn PhysicalExpr>> {
615        Ok(Arc::new(CastExpr {
616            expr: Arc::clone(&children[0]),
617            target_field: Arc::clone(&self.target_field),
618            explicit_target: self.explicit_target,
619            cast_options: self.cast_options.clone(),
620        }))
621    }
622
623    fn evaluate_bounds(&self, children: &[&Interval]) -> Result<Interval> {
624        // Cast current node's interval to the right type:
625        children[0].cast_to(self.cast_type(), &self.cast_options())
626    }
627
628    fn propagate_constraints(
629        &self,
630        interval: &Interval,
631        children: &[&Interval],
632    ) -> Result<Option<Vec<Interval>>> {
633        let source_type = children[0].data_type();
634        let target_type = self.cast_type();
635        if !can_propagate_cast_constraints(&source_type, target_type) {
636            return Ok(Some(vec![]));
637        }
638        Ok(Some(vec![
639            interval.cast_to(&source_type, &DEFAULT_SAFE_CAST_OPTIONS)?,
640        ]))
641    }
642
643    /// Propagate ordering only for supported order-preserving conversions.
644    fn get_properties(&self, children: &[ExprProperties]) -> Result<ExprProperties> {
645        cast_expr_properties(&children[0], self.cast_type(), self.cast_options.safe)
646    }
647
648    fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
649        write!(f, "CAST(")?;
650        self.expr.fmt_sql(f)?;
651        write!(f, " AS {:?}", self.cast_type())?;
652
653        write!(f, ")")
654    }
655
656    #[cfg(feature = "proto")]
657    fn try_to_proto(
658        &self,
659        ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
660    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
661        use datafusion_proto_models::protobuf;
662
663        let Self {
664            expr,
665            target_field,
666            explicit_target,
667            cast_options,
668        } = self;
669        // Presence carries `explicit_target`, even for a default-shaped field.
670        let target_field_proto = if *explicit_target {
671            Some(target_field.as_ref().try_into()?)
672        } else {
673            None
674        };
675        let cast_options_proto = serialize_cast_options(cast_options)?;
676
677        Ok(Some(protobuf::PhysicalExprNode {
678            expr_id: None,
679            expr_type: Some(protobuf::physical_expr_node::ExprType::Cast(Box::new(
680                protobuf::PhysicalCastNode {
681                    expr: Some(Box::new(ctx.encode_child(expr)?)),
682                    arrow_type: Some(target_field.data_type().try_into()?),
683                    target_field: target_field_proto,
684                    cast_options: cast_options_proto,
685                },
686            ))),
687        }))
688    }
689}
690
691/// Whether output bounds can be cast back to `source` without excluding valid inputs.
692///
693/// Used for reverse constraint propagation through a cast from `source` to `target`.
694/// Many-to-one casts, such as Float64 to Int32, cannot generally be inverted this way:
695/// an output of 0 does not imply an input of 0.0.
696/// Returns false for unrecognized conversions so the input range remains unchanged.
697fn can_propagate_cast_constraints(source: &DataType, target: &DataType) -> bool {
698    CastExpr::check_bigger_cast(target, source)
699        || (source.is_integer() && target.is_integer())
700        // NaN bounds are unbounded; finite Float32 values widen exactly.
701        || (*source == Float32 && *target == Float64)
702}
703
704#[cfg(feature = "proto")]
705impl CastExpr {
706    /// Reconstruct a [`CastExpr`] from its protobuf representation.
707    ///
708    /// Takes the whole [`PhysicalExprNode`] so the decode signature matches
709    /// other migrated expressions and can inspect outer-node metadata if
710    /// needed in the future.
711    ///
712    /// [`PhysicalExprNode`]: datafusion_proto_models::protobuf::PhysicalExprNode
713    pub fn try_from_proto(
714        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
715        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
716    ) -> Result<Arc<dyn PhysicalExpr>> {
717        use datafusion_common::internal_err;
718        use datafusion_physical_expr_common::expect_expr_variant;
719        use datafusion_physical_expr_common::physical_expr::proto_decode::require_proto_field;
720        use datafusion_proto_models::protobuf;
721
722        let cast_expr = expect_expr_variant!(
723            node,
724            protobuf::physical_expr_node::ExprType::Cast,
725            "CastExpr",
726        );
727        let protobuf::PhysicalCastNode {
728            expr,
729            arrow_type,
730            target_field,
731            cast_options,
732        } = &**cast_expr;
733        let expr = ctx.decode_required_expression(expr.as_deref(), "CastExpr", "expr")?;
734        let arrow_type =
735            require_proto_field(arrow_type.as_ref(), "CastExpr", "arrow_type")?;
736        let cast_type: DataType = arrow_type.try_into()?;
737        let target_field = target_field
738            .as_ref()
739            .map(|field| {
740                let field: Field = field.try_into()?;
741                if field.data_type() != &cast_type {
742                    return internal_err!(
743                        "CastExpr target_field type does not match arrow_type"
744                    );
745                }
746                Ok(Arc::new(field))
747            })
748            .transpose()?;
749        let cast_options = deserialize_cast_options(cast_options.as_ref())?;
750        let (target_field, explicit_target) = match target_field {
751            Some(target_field) => (target_field, true),
752            None => (cast_type.into_nullable_field_ref(), false),
753        };
754
755        Ok(Arc::new(CastExpr {
756            expr,
757            target_field,
758            explicit_target,
759            cast_options,
760        }))
761    }
762}
763
764/// Return a PhysicalExpression representing `expr` casted to
765/// `cast_type`, if any casting is needed.
766///
767/// Note that such casts may lose type information
768pub fn cast_with_options(
769    expr: Arc<dyn PhysicalExpr>,
770    input_schema: &Schema,
771    cast_type: DataType,
772    cast_options: Option<CastOptions<'static>>,
773) -> Result<Arc<dyn PhysicalExpr>> {
774    let expr_type = expr.data_type(input_schema)?;
775
776    // If the types match, no cast is needed for a type-only cast
777    if expr_type == cast_type {
778        return Ok(Arc::clone(&expr));
779    }
780
781    let can_build_cast = if requires_nested_struct_cast(&expr_type, &cast_type) {
782        can_cast_named_struct_types(&expr_type, &cast_type)
783    } else {
784        can_cast_types(&expr_type, &cast_type)
785    };
786
787    if !can_build_cast {
788        return not_impl_err!("Unsupported CAST from {expr_type} to {cast_type}");
789    }
790
791    Ok(Arc::new(CastExpr::new(expr, cast_type, cast_options)))
792}
793
794/// Return a PhysicalExpression representing `expr` casted to `target_field`,
795/// preserving any explicit field semantics such as name, nullability, and
796/// metadata.
797///
798/// If the input expression already has the same data type and the target field
799/// has no explicit metadata or nullability constraints, the original expression
800/// is returned unchanged.
801pub fn cast_with_target_field(
802    expr: Arc<dyn PhysicalExpr>,
803    input_schema: &Schema,
804    target_field: &FieldRef,
805    cast_options: Option<CastOptions<'static>>,
806) -> Result<Arc<dyn PhysicalExpr>> {
807    let expr_type = expr.data_type(input_schema)?;
808    let cast_type = target_field.data_type();
809
810    // Check if this is a "default" target field (type-only cast with no explicit
811    // metadata or nullability constraints). This is the field created by
812    // `into_nullable_field_ref()` when only a DataType is known.
813    let is_type_only = target_field.name().is_empty()
814        && target_field.is_nullable()
815        && target_field.metadata().is_empty();
816
817    // For same-type casts, we can skip creating a CastExpr only if:
818    // 1. The target is type-only (no explicit metadata)
819    // 2. The source has no extension metadata that needs to be stripped
820    // Otherwise we need the CastExpr to strip extension metadata from the source.
821    if expr_type == *cast_type && is_type_only {
822        let source_field = expr.return_field(input_schema)?;
823        let has_extension_metadata = source_field
824            .metadata()
825            .contains_key(EXTENSION_TYPE_NAME_KEY);
826        if !has_extension_metadata {
827            return Ok(Arc::clone(&expr));
828        }
829    }
830
831    let can_build_cast = if requires_nested_struct_cast(&expr_type, cast_type) {
832        // Allow casts involving structs (including nested inside Lists, Dictionaries,
833        // etc.) that pass name-based compatibility validation. This validation is
834        // applied at planning time (now) to fail fast, rather than deferring errors
835        // to execution time. The name-based casting logic will be executed at runtime
836        // via ColumnarValue::cast_to.
837        can_cast_named_struct_types(&expr_type, cast_type)
838    } else {
839        can_cast_types(&expr_type, cast_type)
840    };
841
842    if !can_build_cast {
843        return not_impl_err!("Unsupported CAST from {expr_type} to {cast_type}");
844    }
845
846    // For type-only casts, use CastExpr::new which preserves source metadata/nullability.
847    // For explicit target fields, use new_with_target_field which applies the target's
848    // extension metadata and nullability.
849    if is_type_only {
850        Ok(Arc::new(CastExpr::new(
851            expr,
852            cast_type.clone(),
853            cast_options,
854        )))
855    } else {
856        Ok(Arc::new(CastExpr::new_with_target_field(
857            expr,
858            Arc::clone(target_field),
859            cast_options,
860        )))
861    }
862}
863
864/// Return a PhysicalExpression representing `expr` casted to
865/// `cast_type`, if any casting is needed.
866///
867/// Note that such casts may lose type information
868pub fn cast(
869    expr: Arc<dyn PhysicalExpr>,
870    input_schema: &Schema,
871    cast_type: DataType,
872) -> Result<Arc<dyn PhysicalExpr>> {
873    cast_with_options(expr, input_schema, cast_type, None)
874}
875
876#[cfg(test)]
877mod tests {
878    use super::*;
879
880    use crate::expressions::column::col;
881
882    use arrow::{
883        array::{
884            Array, ArrayRef, Decimal128Array, Float32Array, Float64Array, Int8Array,
885            Int16Array, Int32Array, Int64Array, StringArray, StructArray,
886            Time64NanosecondArray, TimestampNanosecondArray, UInt32Array,
887        },
888        datatypes::*,
889    };
890    use datafusion_common::ScalarValue;
891    use datafusion_common::cast::{
892        as_boolean_array, as_int64_array, as_string_array, as_struct_array,
893        as_uint8_array,
894    };
895    use datafusion_common::rounding::{next_down, next_up};
896    use datafusion_physical_expr_common::physical_expr::fmt_sql;
897    use insta::assert_snapshot;
898    use std::collections::HashMap;
899
900    #[test]
901    fn test_cast_constraint_propagation() -> Result<()> {
902        for (source, target, propagates) in [
903            (Utf8, Int32, false),
904            (Utf8View, Int32, false),
905            (Timestamp(TimeUnit::Nanosecond, None), Date32, false),
906            (Int32, Date32, true),
907            (Date32, Int32, true),
908            (Utf8, LargeUtf8, true),
909            (Utf8, Utf8, true),
910            (Float64, Int32, false),
911            (Int64, Float32, false),
912            (Float64, Float32, false),
913            (Decimal128(4, 1), Decimal128(4, 0), false),
914            (Decimal128(4, 1), Int32, false),
915            (Float64, Decimal128(4, 1), false),
916            (Int8, Int64, true),
917            (Int64, Int8, true),
918            (Int32, UInt32, true),
919            (UInt32, Int32, true),
920            (Int32, Float64, true),
921            (Float32, Float64, true),
922            (Decimal128(4, 1), Decimal128(4, 1), true),
923        ] {
924            let schema = Schema::new(vec![Field::new("x", source.clone(), true)]);
925            let expr = CastExpr::new(col("x", &schema)?, target.clone(), None);
926            let input = Interval::make_unbounded(&source)?;
927            let value = ScalarValue::Int32(Some(0)).cast_to(&target)?;
928            let output = Interval::from(&value);
929            let expected = if propagates {
930                vec![Interval::from(&value.cast_to(&source)?)]
931            } else {
932                vec![]
933            };
934            assert_eq!(
935                expr.propagate_constraints(&output, &[&input])?,
936                Some(expected),
937                "{source} -> {target}"
938            );
939        }
940        Ok(())
941    }
942
943    #[test]
944    fn test_float_widening_constraint_boundaries() -> Result<()> {
945        let mut values = vec![
946            f32::NEG_INFINITY,
947            -f32::MAX,
948            -1.0,
949            -f32::MIN_POSITIVE,
950            -f32::from_bits(1),
951            -0.0,
952            0.0,
953            f32::from_bits(1),
954            f32::MIN_POSITIVE,
955            1.0,
956            f32::MAX,
957            f32::INFINITY,
958        ];
959        // Include both signs of signaling and quiet NaNs with distinct payloads.
960        values.extend(
961            [0x7f800001, 0x7f800002, 0x7fc00001, 0xff800001, 0xffc00001]
962                .map(f32::from_bits),
963        );
964        values.extend([next_down(1.0f32), next_up(1.0f32)]);
965        let schema = Arc::new(Schema::new(vec![Field::new("x", Float32, false)]));
966        let batch = RecordBatch::try_new(
967            Arc::clone(&schema),
968            vec![Arc::new(Float32Array::from(values.clone()))],
969        )?;
970        let expr = CastExpr::new(col("x", &schema)?, Float64, None);
971        let array = expr.evaluate(&batch)?.into_array(values.len())?;
972        let widened = array.as_any().downcast_ref::<Float64Array>().unwrap();
973        let mut bounds = vec![-f64::MAX, f64::MAX];
974        for value in widened.values() {
975            bounds.extend([next_down(*value), *value, next_up(*value)]);
976        }
977        // Midpoints exercise rounding back to Float32 in both directions.
978        bounds.extend([
979            f64::from(f32::from_bits(1)) / 2.0,
980            -f64::from(f32::from_bits(1)) / 2.0,
981            f64::midpoint(1.0, f64::from(next_up(1.0f32))),
982        ]);
983        bounds.sort_by(f64::total_cmp);
984        bounds.dedup_by(|a, b| a.to_bits() == b.to_bits());
985        let input = Interval::make_unbounded(&Float32)?;
986        for (i, lower) in bounds.iter().enumerate() {
987            for upper in &bounds[i..] {
988                let output = Interval::make(Some(*lower), Some(*upper))?;
989                let propagated = expr.propagate_constraints(&output, &[&input])?.unwrap();
990                assert_eq!(propagated.len(), 1);
991                for (index, value) in values.iter().enumerate() {
992                    if output.contains_value(ScalarValue::Float64(Some(
993                        widened.value(index),
994                    )))? {
995                        assert!(
996                            propagated[0]
997                                .contains_value(ScalarValue::Float32(Some(*value)))?,
998                            "input bits={:08x}, output={output}, propagated={:?}",
999                            value.to_bits(),
1000                            propagated[0]
1001                        );
1002                    }
1003                }
1004            }
1005        }
1006        Ok(())
1007    }
1008
1009    fn make_struct_array(fields: Fields, arrays: Vec<ArrayRef>) -> StructArray {
1010        StructArray::new(fields, arrays, None)
1011    }
1012
1013    fn cast_struct_array(
1014        column: &str,
1015        input_field: Field,
1016        target_field: Field,
1017        input_array: StructArray,
1018    ) -> Result<StructArray> {
1019        let schema = Arc::new(Schema::new(vec![input_field]));
1020        let batch = RecordBatch::try_new(
1021            Arc::clone(&schema),
1022            vec![Arc::new(input_array) as ArrayRef],
1023        )?;
1024        let expr = CastExpr::new_with_target_field(
1025            col(column, schema.as_ref())?,
1026            Arc::new(target_field),
1027            None,
1028        );
1029
1030        let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
1031        Ok(as_struct_array(result.as_ref())?.clone())
1032    }
1033
1034    // runs an end-to-end test of physical type cast
1035    // 1. construct a record batch with a column "a" of type A
1036    // 2. construct a physical expression of CAST(a AS B)
1037    // 3. evaluate the expression
1038    // 4. verify that the resulting expression is of type B
1039    // 5. verify that the resulting values are downcastable and correct
1040    macro_rules! generic_decimal_to_other_test_cast {
1041        ($DECIMAL_ARRAY:ident, $A_TYPE:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr,$CAST_OPTIONS:expr) => {{
1042            let schema = Schema::new(vec![Field::new("a", $A_TYPE, true)]);
1043            let batch = RecordBatch::try_new(
1044                Arc::new(schema.clone()),
1045                vec![Arc::new($DECIMAL_ARRAY)],
1046            )?;
1047            // verify that we can construct the expression
1048            let expression =
1049                cast_with_options(col("a", &schema)?, &schema, $TYPE, $CAST_OPTIONS)?;
1050
1051            // verify that its display is correct
1052            assert_eq!(format!("CAST(a@0 AS {})", $TYPE), format!("{}", expression));
1053
1054            // verify that the expression's type is correct
1055            assert_eq!(expression.data_type(&schema)?, $TYPE);
1056
1057            // compute
1058            let result = expression
1059                .evaluate(&batch)?
1060                .into_array(batch.num_rows())
1061                .expect("Failed to convert to array");
1062
1063            // verify that the array's data_type is correct
1064            assert_eq!(*result.data_type(), $TYPE);
1065
1066            // verify that the data itself is downcastable
1067            let result = result
1068                .as_any()
1069                .downcast_ref::<$TYPEARRAY>()
1070                .expect("failed to downcast");
1071
1072            // verify that the result itself is correct
1073            for (i, x) in $VEC.iter().enumerate() {
1074                match x {
1075                    Some(x) => assert_eq!(result.value(i), *x),
1076                    None => assert!(result.is_null(i)),
1077                }
1078            }
1079        }};
1080    }
1081
1082    // runs an end-to-end test of physical type cast
1083    // 1. construct a record batch with a column "a" of type A
1084    // 2. construct a physical expression of CAST(a AS B)
1085    // 3. evaluate the expression
1086    // 4. verify that the resulting expression is of type B
1087    // 5. verify that the resulting values are downcastable and correct
1088    macro_rules! generic_test_cast {
1089        ($A_ARRAY:ident, $A_TYPE:expr, $A_VEC:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr, $CAST_OPTIONS:expr) => {{
1090            let schema = Schema::new(vec![Field::new("a", $A_TYPE, true)]);
1091            let a_vec_len = $A_VEC.len();
1092            let a = $A_ARRAY::from($A_VEC);
1093            let batch =
1094                RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1095
1096            // verify that we can construct the expression
1097            let expression =
1098                cast_with_options(col("a", &schema)?, &schema, $TYPE, $CAST_OPTIONS)?;
1099
1100            // verify that its display is correct
1101            assert_eq!(format!("CAST(a@0 AS {})", $TYPE), format!("{}", expression));
1102
1103            // verify that the expression's type is correct
1104            assert_eq!(expression.data_type(&schema)?, $TYPE);
1105
1106            // compute
1107            let result = expression
1108                .evaluate(&batch)?
1109                .into_array(batch.num_rows())
1110                .expect("Failed to convert to array");
1111
1112            // verify that the array's data_type is correct
1113            assert_eq!(*result.data_type(), $TYPE);
1114
1115            // verify that the len is correct
1116            assert_eq!(result.len(), a_vec_len);
1117
1118            // verify that the data itself is downcastable
1119            let result = result
1120                .as_any()
1121                .downcast_ref::<$TYPEARRAY>()
1122                .expect("failed to downcast");
1123
1124            // verify that the result itself is correct
1125            for (i, x) in $VEC.iter().enumerate() {
1126                match x {
1127                    Some(x) => assert_eq!(result.value(i), *x),
1128                    None => assert!(result.is_null(i)),
1129                }
1130            }
1131        }};
1132    }
1133
1134    #[test]
1135    fn test_cast_decimal_to_decimal() -> Result<()> {
1136        let array = vec![
1137            Some(1234),
1138            Some(2222),
1139            Some(3),
1140            Some(4000),
1141            Some(5000),
1142            None,
1143        ];
1144
1145        let decimal_array = array
1146            .clone()
1147            .into_iter()
1148            .collect::<Decimal128Array>()
1149            .with_precision_and_scale(10, 3)?;
1150
1151        generic_decimal_to_other_test_cast!(
1152            decimal_array,
1153            Decimal128(10, 3),
1154            Decimal128Array,
1155            Decimal128(20, 6),
1156            [
1157                Some(1_234_000),
1158                Some(2_222_000),
1159                Some(3_000),
1160                Some(4_000_000),
1161                Some(5_000_000),
1162                None
1163            ],
1164            None
1165        );
1166
1167        let decimal_array = array
1168            .into_iter()
1169            .collect::<Decimal128Array>()
1170            .with_precision_and_scale(10, 3)?;
1171
1172        generic_decimal_to_other_test_cast!(
1173            decimal_array,
1174            Decimal128(10, 3),
1175            Decimal128Array,
1176            Decimal128(10, 2),
1177            [Some(123), Some(222), Some(0), Some(400), Some(500), None],
1178            None
1179        );
1180
1181        Ok(())
1182    }
1183
1184    #[test]
1185    fn test_cast_decimal_to_decimal_overflow() -> Result<()> {
1186        let array = vec![Some(123456789)];
1187
1188        let decimal_array = array
1189            .clone()
1190            .into_iter()
1191            .collect::<Decimal128Array>()
1192            .with_precision_and_scale(10, 3)?;
1193
1194        let schema = Schema::new(vec![Field::new("a", Decimal128(10, 3), false)]);
1195        let batch = RecordBatch::try_new(
1196            Arc::new(schema.clone()),
1197            vec![Arc::new(decimal_array)],
1198        )?;
1199        let expression =
1200            cast_with_options(col("a", &schema)?, &schema, Decimal128(6, 2), None)?;
1201        let e = expression.evaluate(&batch).unwrap_err().strip_backtrace(); // panics on OK
1202        assert_snapshot!(e, @r"
1203        Failed to cast field 'a' from Decimal128(10, 3) to Decimal128(6, 2)
1204        caused by
1205        Arrow error: Invalid argument error: 123456.79 is too large to store in a Decimal128 of precision 6. Max is 9999.99
1206        ");
1207        // safe cast should return null
1208        let expression_safe = cast_with_options(
1209            col("a", &schema)?,
1210            &schema,
1211            Decimal128(6, 2),
1212            Some(DEFAULT_SAFE_CAST_OPTIONS),
1213        )?;
1214        let result_safe = expression_safe
1215            .evaluate(&batch)?
1216            .into_array(batch.num_rows())
1217            .expect("failed to convert to array");
1218
1219        assert!(result_safe.is_null(0));
1220
1221        Ok(())
1222    }
1223
1224    #[test]
1225    fn test_cast_decimal_to_numeric() -> Result<()> {
1226        let array = vec![Some(1), Some(2), Some(3), Some(4), Some(5), None];
1227        // decimal to i8
1228        let decimal_array = array
1229            .clone()
1230            .into_iter()
1231            .collect::<Decimal128Array>()
1232            .with_precision_and_scale(10, 0)?;
1233        generic_decimal_to_other_test_cast!(
1234            decimal_array,
1235            Decimal128(10, 0),
1236            Int8Array,
1237            Int8,
1238            [
1239                Some(1_i8),
1240                Some(2_i8),
1241                Some(3_i8),
1242                Some(4_i8),
1243                Some(5_i8),
1244                None
1245            ],
1246            None
1247        );
1248
1249        // decimal to i16
1250        let decimal_array = array
1251            .clone()
1252            .into_iter()
1253            .collect::<Decimal128Array>()
1254            .with_precision_and_scale(10, 0)?;
1255        generic_decimal_to_other_test_cast!(
1256            decimal_array,
1257            Decimal128(10, 0),
1258            Int16Array,
1259            Int16,
1260            [
1261                Some(1_i16),
1262                Some(2_i16),
1263                Some(3_i16),
1264                Some(4_i16),
1265                Some(5_i16),
1266                None
1267            ],
1268            None
1269        );
1270
1271        // decimal to i32
1272        let decimal_array = array
1273            .clone()
1274            .into_iter()
1275            .collect::<Decimal128Array>()
1276            .with_precision_and_scale(10, 0)?;
1277        generic_decimal_to_other_test_cast!(
1278            decimal_array,
1279            Decimal128(10, 0),
1280            Int32Array,
1281            Int32,
1282            [
1283                Some(1_i32),
1284                Some(2_i32),
1285                Some(3_i32),
1286                Some(4_i32),
1287                Some(5_i32),
1288                None
1289            ],
1290            None
1291        );
1292
1293        // decimal to i64
1294        let decimal_array = array
1295            .into_iter()
1296            .collect::<Decimal128Array>()
1297            .with_precision_and_scale(10, 0)?;
1298        generic_decimal_to_other_test_cast!(
1299            decimal_array,
1300            Decimal128(10, 0),
1301            Int64Array,
1302            Int64,
1303            [
1304                Some(1_i64),
1305                Some(2_i64),
1306                Some(3_i64),
1307                Some(4_i64),
1308                Some(5_i64),
1309                None
1310            ],
1311            None
1312        );
1313
1314        // decimal to float32
1315        let array = vec![
1316            Some(1234),
1317            Some(2222),
1318            Some(3),
1319            Some(4000),
1320            Some(5000),
1321            None,
1322        ];
1323        let decimal_array = array
1324            .clone()
1325            .into_iter()
1326            .collect::<Decimal128Array>()
1327            .with_precision_and_scale(10, 3)?;
1328        generic_decimal_to_other_test_cast!(
1329            decimal_array,
1330            Decimal128(10, 3),
1331            Float32Array,
1332            Float32,
1333            [
1334                Some(1.234_f32),
1335                Some(2.222_f32),
1336                Some(0.003_f32),
1337                Some(4.0_f32),
1338                Some(5.0_f32),
1339                None
1340            ],
1341            None
1342        );
1343
1344        // decimal to float64
1345        let decimal_array = array
1346            .into_iter()
1347            .collect::<Decimal128Array>()
1348            .with_precision_and_scale(20, 6)?;
1349        generic_decimal_to_other_test_cast!(
1350            decimal_array,
1351            Decimal128(20, 6),
1352            Float64Array,
1353            Float64,
1354            [
1355                Some(0.001234_f64),
1356                Some(0.002222_f64),
1357                Some(0.000003_f64),
1358                Some(0.004_f64),
1359                Some(0.005_f64),
1360                None
1361            ],
1362            None
1363        );
1364        Ok(())
1365    }
1366
1367    #[test]
1368    fn test_cast_numeric_to_decimal() -> Result<()> {
1369        // int8
1370        generic_test_cast!(
1371            Int8Array,
1372            Int8,
1373            vec![1, 2, 3, 4, 5],
1374            Decimal128Array,
1375            Decimal128(3, 0),
1376            [Some(1), Some(2), Some(3), Some(4), Some(5)],
1377            None
1378        );
1379
1380        // int16
1381        generic_test_cast!(
1382            Int16Array,
1383            Int16,
1384            vec![1, 2, 3, 4, 5],
1385            Decimal128Array,
1386            Decimal128(5, 0),
1387            [Some(1), Some(2), Some(3), Some(4), Some(5)],
1388            None
1389        );
1390
1391        // int32
1392        generic_test_cast!(
1393            Int32Array,
1394            Int32,
1395            vec![1, 2, 3, 4, 5],
1396            Decimal128Array,
1397            Decimal128(10, 0),
1398            [Some(1), Some(2), Some(3), Some(4), Some(5)],
1399            None
1400        );
1401
1402        // int64
1403        generic_test_cast!(
1404            Int64Array,
1405            Int64,
1406            vec![1, 2, 3, 4, 5],
1407            Decimal128Array,
1408            Decimal128(20, 0),
1409            [Some(1), Some(2), Some(3), Some(4), Some(5)],
1410            None
1411        );
1412
1413        // int64 to different scale
1414        generic_test_cast!(
1415            Int64Array,
1416            Int64,
1417            vec![1, 2, 3, 4, 5],
1418            Decimal128Array,
1419            Decimal128(20, 2),
1420            [Some(100), Some(200), Some(300), Some(400), Some(500)],
1421            None
1422        );
1423
1424        // float32
1425        generic_test_cast!(
1426            Float32Array,
1427            Float32,
1428            vec![1.5, 2.5, 3.0, 1.123_456_8, 5.50],
1429            Decimal128Array,
1430            Decimal128(10, 2),
1431            [Some(150), Some(250), Some(300), Some(112), Some(550)],
1432            None
1433        );
1434
1435        // float64
1436        generic_test_cast!(
1437            Float64Array,
1438            Float64,
1439            vec![1.5, 2.5, 3.0, 1.123_456_8, 5.50],
1440            Decimal128Array,
1441            Decimal128(20, 4),
1442            [
1443                Some(15000),
1444                Some(25000),
1445                Some(30000),
1446                Some(11235),
1447                Some(55000)
1448            ],
1449            None
1450        );
1451        Ok(())
1452    }
1453
1454    #[test]
1455    fn test_cast_i32_u32() -> Result<()> {
1456        generic_test_cast!(
1457            Int32Array,
1458            Int32,
1459            vec![1, 2, 3, 4, 5],
1460            UInt32Array,
1461            UInt32,
1462            [
1463                Some(1_u32),
1464                Some(2_u32),
1465                Some(3_u32),
1466                Some(4_u32),
1467                Some(5_u32)
1468            ],
1469            None
1470        );
1471        Ok(())
1472    }
1473
1474    #[test]
1475    fn test_cast_i32_utf8() -> Result<()> {
1476        generic_test_cast!(
1477            Int32Array,
1478            Int32,
1479            vec![1, 2, 3, 4, 5],
1480            StringArray,
1481            Utf8,
1482            [Some("1"), Some("2"), Some("3"), Some("4"), Some("5")],
1483            None
1484        );
1485        Ok(())
1486    }
1487
1488    #[test]
1489    fn test_cast_i64_t64() -> Result<()> {
1490        let original = vec![1, 2, 3, 4, 5];
1491        let expected: Vec<Option<i64>> = original
1492            .iter()
1493            .map(|i| Some(Time64NanosecondArray::from(vec![*i]).value(0)))
1494            .collect();
1495        generic_test_cast!(
1496            Int64Array,
1497            Int64,
1498            original,
1499            TimestampNanosecondArray,
1500            Timestamp(TimeUnit::Nanosecond, None),
1501            expected,
1502            None
1503        );
1504        Ok(())
1505    }
1506
1507    // Tests for timestamp timezone casting have been moved to timestamps.slt
1508    // See the "Casting between timestamp with and without timezone" section
1509
1510    #[test]
1511    fn invalid_cast() {
1512        // Ensure a useful error happens at plan time if invalid casts are used
1513        let schema = Schema::new(vec![Field::new("a", Int32, false)]);
1514
1515        let result = cast(
1516            col("a", &schema).unwrap(),
1517            &schema,
1518            Interval(IntervalUnit::MonthDayNano),
1519        );
1520        result.expect_err("expected Invalid CAST");
1521    }
1522
1523    #[test]
1524    fn invalid_cast_with_options_error() -> Result<()> {
1525        // Ensure a useful error happens at runtime if invalid casts are used
1526        let schema = Schema::new(vec![Field::new("a", Utf8, false)]);
1527        let a = StringArray::from(vec!["9.1"]);
1528        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1529        let expression = cast_with_options(col("a", &schema)?, &schema, Int32, None)?;
1530        let result = expression.evaluate(&batch);
1531
1532        let error = result.expect_err("expected error").strip_backtrace();
1533        assert_eq!(
1534            error,
1535            "Failed to cast field 'a' from Utf8 to Int32\n\
1536             caused by\n\
1537             Arrow error: Cast error: Cannot cast string '9.1' to value of Int32 type"
1538        );
1539        Ok(())
1540    }
1541
1542    #[test]
1543    fn invalid_cast_with_empty_field_name_uses_expression() {
1544        let schema = Schema::new(vec![Field::new("", Utf8, false)]);
1545        let batch = RecordBatch::try_new(
1546            Arc::new(schema.clone()),
1547            vec![Arc::new(StringArray::from(vec!["9.1"]))],
1548        )
1549        .expect("valid record batch");
1550        let expression = cast_with_options(
1551            col("", &schema).expect("valid column"),
1552            &schema,
1553            Int32,
1554            None,
1555        )
1556        .expect("valid cast expression");
1557
1558        let error = expression
1559            .evaluate(&batch)
1560            .expect_err("expected error")
1561            .strip_backtrace();
1562        assert_eq!(
1563            error,
1564            "Failed to cast expression '@0' from Utf8 to Int32\n\
1565             caused by\n\
1566             Arrow error: Cast error: Cannot cast string '9.1' to value of Int32 type"
1567        );
1568    }
1569
1570    #[test]
1571    fn field_aware_cast_preserves_target_field_semantics() -> Result<()> {
1572        // Target field metadata should be preserved exactly (no merging with source).
1573        let metadata = HashMap::from([("target_meta".to_string(), "1".to_string())]);
1574
1575        for (child_nullable, target_nullable) in [(true, false), (false, true)] {
1576            let schema = Schema::new(vec![Field::new("a", Int32, child_nullable)]);
1577            let target_field = Arc::new(
1578                Field::new("cast_target", Int64, target_nullable)
1579                    .with_metadata(metadata.clone()),
1580            );
1581            let expr = CastExpr::new_with_target_field(
1582                col("a", &schema)?,
1583                Arc::clone(&target_field),
1584                None,
1585            );
1586
1587            let field = expr.return_field(&schema)?;
1588            // Field name comes from source
1589            assert_eq!(field.name(), "a");
1590            assert_eq!(field.data_type(), &Int64);
1591            // Nullability comes from target
1592            assert_eq!(field.is_nullable(), target_nullable);
1593            // Target metadata should be preserved exactly
1594            assert_eq!(
1595                field.metadata().get("target_meta"),
1596                Some(&"1".to_string()),
1597                "Target metadata should be preserved exactly"
1598            );
1599            assert_eq!(expr.nullable(&schema)?, child_nullable || target_nullable);
1600        }
1601
1602        Ok(())
1603    }
1604
1605    #[test]
1606    fn target_field_accessor_returns_the_constructed_field() -> Result<()> {
1607        let schema = Schema::new(vec![Field::new("a", Int32, true)]);
1608        let metadata = HashMap::from([("target_meta".to_string(), "1".to_string())]);
1609        let target_field =
1610            Arc::new(Field::new("cast_target", Int64, false).with_metadata(metadata));
1611
1612        let expr = CastExpr::new_with_target_field(
1613            col("a", &schema)?,
1614            Arc::clone(&target_field),
1615            None,
1616        );
1617
1618        // The field is returned verbatim, including its name.
1619        assert_eq!(expr.target_field(), &target_field);
1620        assert_eq!(expr.cast_type(), &Int64);
1621        assert_eq!(expr.target_metadata(), Some(target_field.metadata()));
1622        assert_eq!(expr.target_nullable(), Some(false));
1623        assert!(expr.has_explicit_metadata());
1624        assert!(expr.has_explicit_nullability());
1625
1626        // A type-only cast reports no explicit target.
1627        let type_only = CastExpr::new(col("a", &schema)?, Int64, None);
1628        assert_eq!(type_only.cast_type(), &Int64);
1629        assert_eq!(type_only.target_metadata(), None);
1630        assert_eq!(type_only.target_nullable(), None);
1631        assert!(!type_only.has_explicit_metadata());
1632        assert!(!type_only.has_explicit_nullability());
1633
1634        Ok(())
1635    }
1636
1637    #[test]
1638    fn type_only_cast_preserves_legacy_field_name_and_nullability() -> Result<()> {
1639        let schema = Schema::new(vec![Field::new("a", Int32, false)]);
1640        let expr = CastExpr::new(col("a", &schema)?, Int64, None);
1641
1642        let field = expr.return_field(&schema)?;
1643
1644        assert_eq!(field.name(), "a");
1645        assert_eq!(field.data_type(), &Int64);
1646        assert!(!field.is_nullable());
1647        assert!(!expr.nullable(&schema)?);
1648
1649        Ok(())
1650    }
1651
1652    #[test]
1653    fn struct_cast_validation_uses_nested_target_fields() -> Result<()> {
1654        let source_type = Struct(Fields::from(vec![
1655            Arc::new(Field::new("x", Int32, true)),
1656            Arc::new(Field::new("y", Utf8, true)),
1657        ]));
1658        let schema = Schema::new(vec![Field::new("a", source_type.clone(), true)]);
1659
1660        let valid_target = Struct(Fields::from(vec![
1661            Arc::new(Field::new("y", Utf8, true)),
1662            Arc::new(Field::new("x", Int64, true)),
1663        ]));
1664        cast_with_options(col("a", &schema)?, &schema, valid_target, None)?;
1665
1666        let invalid_target = Struct(Fields::from(vec![
1667            Arc::new(Field::new("y", Utf8, true)),
1668            Arc::new(Field::new("missing", Int64, false)),
1669        ]));
1670        let err = cast_with_options(col("a", &schema)?, &schema, invalid_target, None)
1671            .expect_err("missing required struct field should fail");
1672
1673        assert!(err.to_string().contains("Unsupported CAST"));
1674
1675        Ok(())
1676    }
1677
1678    #[test]
1679    fn field_aware_cast_struct_array_missing_child() -> Result<()> {
1680        let source_a = Field::new("a", Int32, true);
1681        let source_b = Field::new("b", Utf8, true);
1682        let target_field = Field::new(
1683            "s",
1684            Struct(
1685                vec![
1686                    Arc::new(Field::new("a", Int64, true)),
1687                    Arc::new(Field::new("c", Utf8, true)),
1688                ]
1689                .into(),
1690            ),
1691            true,
1692        );
1693
1694        let struct_array = cast_struct_array(
1695            "s",
1696            Field::new(
1697                "s",
1698                Struct(
1699                    vec![Arc::new(source_a.clone()), Arc::new(source_b.clone())].into(),
1700                ),
1701                true,
1702            ),
1703            target_field,
1704            make_struct_array(
1705                vec![Arc::new(source_a), Arc::new(source_b)].into(),
1706                vec![
1707                    Arc::new(Int32Array::from(vec![Some(1), None])) as ArrayRef,
1708                    Arc::new(StringArray::from(vec![Some("alpha"), Some("beta")]))
1709                        as ArrayRef,
1710                ],
1711            ),
1712        )?;
1713        let cast_a = as_int64_array(struct_array.column_by_name("a").unwrap().as_ref())?;
1714        assert_eq!(cast_a.value(0), 1);
1715        assert!(cast_a.is_null(1));
1716
1717        let cast_c = as_string_array(struct_array.column_by_name("c").unwrap().as_ref())?;
1718        assert!(cast_c.is_null(0));
1719        assert!(cast_c.is_null(1));
1720        Ok(())
1721    }
1722
1723    #[test]
1724    fn field_aware_cast_nested_struct_array() -> Result<()> {
1725        let inner_source = Field::new(
1726            "inner",
1727            Struct(vec![Arc::new(Field::new("x", Int32, true))].into()),
1728            true,
1729        );
1730        let inner_target = Field::new(
1731            "inner",
1732            Struct(
1733                vec![
1734                    Arc::new(Field::new("x", Int64, true)),
1735                    Arc::new(Field::new("y", Boolean, true)),
1736                ]
1737                .into(),
1738            ),
1739            true,
1740        );
1741        let target_field =
1742            Field::new("root", Struct(vec![Arc::new(inner_target)].into()), true);
1743
1744        let inner_struct = make_struct_array(
1745            vec![Arc::new(Field::new("x", Int32, true))].into(),
1746            vec![Arc::new(Int32Array::from(vec![Some(7), None])) as ArrayRef],
1747        );
1748        let outer_struct = make_struct_array(
1749            vec![Arc::new(inner_source.clone())].into(),
1750            vec![Arc::new(inner_struct) as ArrayRef],
1751        );
1752        let struct_array = cast_struct_array(
1753            "root",
1754            Field::new("root", Struct(vec![Arc::new(inner_source)].into()), true),
1755            target_field,
1756            outer_struct,
1757        )?;
1758        let inner =
1759            as_struct_array(struct_array.column_by_name("inner").unwrap().as_ref())?;
1760        let x = as_int64_array(inner.column_by_name("x").unwrap().as_ref())?;
1761        assert_eq!(x.value(0), 7);
1762        assert!(x.is_null(1));
1763        let y = as_boolean_array(inner.column_by_name("y").unwrap().as_ref())?;
1764        assert!(y.is_null(0));
1765        assert!(y.is_null(1));
1766        Ok(())
1767    }
1768
1769    #[test]
1770    fn field_aware_cast_struct_scalar() -> Result<()> {
1771        let source_field = Field::new("a", Int32, true);
1772        let target_field = Field::new(
1773            "s",
1774            Struct(vec![Arc::new(Field::new("a", UInt8, true))].into()),
1775            true,
1776        );
1777
1778        let schema = Arc::new(Schema::new(vec![Field::new(
1779            "s",
1780            Struct(vec![Arc::new(source_field.clone())].into()),
1781            true,
1782        )]));
1783        let scalar_struct = make_struct_array(
1784            vec![Arc::new(source_field)].into(),
1785            vec![Arc::new(Int32Array::from(vec![Some(9)])) as ArrayRef],
1786        );
1787        let literal = Arc::new(crate::expressions::Literal::new(ScalarValue::Struct(
1788            Arc::new(scalar_struct),
1789        )));
1790        let target_field = Arc::new(target_field);
1791        let expr = CastExpr::new_with_target_field(literal, target_field, None);
1792
1793        let batch = RecordBatch::new_empty(schema);
1794        let result = expr.evaluate(&batch)?;
1795        let ColumnarValue::Scalar(ScalarValue::Struct(array)) = result else {
1796            panic!("expected struct scalar");
1797        };
1798        let casted = as_uint8_array(array.column_by_name("a").unwrap().as_ref())?;
1799        assert_eq!(casted.value(0), 9);
1800        Ok(())
1801    }
1802
1803    #[test]
1804    #[ignore = "TODO: https://github.com/apache/datafusion/issues/5396"]
1805    fn test_cast_decimal() -> Result<()> {
1806        let schema = Schema::new(vec![Field::new("a", Int64, false)]);
1807        let a = Int64Array::from(vec![100]);
1808        let batch = RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
1809        let expression =
1810            cast_with_options(col("a", &schema)?, &schema, Decimal128(38, 38), None)?;
1811        expression.evaluate(&batch)?;
1812        Ok(())
1813    }
1814
1815    #[test]
1816    fn test_fmt_sql() -> Result<()> {
1817        let schema = Schema::new(vec![Field::new("a", Int32, true)]);
1818
1819        // Test numeric casting
1820        let expr = cast(col("a", &schema)?, &schema, Int64)?;
1821        let display_string = expr.to_string();
1822        assert_eq!(display_string, "CAST(a@0 AS Int64)");
1823        let sql_string = fmt_sql(expr.as_ref()).to_string();
1824        assert_eq!(sql_string, "CAST(a AS Int64)");
1825
1826        // Test string casting
1827        let schema = Schema::new(vec![Field::new("b", Utf8, true)]);
1828        let expr = cast(col("b", &schema)?, &schema, Int32)?;
1829        let display_string = expr.to_string();
1830        assert_eq!(display_string, "CAST(b@0 AS Int32)");
1831        let sql_string = fmt_sql(expr.as_ref()).to_string();
1832        assert_eq!(sql_string, "CAST(b AS Int32)");
1833
1834        Ok(())
1835    }
1836
1837    #[test]
1838    fn test_display_explicit_target_nullability() -> Result<()> {
1839        let schema = Schema::new(vec![Field::new("a", Int32, false)]);
1840
1841        // A same-type cast to a nullable field only relabels the nullability
1842        let expr = CastExpr::new_with_target_field(
1843            col("a", &schema)?,
1844            Arc::new(Field::new("a", Int32, true)),
1845            None,
1846        );
1847        assert_eq!(expr.to_string(), "CAST(a@0 AS Int32;N)");
1848        assert_eq!(fmt_sql(&expr).to_string(), "CAST(a AS Int32)");
1849
1850        let expr = CastExpr::new_with_target_field(
1851            col("a", &schema)?,
1852            Arc::new(Field::new("a", Int32, false)),
1853            None,
1854        );
1855        assert_eq!(expr.to_string(), "CAST(a@0 AS Int32)");
1856
1857        // A cast to a bare type is unchanged
1858        let expr = CastExpr::new(col("a", &schema)?, Int64, None);
1859        assert_eq!(expr.to_string(), "CAST(a@0 AS Int64)");
1860
1861        Ok(())
1862    }
1863
1864    #[test]
1865    fn type_only_cast_strips_extension_metadata() -> Result<()> {
1866        // When using type-only cast (new()), extension metadata from source should NOT propagate
1867        let source_meta = HashMap::from([
1868            (
1869                EXTENSION_TYPE_NAME_KEY.to_string(),
1870                "arrow.uuid".to_string(),
1871            ),
1872            ("custom_key".to_string(), "custom_value".to_string()),
1873        ]);
1874        let schema = Schema::new(vec![
1875            Field::new("a", FixedSizeBinary(16), false).with_metadata(source_meta),
1876        ]);
1877
1878        let expr = CastExpr::new(col("a", &schema)?, Utf8, None);
1879
1880        let field = expr.return_field(&schema)?;
1881        assert!(
1882            field.metadata().get(EXTENSION_TYPE_NAME_KEY).is_none(),
1883            "Type-only cast should strip extension type name from source"
1884        );
1885        assert_eq!(
1886            field.metadata().get("custom_key"),
1887            Some(&"custom_value".to_string()),
1888            "Type-only cast should preserve non-extension metadata"
1889        );
1890
1891        Ok(())
1892    }
1893
1894    #[test]
1895    fn field_aware_cast_uses_exact_target_metadata() -> Result<()> {
1896        // When using field-aware cast, target's metadata should be used exactly
1897        let source_meta = HashMap::from([
1898            (
1899                EXTENSION_TYPE_NAME_KEY.to_string(),
1900                "source.type".to_string(),
1901            ),
1902            ("source_key".to_string(), "source_value".to_string()),
1903        ]);
1904        let target_meta = HashMap::from([
1905            (
1906                EXTENSION_TYPE_NAME_KEY.to_string(),
1907                "target.type".to_string(),
1908            ),
1909            (
1910                EXTENSION_TYPE_METADATA_KEY.to_string(),
1911                "target_ext_meta".to_string(),
1912            ),
1913            ("target_key".to_string(), "target_value".to_string()),
1914        ]);
1915        let schema = Schema::new(vec![
1916            Field::new("a", FixedSizeBinary(16), false).with_metadata(source_meta),
1917        ]);
1918
1919        let target_field =
1920            Arc::new(Field::new("b", Utf8, true).with_metadata(target_meta));
1921        let expr = CastExpr::new_with_target_field(
1922            col("a", &schema)?,
1923            Arc::clone(&target_field),
1924            None,
1925        );
1926
1927        let field = expr.return_field(&schema)?;
1928        assert_eq!(
1929            field.metadata().get(EXTENSION_TYPE_NAME_KEY),
1930            Some(&"target.type".to_string()),
1931            "Field-aware cast should use target's extension type name"
1932        );
1933        assert_eq!(
1934            field.metadata().get(EXTENSION_TYPE_METADATA_KEY),
1935            Some(&"target_ext_meta".to_string()),
1936            "Field-aware cast should use target's extension type metadata"
1937        );
1938        assert!(
1939            field.metadata().get("source_key").is_none(),
1940            "Field-aware cast should NOT preserve source metadata"
1941        );
1942        assert_eq!(
1943            field.metadata().get("target_key"),
1944            Some(&"target_value".to_string()),
1945            "Field-aware cast should preserve target's non-extension metadata"
1946        );
1947
1948        Ok(())
1949    }
1950
1951    #[test]
1952    fn test_integer_date_cast_preserves_values_and_ordering() {
1953        use arrow::array::{Date32Array, Date64Array};
1954        use arrow::compute::SortOptions;
1955        use datafusion_expr_common::sort_properties::SortProperties;
1956
1957        let values = vec![None, Some(i32::MIN), Some(-1), Some(0), Some(i32::MAX)];
1958        let integers: ArrayRef = Arc::new(Int32Array::from(values.clone()));
1959        let dates: ArrayRef = Arc::new(Date32Array::from(values));
1960        let values = vec![None, Some(i64::MIN), Some(-1), Some(0), Some(i64::MAX)];
1961        let integers64: ArrayRef = Arc::new(Int64Array::from(values.clone()));
1962        let dates64: ArrayRef = Arc::new(Date64Array::from(values));
1963        for (input, expected) in [
1964            (Arc::clone(&integers), Arc::clone(&dates)),
1965            (dates, integers),
1966            (Arc::clone(&integers64), Arc::clone(&dates64)),
1967            (dates64, integers64),
1968        ] {
1969            let schema = Arc::new(Schema::new(vec![Field::new(
1970                "a",
1971                input.data_type().clone(),
1972                true,
1973            )]));
1974            let expr = CastExpr::new(
1975                col("a", &schema).expect("column exists"),
1976                expected.data_type().clone(),
1977                None,
1978            );
1979            assert!(expr.is_bigger_cast(input.data_type()));
1980            let child = ExprProperties::new_unknown()
1981                .with_range(
1982                    Interval::make_unbounded(input.data_type())
1983                        .expect("supported interval type"),
1984                )
1985                .with_order(SortProperties::Ordered(SortOptions::default()))
1986                .with_strictly_order_preserving(true);
1987            let properties = expr
1988                .get_properties(std::slice::from_ref(&child))
1989                .expect("cast properties");
1990            assert_eq!(properties.sort_properties, child.sort_properties);
1991            assert!(properties.strictly_order_preserving);
1992            assert_eq!(properties.range.data_type(), *expected.data_type());
1993
1994            let batch =
1995                RecordBatch::try_new(schema, vec![input]).expect("valid input batch");
1996            let actual = expr
1997                .evaluate(&batch)
1998                .expect("cast succeeds")
1999                .into_array(batch.num_rows())
2000                .expect("array result");
2001            assert_eq!(actual.as_ref(), expected.as_ref());
2002        }
2003    }
2004
2005    #[test]
2006    fn test_byte_representation_cast_preserves_values_and_ordering() -> Result<()> {
2007        use arrow::array::{
2008            BinaryArray, BinaryViewArray, LargeBinaryArray, StringViewArray,
2009        };
2010        use arrow::compute::SortOptions;
2011        use datafusion_expr_common::sort_properties::SortProperties;
2012
2013        // Cover nulls, empty values, inline/long views, Unicode, and non-UTF8 bytes.
2014        let strings = vec![
2015            None,
2016            Some(""),
2017            Some("a"),
2018            Some("a longer shared string"),
2019            Some("a longer shared string"),
2020            Some("🦀"),
2021        ];
2022        let bytes: Vec<Option<&[u8]>> = vec![
2023            None,
2024            Some(b""),
2025            Some(b"\0"),
2026            Some(b"a longer shared byte string"),
2027            Some(b"a longer shared byte string"),
2028            Some(b"\xff"),
2029        ];
2030        let binary: ArrayRef = Arc::new(BinaryArray::from(bytes.clone()));
2031        let cases: [(ArrayRef, ArrayRef); 3] = [
2032            (
2033                Arc::new(StringArray::from(strings.clone())),
2034                Arc::new(StringViewArray::from(strings)),
2035            ),
2036            (
2037                Arc::clone(&binary),
2038                Arc::new(LargeBinaryArray::from(bytes.clone())),
2039            ),
2040            (binary, Arc::new(BinaryViewArray::from(bytes))),
2041        ];
2042        for (input, expected) in cases {
2043            let schema = Arc::new(Schema::new(vec![Field::new(
2044                "a",
2045                input.data_type().clone(),
2046                true,
2047            )]));
2048            let expr =
2049                CastExpr::new(col("a", &schema)?, expected.data_type().clone(), None);
2050            assert!(expr.is_bigger_cast(input.data_type()));
2051            for descending in [false, true] {
2052                for nulls_first in [false, true] {
2053                    let child = ExprProperties::new_unknown()
2054                        .with_range(Interval::make_unbounded(input.data_type())?)
2055                        .with_order(SortProperties::Ordered(SortOptions {
2056                            descending,
2057                            nulls_first,
2058                        }))
2059                        .with_strictly_order_preserving(true);
2060                    let properties = expr.get_properties(std::slice::from_ref(&child))?;
2061                    assert_eq!(properties.sort_properties, child.sort_properties);
2062                    assert!(properties.strictly_order_preserving);
2063                    assert_eq!(properties.range.data_type(), *expected.data_type());
2064                }
2065            }
2066            let batch = RecordBatch::try_new(schema, vec![input])?;
2067            let actual = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
2068            assert_eq!(actual.as_ref(), expected.as_ref());
2069        }
2070        for (source, target) in [
2071            (Utf8View, Utf8),
2072            (LargeBinary, Binary),
2073            (BinaryView, Binary),
2074        ] {
2075            assert!(!CastExpr::check_bigger_cast(&target, &source));
2076        }
2077        Ok(())
2078    }
2079
2080    #[test]
2081    fn test_unsigned_to_signed_cast_preserves_values_and_ordering() {
2082        use arrow::array::{UInt8Array, UInt16Array, UInt32Array};
2083        use arrow::compute::SortOptions;
2084        use datafusion_expr_common::sort_properties::SortProperties;
2085
2086        let inputs: [(ArrayRef, Vec<DataType>, i64); 3] = [
2087            (
2088                Arc::new(UInt8Array::from(vec![
2089                    None,
2090                    Some(0),
2091                    Some(1),
2092                    Some(u8::MAX),
2093                ])),
2094                vec![Int16, Int32, Int64],
2095                i64::from(u8::MAX),
2096            ),
2097            (
2098                Arc::new(UInt16Array::from(vec![
2099                    None,
2100                    Some(0),
2101                    Some(1),
2102                    Some(u16::MAX),
2103                ])),
2104                vec![Int32, Int64],
2105                i64::from(u16::MAX),
2106            ),
2107            (
2108                Arc::new(UInt32Array::from(vec![
2109                    None,
2110                    Some(0),
2111                    Some(1),
2112                    Some(u32::MAX),
2113                ])),
2114                vec![Int64],
2115                i64::from(u32::MAX),
2116            ),
2117        ];
2118        for (input, target_types, max) in inputs {
2119            let schema = Arc::new(Schema::new(vec![Field::new(
2120                "a",
2121                input.data_type().clone(),
2122                true,
2123            )]));
2124            let batch =
2125                RecordBatch::try_new(Arc::clone(&schema), vec![Arc::clone(&input)])
2126                    .expect("valid input batch");
2127            for target_type in target_types {
2128                let expr =
2129                    CastExpr::new(col("a", &schema).unwrap(), target_type.clone(), None);
2130                let actual = expr
2131                    .evaluate(&batch)
2132                    .unwrap()
2133                    .into_array(batch.num_rows())
2134                    .unwrap();
2135                for (index, value) in
2136                    [None, Some(0), Some(1), Some(max)].into_iter().enumerate()
2137                {
2138                    let expected = match target_type {
2139                        Int16 => {
2140                            ScalarValue::Int16(value.map(|v| i16::try_from(v).unwrap()))
2141                        }
2142                        Int32 => {
2143                            ScalarValue::Int32(value.map(|v| i32::try_from(v).unwrap()))
2144                        }
2145                        Int64 => ScalarValue::Int64(value),
2146                        _ => unreachable!(),
2147                    };
2148                    assert_eq!(
2149                        ScalarValue::try_from_array(&actual, index).unwrap(),
2150                        expected
2151                    );
2152                }
2153                for descending in [false, true] {
2154                    for nulls_first in [false, true] {
2155                        let child = ExprProperties::new_unknown()
2156                            .with_range(
2157                                Interval::make_unbounded(input.data_type()).unwrap(),
2158                            )
2159                            .with_order(SortProperties::Ordered(SortOptions {
2160                                descending,
2161                                nulls_first,
2162                            }))
2163                            .with_strictly_order_preserving(true);
2164                        let properties =
2165                            expr.get_properties(std::slice::from_ref(&child)).unwrap();
2166                        assert_eq!(properties.sort_properties, child.sort_properties);
2167                        assert!(properties.strictly_order_preserving);
2168                        assert_eq!(properties.range.data_type(), target_type);
2169                    }
2170                }
2171            }
2172        }
2173    }
2174
2175    #[test]
2176    fn test_temporal_cast_ordering() {
2177        use TimeUnit::*;
2178        use arrow::compute::SortOptions;
2179        use datafusion_expr_common::sort_properties::SortProperties;
2180
2181        let timezone = Some("America/Goose_Bay".into());
2182        // Expected ordering is independent of strictness: discarding precision
2183        // may merge values, but must not reverse them.
2184        let cases = [
2185            (Date32, Date64, true),
2186            (Date64, Date32, true),
2187            (Date32, Timestamp(Nanosecond, None), true),
2188            (Date64, Timestamp(Second, None), true),
2189            (Timestamp(Second, None), Date32, true),
2190            (Timestamp(Second, Some("UTC".into())), Date32, true),
2191            (Timestamp(Second, Some("+08:00".into())), Date32, true),
2192            (Timestamp(Second, timezone.clone()), Date32, false),
2193            (Timestamp(Second, timezone.clone()), Date64, true),
2194            (Timestamp(Second, None), Timestamp(Nanosecond, None), true),
2195            (Timestamp(Nanosecond, None), Timestamp(Second, None), true),
2196            (
2197                Timestamp(Second, None),
2198                Timestamp(Second, timezone.clone()),
2199                false,
2200            ),
2201            (
2202                Timestamp(Second, None),
2203                Timestamp(Second, Some("+08:00".into())),
2204                true,
2205            ),
2206            (
2207                Timestamp(Second, timezone.clone()),
2208                Timestamp(Second, None),
2209                true,
2210            ),
2211            (
2212                Timestamp(Second, timezone.clone()),
2213                Timestamp(Millisecond, Some("UTC".into())),
2214                true,
2215            ),
2216            (Timestamp(Second, None), Time32(Second), false),
2217            (Timestamp(Nanosecond, timezone), Time64(Nanosecond), false),
2218            (Time32(Second), Time32(Millisecond), true),
2219            (Time32(Millisecond), Time32(Second), true),
2220            (Time32(Second), Time64(Nanosecond), true),
2221            (Time64(Nanosecond), Time64(Microsecond), true),
2222            (Time64(Microsecond), Time64(Nanosecond), false),
2223            (Time64(Nanosecond), Time32(Second), false),
2224            (Duration(Second), Duration(Nanosecond), true),
2225            (Duration(Nanosecond), Duration(Second), true),
2226            (Null, Timestamp(Second, None), false),
2227        ];
2228        for (source, target, preserves_order) in cases {
2229            let schema = Schema::new(vec![Field::new("a", source.clone(), true)]);
2230            let expr = CastExpr::new(
2231                col("a", &schema).expect("column exists"),
2232                target.clone(),
2233                None,
2234            );
2235            for descending in [false, true] {
2236                for nulls_first in [false, true] {
2237                    let ordered = SortProperties::Ordered(SortOptions {
2238                        descending,
2239                        nulls_first,
2240                    });
2241                    let child = ExprProperties::new_unknown()
2242                        .with_range(
2243                            Interval::make_unbounded(&source)
2244                                .expect("supported interval type"),
2245                        )
2246                        .with_order(ordered)
2247                        .with_strictly_order_preserving(true);
2248                    let properties =
2249                        expr.get_properties(&[child]).expect("cast properties");
2250                    assert_eq!(
2251                        properties.sort_properties,
2252                        if preserves_order {
2253                            ordered
2254                        } else {
2255                            SortProperties::Unordered
2256                        },
2257                        "{source} -> {target}, descending={descending}, nulls_first={nulls_first}"
2258                    );
2259                    assert_eq!(properties.range.data_type(), target);
2260                    assert!(!properties.strictly_order_preserving);
2261                }
2262            }
2263        }
2264    }
2265
2266    #[test]
2267    fn test_cast_ordering_with_null_on_failure() {
2268        use arrow::array::TimestampSecondArray;
2269        use arrow::compute::SortOptions;
2270        use datafusion_expr_common::sort_properties::SortProperties;
2271
2272        // Overflow introduces a trailing NULL even though the input satisfies
2273        // ASC NULLS FIRST. Successful values alone are still in order.
2274        let source = Timestamp(TimeUnit::Second, None);
2275        let target = Timestamp(TimeUnit::Nanosecond, None);
2276        let schema = Arc::new(Schema::new(vec![Field::new("a", source.clone(), true)]));
2277        let batch = RecordBatch::try_new(
2278            Arc::clone(&schema),
2279            vec![Arc::new(TimestampSecondArray::from(vec![
2280                None,
2281                Some(0),
2282                Some(i64::MAX),
2283            ]))],
2284        )
2285        .expect("valid input batch");
2286        let child = ExprProperties::new_unknown()
2287            .with_range(
2288                Interval::make_unbounded(&source).expect("supported interval type"),
2289            )
2290            .with_order(SortProperties::Ordered(SortOptions::default()))
2291            .with_strictly_order_preserving(true);
2292        let expr = CastExpr::new(
2293            col("a", &schema).expect("column exists"),
2294            target.clone(),
2295            Some(DEFAULT_SAFE_CAST_OPTIONS),
2296        );
2297        let actual = expr
2298            .evaluate(&batch)
2299            .expect("safe cast succeeds")
2300            .into_array(batch.num_rows())
2301            .expect("array result");
2302        let expected = TimestampNanosecondArray::from(vec![None, Some(0), None]);
2303        assert_eq!(actual.as_ref(), &expected);
2304        let properties = expr
2305            .get_properties(std::slice::from_ref(&child))
2306            .expect("safe cast properties");
2307        assert_eq!(properties.sort_properties, SortProperties::Unordered);
2308        assert_eq!(properties.range.data_type(), target);
2309        assert!(!properties.strictly_order_preserving);
2310
2311        let expr = CastExpr::new(col("a", &schema).expect("column exists"), target, None);
2312        assert!(expr.evaluate(&batch).is_err());
2313        assert_eq!(
2314            expr.get_properties(&[child])
2315                .expect("cast properties")
2316                .sort_properties,
2317            SortProperties::Ordered(SortOptions::default())
2318        );
2319
2320        // A lossless cast preserves ordering even in NULL-on-failure mode.
2321        let schema = Schema::new(vec![Field::new("a", Int32, true)]);
2322        let child = ExprProperties::new_unknown()
2323            .with_range(
2324                Interval::make_unbounded(&Int32).expect("supported interval type"),
2325            )
2326            .with_order(SortProperties::Ordered(SortOptions::default()))
2327            .with_strictly_order_preserving(true);
2328        let expr = CastExpr::new(
2329            col("a", &schema).expect("column exists"),
2330            Int64,
2331            Some(DEFAULT_SAFE_CAST_OPTIONS),
2332        );
2333        let properties = expr
2334            .get_properties(std::slice::from_ref(&child))
2335            .expect("safe lossless cast properties");
2336        assert_eq!(properties.sort_properties, child.sort_properties);
2337        assert!(properties.strictly_order_preserving);
2338    }
2339
2340    #[test]
2341    fn test_check_bigger_cast_precision_loss() {
2342        use DataType::*;
2343
2344        // Exact conversions without precision loss
2345        assert!(CastExpr::check_bigger_cast(&Int16, &Int8));
2346        assert!(CastExpr::check_bigger_cast(&Int64, &Int32));
2347        assert!(CastExpr::check_bigger_cast(&Float32, &Int16));
2348        assert!(CastExpr::check_bigger_cast(&Float32, &UInt16));
2349        assert!(CastExpr::check_bigger_cast(&Float64, &Int32));
2350        assert!(CastExpr::check_bigger_cast(&Float64, &UInt32));
2351        assert!(CastExpr::check_bigger_cast(&LargeUtf8, &Utf8));
2352
2353        // Precision-losing int-to-float conversions should return false
2354        assert!(!CastExpr::check_bigger_cast(&Float32, &Int32));
2355        assert!(!CastExpr::check_bigger_cast(&Float32, &UInt32));
2356        assert!(!CastExpr::check_bigger_cast(&Float64, &Int64));
2357        assert!(!CastExpr::check_bigger_cast(&Float64, &UInt64));
2358
2359        // Signed-to-unsigned and unsigned-to-signed casts whose target cannot
2360        // represent the entire source range are not lossless for all values.
2361        assert!(!CastExpr::check_bigger_cast(&UInt16, &Int8));
2362        assert!(!CastExpr::check_bigger_cast(&UInt32, &Int16));
2363        assert!(!CastExpr::check_bigger_cast(&Int8, &UInt8));
2364        assert!(!CastExpr::check_bigger_cast(&Int16, &UInt16));
2365        assert!(!CastExpr::check_bigger_cast(&Int32, &UInt32));
2366        assert!(!CastExpr::check_bigger_cast(&Int64, &UInt64));
2367        assert!(!CastExpr::check_bigger_cast(&Int8, &UInt16));
2368    }
2369}
2370
2371/// Tests for the `try_to_proto` / `try_from_proto` hooks.
2372#[cfg(all(test, feature = "proto"))]
2373mod proto_tests {
2374    use super::*;
2375    use crate::expressions::{Column, col};
2376    use crate::proto_test_util::{
2377        StubDecoder, StubEncoder, UnreachableDecoder, column_node,
2378    };
2379    use arrow::datatypes::Field;
2380    use datafusion_common::DataFusionError;
2381    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
2382    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
2383    use datafusion_proto_models::datafusion_common::ArrowType;
2384    use datafusion_proto_models::protobuf::{
2385        PhysicalCastNode, PhysicalExprNode, physical_expr_node,
2386    };
2387
2388    #[derive(Debug)]
2389    struct TestFormatterFactory;
2390
2391    impl ArrayFormatterFactory for TestFormatterFactory {
2392        fn create_array_formatter<'formatter>(
2393            &self,
2394            _array: &'formatter dyn arrow::array::Array,
2395            _options: &FormatOptions<'formatter>,
2396            _field: Option<&'formatter Field>,
2397        ) -> std::result::Result<
2398            Option<arrow::util::display::ArrayFormatter<'formatter>>,
2399            arrow::error::ArrowError,
2400        > {
2401            Ok(None)
2402        }
2403    }
2404
2405    static TEST_FORMATTER_FACTORY: TestFormatterFactory = TestFormatterFactory;
2406
2407    /// A `CastExpr` over an `Int32` column, casting to `Int64`.
2408    fn proto_cast_fixture() -> CastExpr {
2409        let schema = Schema::new(vec![Field::new("a", Int32, false)]);
2410        CastExpr::new(col("a", &schema).unwrap(), Int64, None)
2411    }
2412
2413    fn proto_int64_arrow_type() -> ArrowType {
2414        (&Int64).try_into().unwrap()
2415    }
2416
2417    /// Build a legacy `CastExpr` proto node with the given child and target type.
2418    fn proto_cast_node(
2419        expr: Option<Box<PhysicalExprNode>>,
2420        arrow_type: Option<ArrowType>,
2421    ) -> PhysicalExprNode {
2422        PhysicalExprNode {
2423            expr_id: None,
2424            expr_type: Some(physical_expr_node::ExprType::Cast(Box::new(
2425                PhysicalCastNode {
2426                    expr,
2427                    arrow_type,
2428                    target_field: None,
2429                    cast_options: None,
2430                },
2431            ))),
2432        }
2433    }
2434
2435    fn encode_cast(cast: &CastExpr) -> PhysicalCastNode {
2436        let encoder = StubEncoder::ok();
2437        let node = cast
2438            .try_to_proto(&PhysicalExprEncodeCtx::new(&encoder))
2439            .unwrap()
2440            .expect("CastExpr should encode to Some(node)");
2441        match node.expr_type {
2442            Some(physical_expr_node::ExprType::Cast(cast)) => *cast,
2443            other => panic!("expected a Cast node, got {other:?}"),
2444        }
2445    }
2446
2447    fn round_trip_cast(cast: &CastExpr, schema: &Schema) -> CastExpr {
2448        let encoder = StubEncoder::ok();
2449        let node = cast
2450            .try_to_proto(&PhysicalExprEncodeCtx::new(&encoder))
2451            .unwrap()
2452            .expect("CastExpr should encode to Some(node)");
2453        let decoder = StubDecoder::ok();
2454        CastExpr::try_from_proto(&node, &PhysicalExprDecodeCtx::new(schema, &decoder))
2455            .unwrap()
2456            .downcast_ref::<CastExpr>()
2457            .expect("decoded expr should be a CastExpr")
2458            .clone()
2459    }
2460
2461    fn non_default_cast_options() -> CastOptions<'static> {
2462        CastOptions {
2463            safe: true,
2464            format_options: FormatOptions::new()
2465                .with_display_error(false)
2466                .with_null("NULL")
2467                .with_date_format(Some("%d/%m/%Y"))
2468                .with_datetime_format(Some("%d/%m/%Y %H:%M:%S"))
2469                .with_timestamp_format(Some("%s"))
2470                .with_timestamp_tz_format(Some("%+"))
2471                .with_time_format(Some("%H-%M-%S"))
2472                .with_duration_format(DurationFormat::ISO8601)
2473                .with_types_info(true)
2474                .with_quoted_strings(true),
2475        }
2476    }
2477
2478    #[test]
2479    fn try_to_proto_encodes_cast_expr() {
2480        let cast = proto_cast_fixture();
2481        let encoder = StubEncoder::ok();
2482        let ctx = PhysicalExprEncodeCtx::new(&encoder);
2483
2484        let node = cast
2485            .try_to_proto(&ctx)
2486            .unwrap()
2487            .expect("CastExpr should encode to Some(node)");
2488
2489        assert!(node.expr_id.is_none());
2490        let cast_node = match node.expr_type {
2491            Some(physical_expr_node::ExprType::Cast(cast_node)) => *cast_node,
2492            other => panic!("expected a Cast node, got {other:?}"),
2493        };
2494        assert!(cast_node.expr.is_some());
2495
2496        let arrow_type = cast_node
2497            .arrow_type
2498            .as_ref()
2499            .expect("cast type should be encoded");
2500        let data_type: DataType = arrow_type.try_into().unwrap();
2501        assert_eq!(data_type, Int64);
2502        assert!(cast_node.target_field.is_none());
2503        assert!(cast_node.cast_options.is_none());
2504    }
2505
2506    #[test]
2507    fn cast_target_field_survives_proto_round_trip() {
2508        let schema = Schema::new(vec![Field::new("a", Int32, true)]);
2509        let target = Arc::new(Field::new("target", Int64, false).with_metadata(
2510            Metadata::from([("extension".to_string(), "value".to_string())]),
2511        ));
2512        let cast = CastExpr::new_with_target_field(
2513            col("a", &schema).unwrap(),
2514            Arc::clone(&target),
2515            None,
2516        );
2517
2518        assert!(encode_cast(&cast).target_field.is_some());
2519        let decoded = round_trip_cast(&cast, &schema);
2520
2521        assert_eq!(decoded.target_field(), &target);
2522        assert_eq!(decoded.target_metadata(), Some(target.metadata()));
2523        assert_eq!(decoded.target_nullable(), Some(false));
2524        assert!(!decoded.return_field(&schema).unwrap().is_nullable());
2525    }
2526
2527    #[test]
2528    fn explicit_default_shaped_cast_target_is_encoded() {
2529        let schema = Schema::new(vec![Field::new("a", Int32, false).with_metadata(
2530            Metadata::from([("source".to_string(), "value".to_string())]),
2531        )]);
2532        let cast = CastExpr::new_with_target_field(
2533            col("a", &schema).unwrap(),
2534            Int64.into_nullable_field_ref(),
2535            None,
2536        );
2537
2538        assert!(encode_cast(&cast).target_field.is_some());
2539        let decoded = round_trip_cast(&cast, &schema);
2540        assert_eq!(decoded.target_metadata(), Some(&Metadata::default()));
2541        assert_eq!(decoded.target_nullable(), Some(true));
2542        let output = decoded.return_field(&schema).unwrap();
2543        assert!(output.metadata().is_empty());
2544        assert!(output.is_nullable());
2545    }
2546
2547    #[test]
2548    fn type_only_cast_target_is_omitted_and_remains_type_only() {
2549        let metadata = Metadata::from([("source".to_string(), "value".to_string())]);
2550        let schema = Schema::new(vec![
2551            Field::new("a", Int32, false).with_metadata(metadata.clone()),
2552        ]);
2553        let cast = CastExpr::new(col("a", &schema).unwrap(), Int64, None);
2554
2555        assert!(encode_cast(&cast).target_field.is_none());
2556        let decoded = round_trip_cast(&cast, &schema);
2557
2558        assert_eq!(decoded.target_metadata(), None);
2559        assert_eq!(decoded.target_nullable(), None);
2560        let output = decoded.return_field(&schema).unwrap();
2561        assert_eq!(output.metadata(), &metadata);
2562        assert!(!output.is_nullable());
2563    }
2564
2565    #[test]
2566    fn cast_options_survive_proto_round_trip() {
2567        let schema = Schema::new(vec![Field::new("a", Int32, false)]);
2568        let options = non_default_cast_options();
2569        let cast =
2570            CastExpr::new(col("a", &schema).unwrap(), Int64, Some(options.clone()));
2571
2572        assert!(encode_cast(&cast).cast_options.is_some());
2573        assert_eq!(round_trip_cast(&cast, &schema).cast_options(), options);
2574    }
2575
2576    #[test]
2577    fn custom_formatter_factory_is_rejected() {
2578        let schema = Schema::new(vec![Field::new("a", Int32, false)]);
2579        let cast = CastExpr::new(
2580            col("a", &schema).unwrap(),
2581            Int64,
2582            Some(CastOptions {
2583                safe: false,
2584                format_options: DEFAULT_FORMAT_OPTIONS
2585                    .with_formatter_factory(Some(&TEST_FORMATTER_FACTORY)),
2586            }),
2587        );
2588        let encoder = StubEncoder::ok();
2589
2590        let err = cast
2591            .try_to_proto(&PhysicalExprEncodeCtx::new(&encoder))
2592            .unwrap_err();
2593        assert!(matches!(
2594            err,
2595            DataFusionError::NotImplemented(msg)
2596                if msg.contains("custom formatter_factory")
2597        ));
2598    }
2599
2600    #[test]
2601    fn try_to_proto_propagates_child_encode_error() {
2602        let cast = proto_cast_fixture();
2603        let encoder = StubEncoder::failing_on(1);
2604        let ctx = PhysicalExprEncodeCtx::new(&encoder);
2605
2606        let err = cast.try_to_proto(&ctx).unwrap_err();
2607        assert!(matches!(
2608            err,
2609            DataFusionError::Internal(msg) if msg.contains("call 1")
2610        ));
2611    }
2612
2613    #[test]
2614    fn try_from_proto_decodes_legacy_cast_expr() {
2615        let node = proto_cast_node(
2616            Some(Box::new(column_node("a"))),
2617            Some(proto_int64_arrow_type()),
2618        );
2619        let schema = Schema::empty();
2620        let decoder = StubDecoder::ok();
2621        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
2622
2623        let decoded = CastExpr::try_from_proto(&node, &ctx).unwrap();
2624        let cast = decoded
2625            .downcast_ref::<CastExpr>()
2626            .expect("decoded expr should be a CastExpr");
2627
2628        assert_eq!(cast.cast_type(), &Int64);
2629        assert!(cast.expr().downcast_ref::<Column>().is_some());
2630        assert_eq!(cast.target_metadata(), None);
2631        assert_eq!(cast.target_nullable(), None);
2632        assert_eq!(cast.cast_options(), DEFAULT_CAST_OPTIONS);
2633    }
2634
2635    #[test]
2636    fn try_from_proto_rejects_mismatched_target_field_type() {
2637        let mut node = proto_cast_node(
2638            Some(Box::new(column_node("a"))),
2639            Some(proto_int64_arrow_type()),
2640        );
2641        let Some(physical_expr_node::ExprType::Cast(cast)) = node.expr_type.as_mut()
2642        else {
2643            unreachable!()
2644        };
2645        cast.target_field =
2646            Some((&Field::new("target", Int32, true)).try_into().unwrap());
2647        let schema = Schema::empty();
2648        let decoder = StubDecoder::ok();
2649
2650        let err = CastExpr::try_from_proto(
2651            &node,
2652            &PhysicalExprDecodeCtx::new(&schema, &decoder),
2653        )
2654        .unwrap_err();
2655        assert!(err.to_string().contains("target_field type"));
2656    }
2657
2658    #[test]
2659    fn try_from_proto_rejects_non_cast_node() {
2660        let node = column_node("a");
2661        let schema = Schema::empty();
2662        let decoder = UnreachableDecoder;
2663        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
2664
2665        let err = CastExpr::try_from_proto(&node, &ctx).unwrap_err();
2666        assert!(matches!(
2667            err,
2668            DataFusionError::Internal(msg)
2669                if msg.contains("PhysicalExprNode is not a CastExpr")
2670        ));
2671    }
2672
2673    #[test]
2674    fn try_from_proto_rejects_missing_expr() {
2675        let node = proto_cast_node(None, Some(proto_int64_arrow_type()));
2676        let schema = Schema::empty();
2677        let decoder = UnreachableDecoder;
2678        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
2679
2680        let err = CastExpr::try_from_proto(&node, &ctx).unwrap_err();
2681        assert!(matches!(
2682            err,
2683            DataFusionError::Internal(msg)
2684                if msg.contains("CastExpr is missing required field 'expr'")
2685        ));
2686    }
2687
2688    #[test]
2689    fn try_from_proto_rejects_missing_arrow_type() {
2690        let node = proto_cast_node(Some(Box::new(column_node("a"))), None);
2691        let schema = Schema::empty();
2692        let decoder = StubDecoder::ok();
2693        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
2694
2695        let err = CastExpr::try_from_proto(&node, &ctx).unwrap_err();
2696        assert!(matches!(
2697            err,
2698            DataFusionError::Internal(msg)
2699                if msg.contains("CastExpr is missing required field 'arrow_type'")
2700        ));
2701    }
2702
2703    #[test]
2704    fn try_from_proto_propagates_child_decode_error() {
2705        let node = proto_cast_node(
2706            Some(Box::new(column_node("a"))),
2707            Some(proto_int64_arrow_type()),
2708        );
2709        let schema = Schema::empty();
2710        let decoder = StubDecoder::failing_on(1);
2711        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
2712
2713        let err = CastExpr::try_from_proto(&node, &ctx).unwrap_err();
2714        assert!(matches!(
2715            err,
2716            DataFusionError::Internal(msg) if msg.contains("call 1")
2717        ));
2718    }
2719}