Skip to main content

datafusion_physical_expr/expressions/
try_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::PhysicalExpr;
10use arrow::compute;
11use arrow::compute::CastOptions;
12use arrow::datatypes::{DataType, Field, FieldRef, Metadata, Schema};
13use arrow::record_batch::RecordBatch;
14use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
15use compute::can_cast_types;
16use datafusion_common::datatype::DataTypeExt;
17use datafusion_common::format::DEFAULT_FORMAT_OPTIONS;
18use datafusion_common::{Result, not_impl_err};
19use datafusion_expr::ColumnarValue;
20
21/// TRY_CAST expression casts an expression to a specific data type and returns NULL on invalid cast
22#[derive(Debug, Clone, Eq)]
23pub struct TryCastExpr {
24    /// The expression to cast
25    expr: Arc<dyn PhysicalExpr>,
26    /// The target field.
27    ///
28    /// For a type-only cast (see [`TryCastExpr::new`]) this is a field
29    /// synthesized from the target data type alone and only its data type is
30    /// meaningful. For a cast built from an explicit field (see
31    /// [`TryCastExpr::new_with_target_field`]) its metadata is applied to the
32    /// output field as-is.
33    target_field: FieldRef,
34    /// Whether `target_field` was supplied by the caller (as opposed to being
35    /// synthesized from a `DataType`), and therefore whether its metadata
36    /// describes the output field exactly.
37    explicit_target: bool,
38}
39
40// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
41impl PartialEq for TryCastExpr {
42    fn eq(&self, other: &Self) -> bool {
43        // Compare the semantically meaningful parts of the target field only:
44        // the field name never affects the output of this expression.
45        self.expr.eq(&other.expr)
46            && self.cast_type() == other.cast_type()
47            && self.target_metadata() == other.target_metadata()
48    }
49}
50
51impl Hash for TryCastExpr {
52    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
53        self.expr.hash(state);
54        self.cast_type().hash(state);
55        // Hash the metadata by iterating over sorted keys for deterministic ordering
56        if let Some(metadata) = self.target_metadata() {
57            let mut entries: Vec<_> = metadata.iter().collect();
58            entries.sort_by_key(|(k, _)| *k);
59            for (k, v) in entries {
60                k.hash(state);
61                v.hash(state);
62            }
63        }
64    }
65}
66
67impl TryCastExpr {
68    /// Create a new `TryCastExpr` using only a `DataType`.
69    ///
70    /// This constructor creates a type-only cast where metadata is passed through
71    /// from the source expression (with extension type keys stripped).
72    /// TRY_CAST results are always nullable since failed casts return NULL.
73    pub fn new(expr: Arc<dyn PhysicalExpr>, cast_type: DataType) -> Self {
74        Self {
75            expr,
76            target_field: cast_type.into_nullable_field_ref(),
77            explicit_target: false,
78        }
79    }
80
81    /// Create a new `TryCastExpr` with an explicit target `FieldRef`.
82    ///
83    /// The provided `target_field` determines the output characteristics:
84    /// - The field's data type becomes the cast target type
85    /// - The field's metadata is used exactly as provided
86    ///
87    /// TRY_CAST results are always nullable since failed casts return NULL.
88    ///
89    /// See [`TryCastExpr::new`] for type-only casts where source metadata should
90    /// pass through.
91    pub fn new_with_target_field(
92        expr: Arc<dyn PhysicalExpr>,
93        target_field: FieldRef,
94    ) -> Self {
95        Self {
96            expr,
97            target_field,
98            explicit_target: true,
99        }
100    }
101
102    /// The expression to cast
103    pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
104        &self.expr
105    }
106
107    /// The data type to cast to
108    pub fn cast_type(&self) -> &DataType {
109        self.target_field.data_type()
110    }
111
112    /// Explicit metadata for the output field, or `None` to pass through source metadata.
113    pub fn target_metadata(&self) -> Option<&Metadata> {
114        self.explicit_target.then(|| self.target_field.metadata())
115    }
116
117    /// The target field this cast was constructed with.
118    ///
119    /// For a type-only cast this is a field synthesized from the target data
120    /// type alone; only its data type is meaningful. TRY_CAST results are
121    /// always nullable regardless of the target field's nullability.
122    pub fn target_field(&self) -> &FieldRef {
123        &self.target_field
124    }
125}
126
127impl fmt::Display for TryCastExpr {
128    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
129        write!(f, "TRY_CAST({} AS {})", self.expr, self.cast_type())
130    }
131}
132
133impl PhysicalExpr for TryCastExpr {
134    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
135        Ok(self.cast_type().clone())
136    }
137
138    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
139        Ok(true)
140    }
141
142    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
143        let value = self.expr.evaluate(batch)?;
144        let options = CastOptions {
145            safe: true,
146            format_options: DEFAULT_FORMAT_OPTIONS,
147        };
148        value.cast_to(self.cast_type(), Some(&options))
149    }
150
151    fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
152        // If metadata is explicit, we can build the field without source
153        // (though we still try to get source for the name)
154        let source_result = self.expr.return_field(input_schema);
155
156        if let Some(metadata) = self.target_metadata() {
157            // Explicit metadata: use it exactly, TRY_CAST is always nullable
158            let name = source_result
159                .as_ref()
160                .map(|f| f.name().to_string())
161                .unwrap_or_default();
162            return Ok(Arc::new(
163                Field::new(name, self.cast_type().clone(), true)
164                    .with_metadata(metadata.clone()),
165            ));
166        }
167
168        // Pass-through metadata from source (stripping extension keys)
169        source_result.map(|source_field| {
170            let mut metadata = source_field.metadata().clone();
171            metadata.remove(EXTENSION_TYPE_NAME_KEY);
172            metadata.remove(EXTENSION_TYPE_METADATA_KEY);
173
174            Arc::new(
175                source_field
176                    .as_ref()
177                    .clone()
178                    .with_data_type(self.cast_type().clone())
179                    .with_nullable(true) // TRY_CAST is always nullable
180                    .with_metadata(metadata),
181            )
182        })
183    }
184
185    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
186        vec![&self.expr]
187    }
188
189    fn with_new_children(
190        self: Arc<Self>,
191        children: Vec<Arc<dyn PhysicalExpr>>,
192    ) -> Result<Arc<dyn PhysicalExpr>> {
193        Ok(Arc::new(TryCastExpr {
194            expr: Arc::clone(&children[0]),
195            target_field: Arc::clone(&self.target_field),
196            explicit_target: self.explicit_target,
197        }))
198    }
199
200    fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        write!(f, "TRY_CAST(")?;
202        self.expr.fmt_sql(f)?;
203        write!(f, " AS {:?})", self.cast_type())
204    }
205
206    #[cfg(feature = "proto")]
207    fn try_to_proto(
208        &self,
209        ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
210    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
211        use datafusion_proto_models::protobuf;
212
213        let Self {
214            expr,
215            target_field,
216            explicit_target,
217        } = self;
218        // Presence carries `explicit_target`, even for a default-shaped field.
219        let target_field_proto = if *explicit_target {
220            Some(target_field.as_ref().try_into()?)
221        } else {
222            None
223        };
224
225        Ok(Some(protobuf::PhysicalExprNode {
226            expr_id: None,
227            expr_type: Some(protobuf::physical_expr_node::ExprType::TryCast(Box::new(
228                protobuf::PhysicalTryCastNode {
229                    expr: Some(Box::new(ctx.encode_child(expr)?)),
230                    arrow_type: Some(target_field.data_type().try_into()?),
231                    target_field: target_field_proto,
232                },
233            ))),
234        }))
235    }
236}
237
238#[cfg(feature = "proto")]
239impl TryCastExpr {
240    /// Reconstruct a [`TryCastExpr`] from its protobuf representation.
241    pub fn try_from_proto(
242        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
243        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
244    ) -> Result<Arc<dyn PhysicalExpr>> {
245        use datafusion_common::internal_err;
246        use datafusion_physical_expr_common::expect_expr_variant;
247        use datafusion_physical_expr_common::physical_expr::proto_decode::require_proto_field;
248        use datafusion_proto_models::protobuf;
249
250        let try_cast = expect_expr_variant!(
251            node,
252            protobuf::physical_expr_node::ExprType::TryCast,
253            "TryCastExpr",
254        );
255        let protobuf::PhysicalTryCastNode {
256            expr,
257            arrow_type,
258            target_field,
259        } = &**try_cast;
260        let expr =
261            ctx.decode_required_expression(expr.as_deref(), "TryCastExpr", "expr")?;
262        let arrow_type =
263            require_proto_field(arrow_type.as_ref(), "TryCastExpr", "arrow_type")?;
264        let cast_type: DataType = arrow_type.try_into()?;
265        let target_field = target_field
266            .as_ref()
267            .map(|field| {
268                let field: Field = field.try_into()?;
269                if field.data_type() != &cast_type {
270                    return internal_err!(
271                        "TryCastExpr target_field type does not match arrow_type"
272                    );
273                }
274                Ok(Arc::new(field))
275            })
276            .transpose()?;
277
278        Ok(Arc::new(match target_field {
279            Some(target_field) => TryCastExpr::new_with_target_field(expr, target_field),
280            None => TryCastExpr::new(expr, cast_type),
281        }))
282    }
283}
284
285/// Return a PhysicalExpression representing `expr` casted to
286/// `cast_type`, if any casting is needed.
287///
288/// Note that such casts may lose type information
289pub fn try_cast(
290    expr: Arc<dyn PhysicalExpr>,
291    input_schema: &Schema,
292    cast_type: DataType,
293) -> Result<Arc<dyn PhysicalExpr>> {
294    let expr_type = expr.data_type(input_schema)?;
295    if expr_type == cast_type {
296        Ok(Arc::clone(&expr))
297    } else if can_cast_types(&expr_type, &cast_type) {
298        Ok(Arc::new(TryCastExpr::new(expr, cast_type)))
299    } else {
300        not_impl_err!("Unsupported TRY_CAST from {expr_type} to {cast_type}")
301    }
302}
303
304/// Return a PhysicalExpression representing `expr` casted to `target_field`,
305/// preserving any explicit field semantics such as metadata.
306///
307/// TRY_CAST results are always nullable since failed casts return NULL.
308///
309/// If the input expression already has the same data type, the target field
310/// has no explicit metadata constraints, and the source has no extension
311/// metadata to strip, the original expression is returned unchanged.
312pub fn try_cast_with_target_field(
313    expr: Arc<dyn PhysicalExpr>,
314    input_schema: &Schema,
315    target_field: &FieldRef,
316) -> Result<Arc<dyn PhysicalExpr>> {
317    let expr_type = expr.data_type(input_schema)?;
318    let cast_type = target_field.data_type();
319
320    // Check if this is a "default" target field (type-only cast with no explicit
321    // metadata constraints). This is the field created by `into_nullable_field_ref()`
322    // when only a DataType is known.
323    let is_type_only = target_field.name().is_empty()
324        && target_field.is_nullable()
325        && target_field.metadata().is_empty();
326
327    // For same-type casts, we can skip creating a TryCastExpr only if:
328    // 1. The target is type-only (no explicit metadata)
329    // 2. The source has no extension metadata that needs to be stripped
330    // Otherwise we need the TryCastExpr to strip extension metadata from the source.
331    if expr_type == *cast_type && is_type_only {
332        let source_field = expr.return_field(input_schema)?;
333        let has_extension_metadata = source_field
334            .metadata()
335            .contains_key(EXTENSION_TYPE_NAME_KEY);
336        if !has_extension_metadata {
337            return Ok(Arc::clone(&expr));
338        }
339    }
340
341    if !can_cast_types(&expr_type, cast_type) {
342        return not_impl_err!("Unsupported TRY_CAST from {expr_type} to {cast_type}");
343    }
344
345    // For type-only casts, use TryCastExpr::new which preserves source metadata.
346    // For explicit target fields, use new_with_target_field which applies the target's
347    // metadata exactly.
348    if is_type_only {
349        Ok(Arc::new(TryCastExpr::new(expr, cast_type.clone())))
350    } else {
351        Ok(Arc::new(TryCastExpr::new_with_target_field(
352            expr,
353            Arc::clone(target_field),
354        )))
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use std::collections::HashMap;
361
362    use super::*;
363    use crate::expressions::col;
364    use arrow::array::{
365        Decimal128Array, Decimal128Builder, StringArray, Time64NanosecondArray,
366    };
367    use arrow::{
368        array::{
369            Array, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array,
370            Int64Array, TimestampNanosecondArray, UInt32Array,
371        },
372        datatypes::*,
373    };
374    use datafusion_physical_expr_common::physical_expr::fmt_sql;
375
376    // runs an end-to-end test of physical type cast
377    // 1. construct a record batch with a column "a" of type A
378    // 2. construct a physical expression of TRY_CAST(a AS B)
379    // 3. evaluate the expression
380    // 4. verify that the resulting expression is of type B
381    // 5. verify that the resulting values are downcastable and correct
382    macro_rules! generic_decimal_to_other_test_cast {
383        ($DECIMAL_ARRAY:ident, $A_TYPE:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr) => {{
384            let schema = Schema::new(vec![Field::new("a", $A_TYPE, true)]);
385            let batch = RecordBatch::try_new(
386                Arc::new(schema.clone()),
387                vec![Arc::new($DECIMAL_ARRAY)],
388            )?;
389            // verify that we can construct the expression
390            let expression = try_cast(col("a", &schema)?, &schema, $TYPE)?;
391
392            // verify that its display is correct
393            assert_eq!(
394                format!("TRY_CAST(a@0 AS {})", $TYPE),
395                format!("{}", expression)
396            );
397
398            // verify that the expression's type is correct
399            assert_eq!(expression.data_type(&schema)?, $TYPE);
400
401            // compute
402            let result = expression
403                .evaluate(&batch)?
404                .into_array(batch.num_rows())
405                .expect("Failed to convert to array");
406
407            // verify that the array's data_type is correct
408            assert_eq!(*result.data_type(), $TYPE);
409
410            // verify that the data itself is downcastable
411            let result = result
412                .as_any()
413                .downcast_ref::<$TYPEARRAY>()
414                .expect("failed to downcast");
415
416            // verify that the result itself is correct
417            for (i, x) in $VEC.iter().enumerate() {
418                match x {
419                    Some(x) => assert_eq!(result.value(i), *x),
420                    None => assert!(result.is_null(i)),
421                }
422            }
423        }};
424    }
425
426    // runs an end-to-end test of physical type cast
427    // 1. construct a record batch with a column "a" of type A
428    // 2. construct a physical expression of TRY_CAST(a AS B)
429    // 3. evaluate the expression
430    // 4. verify that the resulting expression is of type B
431    // 5. verify that the resulting values are downcastable and correct
432    macro_rules! generic_test_cast {
433        ($A_ARRAY:ident, $A_TYPE:expr, $A_VEC:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr) => {{
434            let schema = Schema::new(vec![Field::new("a", $A_TYPE, true)]);
435            let a_vec_len = $A_VEC.len();
436            let a = $A_ARRAY::from($A_VEC);
437            let batch =
438                RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
439
440            // verify that we can construct the expression
441            let expression = try_cast(col("a", &schema)?, &schema, $TYPE)?;
442
443            // verify that its display is correct
444            assert_eq!(
445                format!("TRY_CAST(a@0 AS {})", $TYPE),
446                format!("{}", expression)
447            );
448
449            // verify that the expression's type is correct
450            assert_eq!(expression.data_type(&schema)?, $TYPE);
451
452            // compute
453            let result = expression
454                .evaluate(&batch)?
455                .into_array(batch.num_rows())
456                .expect("Failed to convert to array");
457
458            // verify that the array's data_type is correct
459            assert_eq!(*result.data_type(), $TYPE);
460
461            // verify that the len is correct
462            assert_eq!(result.len(), a_vec_len);
463
464            // verify that the data itself is downcastable
465            let result = result
466                .as_any()
467                .downcast_ref::<$TYPEARRAY>()
468                .expect("failed to downcast");
469
470            // verify that the result itself is correct
471            for (i, x) in $VEC.iter().enumerate() {
472                match x {
473                    Some(x) => assert_eq!(result.value(i), *x),
474                    None => assert!(result.is_null(i)),
475                }
476            }
477        }};
478    }
479
480    #[test]
481    fn test_try_cast_decimal_to_decimal() -> Result<()> {
482        // try cast one decimal data type to another decimal data type
483        let array: Vec<i128> = vec![1234, 2222, 3, 4000, 5000];
484        let decimal_array = create_decimal_array(&array, 10, 3);
485        generic_decimal_to_other_test_cast!(
486            decimal_array,
487            DataType::Decimal128(10, 3),
488            Decimal128Array,
489            DataType::Decimal128(20, 6),
490            [
491                Some(1_234_000),
492                Some(2_222_000),
493                Some(3_000),
494                Some(4_000_000),
495                Some(5_000_000),
496                None
497            ]
498        );
499
500        let decimal_array = create_decimal_array(&array, 10, 3);
501        generic_decimal_to_other_test_cast!(
502            decimal_array,
503            DataType::Decimal128(10, 3),
504            Decimal128Array,
505            DataType::Decimal128(10, 2),
506            [Some(123), Some(222), Some(0), Some(400), Some(500), None]
507        );
508
509        Ok(())
510    }
511
512    #[test]
513    fn test_try_cast_decimal_to_numeric() -> Result<()> {
514        // TODO we should add function to create Decimal128Array with value and metadata
515        // https://github.com/apache/arrow-rs/issues/1009
516        let array: Vec<i128> = vec![1, 2, 3, 4, 5];
517        let decimal_array = create_decimal_array(&array, 10, 0);
518        // decimal to i8
519        generic_decimal_to_other_test_cast!(
520            decimal_array,
521            DataType::Decimal128(10, 0),
522            Int8Array,
523            DataType::Int8,
524            [
525                Some(1_i8),
526                Some(2_i8),
527                Some(3_i8),
528                Some(4_i8),
529                Some(5_i8),
530                None
531            ]
532        );
533
534        // decimal to i16
535        let decimal_array = create_decimal_array(&array, 10, 0);
536        generic_decimal_to_other_test_cast!(
537            decimal_array,
538            DataType::Decimal128(10, 0),
539            Int16Array,
540            DataType::Int16,
541            [
542                Some(1_i16),
543                Some(2_i16),
544                Some(3_i16),
545                Some(4_i16),
546                Some(5_i16),
547                None
548            ]
549        );
550
551        // decimal to i32
552        let decimal_array = create_decimal_array(&array, 10, 0);
553        generic_decimal_to_other_test_cast!(
554            decimal_array,
555            DataType::Decimal128(10, 0),
556            Int32Array,
557            DataType::Int32,
558            [
559                Some(1_i32),
560                Some(2_i32),
561                Some(3_i32),
562                Some(4_i32),
563                Some(5_i32),
564                None
565            ]
566        );
567
568        // decimal to i64
569        let decimal_array = create_decimal_array(&array, 10, 0);
570        generic_decimal_to_other_test_cast!(
571            decimal_array,
572            DataType::Decimal128(10, 0),
573            Int64Array,
574            DataType::Int64,
575            [
576                Some(1_i64),
577                Some(2_i64),
578                Some(3_i64),
579                Some(4_i64),
580                Some(5_i64),
581                None
582            ]
583        );
584
585        // decimal to float32
586        let array: Vec<i128> = vec![1234, 2222, 3, 4000, 5000];
587        let decimal_array = create_decimal_array(&array, 10, 3);
588        generic_decimal_to_other_test_cast!(
589            decimal_array,
590            DataType::Decimal128(10, 3),
591            Float32Array,
592            DataType::Float32,
593            [
594                Some(1.234_f32),
595                Some(2.222_f32),
596                Some(0.003_f32),
597                Some(4.0_f32),
598                Some(5.0_f32),
599                None
600            ]
601        );
602        // decimal to float64
603        let decimal_array = create_decimal_array(&array, 20, 6);
604        generic_decimal_to_other_test_cast!(
605            decimal_array,
606            DataType::Decimal128(20, 6),
607            Float64Array,
608            DataType::Float64,
609            [
610                Some(0.001234_f64),
611                Some(0.002222_f64),
612                Some(0.000003_f64),
613                Some(0.004_f64),
614                Some(0.005_f64),
615                None
616            ]
617        );
618
619        Ok(())
620    }
621
622    #[test]
623    fn test_try_cast_numeric_to_decimal() -> Result<()> {
624        // int8
625        generic_test_cast!(
626            Int8Array,
627            DataType::Int8,
628            vec![1, 2, 3, 4, 5],
629            Decimal128Array,
630            DataType::Decimal128(3, 0),
631            [Some(1), Some(2), Some(3), Some(4), Some(5)]
632        );
633
634        // int16
635        generic_test_cast!(
636            Int16Array,
637            DataType::Int16,
638            vec![1, 2, 3, 4, 5],
639            Decimal128Array,
640            DataType::Decimal128(5, 0),
641            [Some(1), Some(2), Some(3), Some(4), Some(5)]
642        );
643
644        // int32
645        generic_test_cast!(
646            Int32Array,
647            DataType::Int32,
648            vec![1, 2, 3, 4, 5],
649            Decimal128Array,
650            DataType::Decimal128(10, 0),
651            [Some(1), Some(2), Some(3), Some(4), Some(5)]
652        );
653
654        // int64
655        generic_test_cast!(
656            Int64Array,
657            DataType::Int64,
658            vec![1, 2, 3, 4, 5],
659            Decimal128Array,
660            DataType::Decimal128(20, 0),
661            [Some(1), Some(2), Some(3), Some(4), Some(5)]
662        );
663
664        // int64 to different scale
665        generic_test_cast!(
666            Int64Array,
667            DataType::Int64,
668            vec![1, 2, 3, 4, 5],
669            Decimal128Array,
670            DataType::Decimal128(20, 2),
671            [Some(100), Some(200), Some(300), Some(400), Some(500)]
672        );
673
674        // float32
675        generic_test_cast!(
676            Float32Array,
677            DataType::Float32,
678            vec![1.5, 2.5, 3.0, 1.123_456_8, 5.50],
679            Decimal128Array,
680            DataType::Decimal128(10, 2),
681            [Some(150), Some(250), Some(300), Some(112), Some(550)]
682        );
683
684        // float64
685        generic_test_cast!(
686            Float64Array,
687            DataType::Float64,
688            vec![1.5, 2.5, 3.0, 1.123_456_8, 5.50],
689            Decimal128Array,
690            DataType::Decimal128(20, 4),
691            [
692                Some(15000),
693                Some(25000),
694                Some(30000),
695                Some(11235),
696                Some(55000)
697            ]
698        );
699        Ok(())
700    }
701
702    #[test]
703    fn test_cast_i32_u32() -> Result<()> {
704        generic_test_cast!(
705            Int32Array,
706            DataType::Int32,
707            vec![1, 2, 3, 4, 5],
708            UInt32Array,
709            DataType::UInt32,
710            [
711                Some(1_u32),
712                Some(2_u32),
713                Some(3_u32),
714                Some(4_u32),
715                Some(5_u32)
716            ]
717        );
718        Ok(())
719    }
720
721    #[test]
722    fn test_cast_i32_utf8() -> Result<()> {
723        generic_test_cast!(
724            Int32Array,
725            DataType::Int32,
726            vec![1, 2, 3, 4, 5],
727            StringArray,
728            DataType::Utf8,
729            [Some("1"), Some("2"), Some("3"), Some("4"), Some("5")]
730        );
731        Ok(())
732    }
733
734    #[test]
735    fn test_try_cast_utf8_i32() -> Result<()> {
736        generic_test_cast!(
737            StringArray,
738            DataType::Utf8,
739            vec!["a", "2", "3", "b", "5"],
740            Int32Array,
741            DataType::Int32,
742            [None, Some(2), Some(3), None, Some(5)]
743        );
744        Ok(())
745    }
746
747    #[test]
748    fn test_cast_i64_t64() -> Result<()> {
749        let original = vec![1, 2, 3, 4, 5];
750        let expected: Vec<Option<i64>> = original
751            .iter()
752            .map(|i| Some(Time64NanosecondArray::from(vec![*i]).value(0)))
753            .collect();
754        generic_test_cast!(
755            Int64Array,
756            DataType::Int64,
757            original,
758            TimestampNanosecondArray,
759            DataType::Timestamp(TimeUnit::Nanosecond, None),
760            expected
761        );
762        Ok(())
763    }
764
765    #[test]
766    fn invalid_cast() {
767        // Ensure a useful error happens at plan time if invalid casts are used
768        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
769
770        let result = try_cast(
771            col("a", &schema).unwrap(),
772            &schema,
773            DataType::Interval(IntervalUnit::MonthDayNano),
774        );
775        result.expect_err("expected Invalid TRY_CAST");
776    }
777
778    // create decimal array with the specified precision and scale
779    fn create_decimal_array(array: &[i128], precision: u8, scale: i8) -> Decimal128Array {
780        let mut decimal_builder = Decimal128Builder::with_capacity(array.len());
781        for value in array {
782            decimal_builder.append_value(*value);
783        }
784        decimal_builder.append_null();
785        decimal_builder
786            .finish()
787            .with_precision_and_scale(precision, scale)
788            .unwrap()
789    }
790
791    #[test]
792    fn test_fmt_sql() -> Result<()> {
793        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
794
795        // Test numeric casting
796        let expr = try_cast(col("a", &schema)?, &schema, DataType::Int64)?;
797        let display_string = expr.to_string();
798        assert_eq!(display_string, "TRY_CAST(a@0 AS Int64)");
799        let sql_string = fmt_sql(expr.as_ref()).to_string();
800        assert_eq!(sql_string, "TRY_CAST(a AS Int64)");
801
802        // Test string casting
803        let schema = Schema::new(vec![Field::new("b", DataType::Utf8, true)]);
804        let expr = try_cast(col("b", &schema)?, &schema, DataType::Int32)?;
805        let display_string = expr.to_string();
806        assert_eq!(display_string, "TRY_CAST(b@0 AS Int32)");
807        let sql_string = fmt_sql(expr.as_ref()).to_string();
808        assert_eq!(sql_string, "TRY_CAST(b AS Int32)");
809
810        Ok(())
811    }
812
813    #[test]
814    fn field_aware_try_cast_uses_exact_target_metadata() -> Result<()> {
815        // When using field-aware cast, target's metadata should be used exactly
816        let source_meta = HashMap::from([
817            (
818                EXTENSION_TYPE_NAME_KEY.to_string(),
819                "source.type".to_string(),
820            ),
821            ("source_key".to_string(), "source_value".to_string()),
822        ]);
823        let target_meta = HashMap::from([
824            (
825                EXTENSION_TYPE_NAME_KEY.to_string(),
826                "target.type".to_string(),
827            ),
828            (
829                EXTENSION_TYPE_METADATA_KEY.to_string(),
830                "target_ext_meta".to_string(),
831            ),
832            ("target_key".to_string(), "target_value".to_string()),
833        ]);
834        let schema = Schema::new(vec![
835            Field::new("a", DataType::FixedSizeBinary(16), false)
836                .with_metadata(source_meta),
837        ]);
838
839        let target_field =
840            Arc::new(Field::new("b", DataType::Utf8, true).with_metadata(target_meta));
841        let expr = TryCastExpr::new_with_target_field(
842            col("a", &schema)?,
843            Arc::clone(&target_field),
844        );
845
846        let field = expr.return_field(&schema)?;
847        assert_eq!(
848            field.metadata().get(EXTENSION_TYPE_NAME_KEY),
849            Some(&"target.type".to_string()),
850            "Field-aware try_cast should use target's extension type name"
851        );
852        assert_eq!(
853            field.metadata().get(EXTENSION_TYPE_METADATA_KEY),
854            Some(&"target_ext_meta".to_string()),
855            "Field-aware try_cast should use target's extension type metadata"
856        );
857        assert!(
858            field.metadata().get("source_key").is_none(),
859            "Field-aware try_cast should NOT preserve source metadata"
860        );
861        assert_eq!(
862            field.metadata().get("target_key"),
863            Some(&"target_value".to_string()),
864            "Field-aware try_cast should preserve target's non-extension metadata"
865        );
866        // TRY_CAST is always nullable
867        assert!(field.is_nullable());
868
869        Ok(())
870    }
871
872    #[test]
873    fn field_aware_try_cast_preserves_target_field_semantics() -> Result<()> {
874        // Target field metadata should be preserved exactly (no merging with source).
875        // TRY_CAST is always nullable regardless of target field's nullability.
876        let metadata = HashMap::from([("target_meta".to_string(), "1".to_string())]);
877
878        for child_nullable in [true, false] {
879            let schema =
880                Schema::new(vec![Field::new("a", DataType::Int32, child_nullable)]);
881            let target_field = Arc::new(
882                Field::new("cast_target", DataType::Int64, false) // target says non-nullable
883                    .with_metadata(metadata.clone()),
884            );
885            let expr = TryCastExpr::new_with_target_field(
886                col("a", &schema)?,
887                Arc::clone(&target_field),
888            );
889
890            let field = expr.return_field(&schema)?;
891            // Field name comes from source
892            assert_eq!(field.name(), "a");
893            assert_eq!(field.data_type(), &DataType::Int64);
894            // TRY_CAST is ALWAYS nullable (ignores target field's nullability)
895            assert!(field.is_nullable(), "TRY_CAST should always be nullable");
896            // Target metadata should be preserved exactly
897            assert_eq!(
898                field.metadata().get("target_meta"),
899                Some(&"1".to_string()),
900                "Target metadata should be preserved exactly"
901            );
902            assert!(
903                expr.nullable(&schema)?,
904                "TRY_CAST should always be nullable"
905            );
906        }
907
908        Ok(())
909    }
910
911    #[test]
912    fn type_only_try_cast_strips_extension_keys() -> Result<()> {
913        // Type-only cast should strip extension keys but preserve other source metadata
914        let source_meta = HashMap::from([
915            (
916                EXTENSION_TYPE_NAME_KEY.to_string(),
917                "source.extension".to_string(),
918            ),
919            (
920                EXTENSION_TYPE_METADATA_KEY.to_string(),
921                "ext_meta".to_string(),
922            ),
923            ("custom_key".to_string(), "custom_value".to_string()),
924        ]);
925        let schema = Schema::new(vec![
926            Field::new("a", DataType::Int32, false).with_metadata(source_meta),
927        ]);
928
929        let expr = TryCastExpr::new(col("a", &schema)?, DataType::Int64);
930        let field = expr.return_field(&schema)?;
931
932        // Extension keys should be stripped
933        assert!(
934            field.metadata().get(EXTENSION_TYPE_NAME_KEY).is_none(),
935            "Type-only try_cast should strip extension type name"
936        );
937        assert!(
938            field.metadata().get(EXTENSION_TYPE_METADATA_KEY).is_none(),
939            "Type-only try_cast should strip extension type metadata"
940        );
941        // Non-extension metadata should pass through
942        assert_eq!(
943            field.metadata().get("custom_key"),
944            Some(&"custom_value".to_string()),
945            "Type-only try_cast should preserve non-extension metadata"
946        );
947        // Field name preserved, type changed, always nullable
948        assert_eq!(field.name(), "a");
949        assert_eq!(field.data_type(), &DataType::Int64);
950        assert!(field.is_nullable());
951
952        Ok(())
953    }
954
955    #[test]
956    fn type_only_try_cast_is_always_nullable() -> Result<()> {
957        // TRY_CAST is always nullable even when source is non-nullable
958        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
959        let expr = TryCastExpr::new(col("a", &schema)?, DataType::Int64);
960
961        let field = expr.return_field(&schema)?;
962
963        assert_eq!(field.name(), "a");
964        assert_eq!(field.data_type(), &DataType::Int64);
965        assert!(field.is_nullable(), "TRY_CAST should always be nullable");
966        assert!(
967            expr.nullable(&schema)?,
968            "TRY_CAST should always be nullable"
969        );
970
971        Ok(())
972    }
973}
974
975#[cfg(all(test, feature = "proto"))]
976mod proto_tests {
977    use super::*;
978    use crate::expressions::{Column, col};
979    use crate::proto_test_util::{
980        StubDecoder, StubEncoder, UnreachableDecoder, column_node,
981    };
982    use arrow::datatypes::Field;
983    use datafusion_common::DataFusionError;
984    use datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx;
985    use datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx;
986    use datafusion_proto_models::datafusion_common::ArrowType;
987    use datafusion_proto_models::protobuf::{
988        PhysicalExprNode, PhysicalTryCastNode, physical_expr_node,
989    };
990
991    fn try_cast_fixture() -> TryCastExpr {
992        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
993        TryCastExpr::new(col("a", &schema).unwrap(), DataType::Int32)
994    }
995
996    fn int32_arrow_type() -> ArrowType {
997        (&DataType::Int32).try_into().unwrap()
998    }
999
1000    fn try_cast_node(
1001        expr: Option<Box<PhysicalExprNode>>,
1002        arrow_type: Option<ArrowType>,
1003    ) -> PhysicalExprNode {
1004        PhysicalExprNode {
1005            expr_id: None,
1006            expr_type: Some(physical_expr_node::ExprType::TryCast(Box::new(
1007                PhysicalTryCastNode {
1008                    expr,
1009                    arrow_type,
1010                    target_field: None,
1011                },
1012            ))),
1013        }
1014    }
1015
1016    fn encode_try_cast(try_cast: &TryCastExpr) -> PhysicalTryCastNode {
1017        let encoder = StubEncoder::ok();
1018        let node = try_cast
1019            .try_to_proto(&PhysicalExprEncodeCtx::new(&encoder))
1020            .unwrap()
1021            .expect("TryCastExpr should encode to Some(node)");
1022        match node.expr_type {
1023            Some(physical_expr_node::ExprType::TryCast(try_cast)) => *try_cast,
1024            other => panic!("expected a TryCastExpr node, got {other:?}"),
1025        }
1026    }
1027
1028    fn round_trip_try_cast(try_cast: &TryCastExpr, schema: &Schema) -> TryCastExpr {
1029        let encoder = StubEncoder::ok();
1030        let node = try_cast
1031            .try_to_proto(&PhysicalExprEncodeCtx::new(&encoder))
1032            .unwrap()
1033            .expect("TryCastExpr should encode to Some(node)");
1034        let decoder = StubDecoder::ok();
1035        TryCastExpr::try_from_proto(&node, &PhysicalExprDecodeCtx::new(schema, &decoder))
1036            .unwrap()
1037            .downcast_ref::<TryCastExpr>()
1038            .expect("decoded expr should be a TryCastExpr")
1039            .clone()
1040    }
1041
1042    #[test]
1043    fn try_to_proto_encodes_try_cast_expr() {
1044        let try_cast = try_cast_fixture();
1045        let encoder = StubEncoder::ok();
1046        let ctx = PhysicalExprEncodeCtx::new(&encoder);
1047
1048        let node = try_cast
1049            .try_to_proto(&ctx)
1050            .unwrap()
1051            .expect("TryCastExpr should encode to Some(node)");
1052
1053        assert!(node.expr_id.is_none());
1054        let try_cast_node = match node.expr_type {
1055            Some(physical_expr_node::ExprType::TryCast(boxed)) => *boxed,
1056            other => panic!("expected a TryCastExpr node, got {other:?}"),
1057        };
1058        assert!(try_cast_node.expr.is_some());
1059
1060        let arrow_type = try_cast_node
1061            .arrow_type
1062            .as_ref()
1063            .expect("try cast type should be encoded");
1064        let data_type: DataType = arrow_type.try_into().unwrap();
1065        assert_eq!(data_type, DataType::Int32);
1066        assert!(try_cast_node.target_field.is_none());
1067    }
1068
1069    #[test]
1070    fn try_cast_target_field_survives_proto_round_trip() {
1071        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
1072        let target =
1073            Arc::new(Field::new("target", DataType::Int32, false).with_metadata(
1074                Metadata::from([("extension".to_string(), "value".to_string())]),
1075            ));
1076        let try_cast = TryCastExpr::new_with_target_field(
1077            col("a", &schema).unwrap(),
1078            Arc::clone(&target),
1079        );
1080
1081        assert!(encode_try_cast(&try_cast).target_field.is_some());
1082        let decoded = round_trip_try_cast(&try_cast, &schema);
1083
1084        assert_eq!(decoded.target_field(), &target);
1085        assert_eq!(decoded.target_metadata(), Some(target.metadata()));
1086    }
1087
1088    #[test]
1089    fn explicit_default_shaped_try_cast_target_is_encoded() {
1090        let schema =
1091            Schema::new(vec![Field::new("a", DataType::Utf8, false).with_metadata(
1092                Metadata::from([("source".to_string(), "value".to_string())]),
1093            )]);
1094        let try_cast = TryCastExpr::new_with_target_field(
1095            col("a", &schema).unwrap(),
1096            DataType::Int32.into_nullable_field_ref(),
1097        );
1098
1099        assert!(encode_try_cast(&try_cast).target_field.is_some());
1100        let decoded = round_trip_try_cast(&try_cast, &schema);
1101        assert_eq!(decoded.target_metadata(), Some(&Metadata::default()));
1102        assert!(decoded.return_field(&schema).unwrap().metadata().is_empty());
1103    }
1104
1105    #[test]
1106    fn type_only_try_cast_target_is_omitted_and_remains_type_only() {
1107        let metadata = Metadata::from([("source".to_string(), "value".to_string())]);
1108        let schema = Schema::new(vec![
1109            Field::new("a", DataType::Utf8, false).with_metadata(metadata.clone()),
1110        ]);
1111        let try_cast = TryCastExpr::new(col("a", &schema).unwrap(), DataType::Int32);
1112
1113        assert!(encode_try_cast(&try_cast).target_field.is_none());
1114        let decoded = round_trip_try_cast(&try_cast, &schema);
1115
1116        assert_eq!(decoded.target_metadata(), None);
1117        let output = decoded.return_field(&schema).unwrap();
1118        assert_eq!(output.metadata(), &metadata);
1119        assert!(output.is_nullable());
1120    }
1121
1122    #[test]
1123    fn try_to_proto_propagates_child_encode_error() {
1124        let try_cast = try_cast_fixture();
1125        let encoder = StubEncoder::failing_on(1);
1126        let ctx = PhysicalExprEncodeCtx::new(&encoder);
1127        let err = try_cast.try_to_proto(&ctx).unwrap_err();
1128        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
1129    }
1130
1131    #[test]
1132    fn try_from_proto_decodes_legacy_try_cast_expr() {
1133        let node =
1134            try_cast_node(Some(Box::new(column_node("a"))), Some(int32_arrow_type()));
1135        let schema = Schema::empty();
1136        let decoder = StubDecoder::ok();
1137        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
1138
1139        let decoded = TryCastExpr::try_from_proto(&node, &ctx).unwrap();
1140        let try_cast = decoded
1141            .downcast_ref::<TryCastExpr>()
1142            .expect("decoded expr should be a TryCastExpr");
1143
1144        assert_eq!(try_cast.cast_type(), &DataType::Int32);
1145        assert!(try_cast.expr().downcast_ref::<Column>().is_some());
1146        assert_eq!(try_cast.target_metadata(), None);
1147    }
1148
1149    #[test]
1150    fn try_from_proto_rejects_mismatched_target_field_type() {
1151        let mut node =
1152            try_cast_node(Some(Box::new(column_node("a"))), Some(int32_arrow_type()));
1153        let Some(physical_expr_node::ExprType::TryCast(try_cast)) =
1154            node.expr_type.as_mut()
1155        else {
1156            unreachable!()
1157        };
1158        try_cast.target_field = Some(
1159            (&Field::new("target", DataType::Int64, true))
1160                .try_into()
1161                .unwrap(),
1162        );
1163        let schema = Schema::empty();
1164        let decoder = StubDecoder::ok();
1165
1166        let err = TryCastExpr::try_from_proto(
1167            &node,
1168            &PhysicalExprDecodeCtx::new(&schema, &decoder),
1169        )
1170        .unwrap_err();
1171        assert!(err.to_string().contains("target_field type"));
1172    }
1173
1174    #[test]
1175    fn try_from_proto_rejects_non_try_cast_node() {
1176        let node = column_node("a");
1177        let schema = Schema::empty();
1178        let decoder = UnreachableDecoder;
1179        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
1180
1181        let err = TryCastExpr::try_from_proto(&node, &ctx).unwrap_err();
1182        assert!(
1183            matches!(err, DataFusionError::Internal(msg) if msg.contains("PhysicalExprNode is not a TryCastExpr"))
1184        );
1185    }
1186
1187    #[test]
1188    fn try_from_proto_rejects_missing_expr() {
1189        let node = try_cast_node(None, Some(int32_arrow_type()));
1190        let schema = Schema::empty();
1191        let decoder = UnreachableDecoder;
1192        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
1193
1194        let err = TryCastExpr::try_from_proto(&node, &ctx).unwrap_err();
1195        assert!(
1196            matches!(err, DataFusionError::Internal(msg) if msg.contains("TryCastExpr is missing required field 'expr'"))
1197        );
1198    }
1199
1200    #[test]
1201    fn try_from_proto_rejects_missing_arrow_type() {
1202        let node = try_cast_node(Some(Box::new(column_node("a"))), None);
1203        let schema = Schema::empty();
1204        let decoder = StubDecoder::ok();
1205        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
1206
1207        let err = TryCastExpr::try_from_proto(&node, &ctx).unwrap_err();
1208        assert!(
1209            matches!(err, DataFusionError::Internal(msg) if msg.contains("TryCastExpr is missing required field 'arrow_type'"))
1210        );
1211    }
1212
1213    #[test]
1214    fn try_from_proto_propagates_child_decode_error() {
1215        let node =
1216            try_cast_node(Some(Box::new(column_node("a"))), Some(int32_arrow_type()));
1217        let schema = Schema::empty();
1218        let decoder = StubDecoder::failing_on(1);
1219        let ctx = PhysicalExprDecodeCtx::new(&schema, &decoder);
1220        let err = TryCastExpr::try_from_proto(&node, &ctx).unwrap_err();
1221        assert!(matches!(err, DataFusionError::Internal(msg) if msg.contains("call 1")));
1222    }
1223}