Skip to main content

datafusion_physical_expr/expressions/
try_cast.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt;
19use std::hash::Hash;
20use std::sync::Arc;
21
22use crate::PhysicalExpr;
23use arrow::compute;
24use arrow::compute::CastOptions;
25use arrow::datatypes::{DataType, FieldRef, Schema};
26use arrow::record_batch::RecordBatch;
27use compute::can_cast_types;
28use datafusion_common::format::DEFAULT_FORMAT_OPTIONS;
29use datafusion_common::{Result, not_impl_err};
30use datafusion_expr::ColumnarValue;
31
32/// TRY_CAST expression casts an expression to a specific data type and returns NULL on invalid cast
33#[derive(Debug, Eq)]
34pub struct TryCastExpr {
35    /// The expression to cast
36    expr: Arc<dyn PhysicalExpr>,
37    /// The data type to cast to
38    cast_type: DataType,
39}
40
41// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
42impl PartialEq for TryCastExpr {
43    fn eq(&self, other: &Self) -> bool {
44        self.expr.eq(&other.expr) && self.cast_type == other.cast_type
45    }
46}
47
48impl Hash for TryCastExpr {
49    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
50        self.expr.hash(state);
51        self.cast_type.hash(state);
52    }
53}
54
55impl TryCastExpr {
56    /// Create a new CastExpr
57    pub fn new(expr: Arc<dyn PhysicalExpr>, cast_type: DataType) -> Self {
58        Self { expr, cast_type }
59    }
60
61    /// The expression to cast
62    pub fn expr(&self) -> &Arc<dyn PhysicalExpr> {
63        &self.expr
64    }
65
66    /// The data type to cast to
67    pub fn cast_type(&self) -> &DataType {
68        &self.cast_type
69    }
70}
71
72impl fmt::Display for TryCastExpr {
73    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74        write!(f, "TRY_CAST({} AS {})", self.expr, self.cast_type)
75    }
76}
77
78impl PhysicalExpr for TryCastExpr {
79    fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
80        Ok(self.cast_type.clone())
81    }
82
83    fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
84        Ok(true)
85    }
86
87    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
88        let value = self.expr.evaluate(batch)?;
89        let options = CastOptions {
90            safe: true,
91            format_options: DEFAULT_FORMAT_OPTIONS,
92        };
93        value.cast_to(&self.cast_type, Some(&options))
94    }
95
96    fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> {
97        self.expr
98            .return_field(input_schema)
99            .map(|f| f.as_ref().clone().with_data_type(self.cast_type.clone()))
100            .map(Arc::new)
101    }
102
103    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
104        vec![&self.expr]
105    }
106
107    fn with_new_children(
108        self: Arc<Self>,
109        children: Vec<Arc<dyn PhysicalExpr>>,
110    ) -> Result<Arc<dyn PhysicalExpr>> {
111        Ok(Arc::new(TryCastExpr::new(
112            Arc::clone(&children[0]),
113            self.cast_type.clone(),
114        )))
115    }
116
117    fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        write!(f, "TRY_CAST(")?;
119        self.expr.fmt_sql(f)?;
120        write!(f, " AS {:?})", self.cast_type)
121    }
122}
123
124/// Return a PhysicalExpression representing `expr` casted to
125/// `cast_type`, if any casting is needed.
126///
127/// Note that such casts may lose type information
128pub fn try_cast(
129    expr: Arc<dyn PhysicalExpr>,
130    input_schema: &Schema,
131    cast_type: DataType,
132) -> Result<Arc<dyn PhysicalExpr>> {
133    let expr_type = expr.data_type(input_schema)?;
134    if expr_type == cast_type {
135        Ok(Arc::clone(&expr))
136    } else if can_cast_types(&expr_type, &cast_type) {
137        Ok(Arc::new(TryCastExpr::new(expr, cast_type)))
138    } else {
139        not_impl_err!("Unsupported TRY_CAST from {expr_type} to {cast_type}")
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146    use crate::expressions::col;
147    use arrow::array::{
148        Decimal128Array, Decimal128Builder, StringArray, Time64NanosecondArray,
149    };
150    use arrow::{
151        array::{
152            Array, Float32Array, Float64Array, Int8Array, Int16Array, Int32Array,
153            Int64Array, TimestampNanosecondArray, UInt32Array,
154        },
155        datatypes::*,
156    };
157    use datafusion_physical_expr_common::physical_expr::fmt_sql;
158
159    // runs an end-to-end test of physical type cast
160    // 1. construct a record batch with a column "a" of type A
161    // 2. construct a physical expression of TRY_CAST(a AS B)
162    // 3. evaluate the expression
163    // 4. verify that the resulting expression is of type B
164    // 5. verify that the resulting values are downcastable and correct
165    macro_rules! generic_decimal_to_other_test_cast {
166        ($DECIMAL_ARRAY:ident, $A_TYPE:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr) => {{
167            let schema = Schema::new(vec![Field::new("a", $A_TYPE, true)]);
168            let batch = RecordBatch::try_new(
169                Arc::new(schema.clone()),
170                vec![Arc::new($DECIMAL_ARRAY)],
171            )?;
172            // verify that we can construct the expression
173            let expression = try_cast(col("a", &schema)?, &schema, $TYPE)?;
174
175            // verify that its display is correct
176            assert_eq!(
177                format!("TRY_CAST(a@0 AS {})", $TYPE),
178                format!("{}", expression)
179            );
180
181            // verify that the expression's type is correct
182            assert_eq!(expression.data_type(&schema)?, $TYPE);
183
184            // compute
185            let result = expression
186                .evaluate(&batch)?
187                .into_array(batch.num_rows())
188                .expect("Failed to convert to array");
189
190            // verify that the array's data_type is correct
191            assert_eq!(*result.data_type(), $TYPE);
192
193            // verify that the data itself is downcastable
194            let result = result
195                .as_any()
196                .downcast_ref::<$TYPEARRAY>()
197                .expect("failed to downcast");
198
199            // verify that the result itself is correct
200            for (i, x) in $VEC.iter().enumerate() {
201                match x {
202                    Some(x) => assert_eq!(result.value(i), *x),
203                    None => assert!(result.is_null(i)),
204                }
205            }
206        }};
207    }
208
209    // runs an end-to-end test of physical type cast
210    // 1. construct a record batch with a column "a" of type A
211    // 2. construct a physical expression of TRY_CAST(a AS B)
212    // 3. evaluate the expression
213    // 4. verify that the resulting expression is of type B
214    // 5. verify that the resulting values are downcastable and correct
215    macro_rules! generic_test_cast {
216        ($A_ARRAY:ident, $A_TYPE:expr, $A_VEC:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr) => {{
217            let schema = Schema::new(vec![Field::new("a", $A_TYPE, true)]);
218            let a_vec_len = $A_VEC.len();
219            let a = $A_ARRAY::from($A_VEC);
220            let batch =
221                RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;
222
223            // verify that we can construct the expression
224            let expression = try_cast(col("a", &schema)?, &schema, $TYPE)?;
225
226            // verify that its display is correct
227            assert_eq!(
228                format!("TRY_CAST(a@0 AS {})", $TYPE),
229                format!("{}", expression)
230            );
231
232            // verify that the expression's type is correct
233            assert_eq!(expression.data_type(&schema)?, $TYPE);
234
235            // compute
236            let result = expression
237                .evaluate(&batch)?
238                .into_array(batch.num_rows())
239                .expect("Failed to convert to array");
240
241            // verify that the array's data_type is correct
242            assert_eq!(*result.data_type(), $TYPE);
243
244            // verify that the len is correct
245            assert_eq!(result.len(), a_vec_len);
246
247            // verify that the data itself is downcastable
248            let result = result
249                .as_any()
250                .downcast_ref::<$TYPEARRAY>()
251                .expect("failed to downcast");
252
253            // verify that the result itself is correct
254            for (i, x) in $VEC.iter().enumerate() {
255                match x {
256                    Some(x) => assert_eq!(result.value(i), *x),
257                    None => assert!(result.is_null(i)),
258                }
259            }
260        }};
261    }
262
263    #[test]
264    fn test_try_cast_decimal_to_decimal() -> Result<()> {
265        // try cast one decimal data type to another decimal data type
266        let array: Vec<i128> = vec![1234, 2222, 3, 4000, 5000];
267        let decimal_array = create_decimal_array(&array, 10, 3);
268        generic_decimal_to_other_test_cast!(
269            decimal_array,
270            DataType::Decimal128(10, 3),
271            Decimal128Array,
272            DataType::Decimal128(20, 6),
273            [
274                Some(1_234_000),
275                Some(2_222_000),
276                Some(3_000),
277                Some(4_000_000),
278                Some(5_000_000),
279                None
280            ]
281        );
282
283        let decimal_array = create_decimal_array(&array, 10, 3);
284        generic_decimal_to_other_test_cast!(
285            decimal_array,
286            DataType::Decimal128(10, 3),
287            Decimal128Array,
288            DataType::Decimal128(10, 2),
289            [Some(123), Some(222), Some(0), Some(400), Some(500), None]
290        );
291
292        Ok(())
293    }
294
295    #[test]
296    fn test_try_cast_decimal_to_numeric() -> Result<()> {
297        // TODO we should add function to create Decimal128Array with value and metadata
298        // https://github.com/apache/arrow-rs/issues/1009
299        let array: Vec<i128> = vec![1, 2, 3, 4, 5];
300        let decimal_array = create_decimal_array(&array, 10, 0);
301        // decimal to i8
302        generic_decimal_to_other_test_cast!(
303            decimal_array,
304            DataType::Decimal128(10, 0),
305            Int8Array,
306            DataType::Int8,
307            [
308                Some(1_i8),
309                Some(2_i8),
310                Some(3_i8),
311                Some(4_i8),
312                Some(5_i8),
313                None
314            ]
315        );
316
317        // decimal to i16
318        let decimal_array = create_decimal_array(&array, 10, 0);
319        generic_decimal_to_other_test_cast!(
320            decimal_array,
321            DataType::Decimal128(10, 0),
322            Int16Array,
323            DataType::Int16,
324            [
325                Some(1_i16),
326                Some(2_i16),
327                Some(3_i16),
328                Some(4_i16),
329                Some(5_i16),
330                None
331            ]
332        );
333
334        // decimal to i32
335        let decimal_array = create_decimal_array(&array, 10, 0);
336        generic_decimal_to_other_test_cast!(
337            decimal_array,
338            DataType::Decimal128(10, 0),
339            Int32Array,
340            DataType::Int32,
341            [
342                Some(1_i32),
343                Some(2_i32),
344                Some(3_i32),
345                Some(4_i32),
346                Some(5_i32),
347                None
348            ]
349        );
350
351        // decimal to i64
352        let decimal_array = create_decimal_array(&array, 10, 0);
353        generic_decimal_to_other_test_cast!(
354            decimal_array,
355            DataType::Decimal128(10, 0),
356            Int64Array,
357            DataType::Int64,
358            [
359                Some(1_i64),
360                Some(2_i64),
361                Some(3_i64),
362                Some(4_i64),
363                Some(5_i64),
364                None
365            ]
366        );
367
368        // decimal to float32
369        let array: Vec<i128> = vec![1234, 2222, 3, 4000, 5000];
370        let decimal_array = create_decimal_array(&array, 10, 3);
371        generic_decimal_to_other_test_cast!(
372            decimal_array,
373            DataType::Decimal128(10, 3),
374            Float32Array,
375            DataType::Float32,
376            [
377                Some(1.234_f32),
378                Some(2.222_f32),
379                Some(0.003_f32),
380                Some(4.0_f32),
381                Some(5.0_f32),
382                None
383            ]
384        );
385        // decimal to float64
386        let decimal_array = create_decimal_array(&array, 20, 6);
387        generic_decimal_to_other_test_cast!(
388            decimal_array,
389            DataType::Decimal128(20, 6),
390            Float64Array,
391            DataType::Float64,
392            [
393                Some(0.001234_f64),
394                Some(0.002222_f64),
395                Some(0.000003_f64),
396                Some(0.004_f64),
397                Some(0.005_f64),
398                None
399            ]
400        );
401
402        Ok(())
403    }
404
405    #[test]
406    fn test_try_cast_numeric_to_decimal() -> Result<()> {
407        // int8
408        generic_test_cast!(
409            Int8Array,
410            DataType::Int8,
411            vec![1, 2, 3, 4, 5],
412            Decimal128Array,
413            DataType::Decimal128(3, 0),
414            [Some(1), Some(2), Some(3), Some(4), Some(5)]
415        );
416
417        // int16
418        generic_test_cast!(
419            Int16Array,
420            DataType::Int16,
421            vec![1, 2, 3, 4, 5],
422            Decimal128Array,
423            DataType::Decimal128(5, 0),
424            [Some(1), Some(2), Some(3), Some(4), Some(5)]
425        );
426
427        // int32
428        generic_test_cast!(
429            Int32Array,
430            DataType::Int32,
431            vec![1, 2, 3, 4, 5],
432            Decimal128Array,
433            DataType::Decimal128(10, 0),
434            [Some(1), Some(2), Some(3), Some(4), Some(5)]
435        );
436
437        // int64
438        generic_test_cast!(
439            Int64Array,
440            DataType::Int64,
441            vec![1, 2, 3, 4, 5],
442            Decimal128Array,
443            DataType::Decimal128(20, 0),
444            [Some(1), Some(2), Some(3), Some(4), Some(5)]
445        );
446
447        // int64 to different scale
448        generic_test_cast!(
449            Int64Array,
450            DataType::Int64,
451            vec![1, 2, 3, 4, 5],
452            Decimal128Array,
453            DataType::Decimal128(20, 2),
454            [Some(100), Some(200), Some(300), Some(400), Some(500)]
455        );
456
457        // float32
458        generic_test_cast!(
459            Float32Array,
460            DataType::Float32,
461            vec![1.5, 2.5, 3.0, 1.123_456_8, 5.50],
462            Decimal128Array,
463            DataType::Decimal128(10, 2),
464            [Some(150), Some(250), Some(300), Some(112), Some(550)]
465        );
466
467        // float64
468        generic_test_cast!(
469            Float64Array,
470            DataType::Float64,
471            vec![1.5, 2.5, 3.0, 1.123_456_8, 5.50],
472            Decimal128Array,
473            DataType::Decimal128(20, 4),
474            [
475                Some(15000),
476                Some(25000),
477                Some(30000),
478                Some(11235),
479                Some(55000)
480            ]
481        );
482        Ok(())
483    }
484
485    #[test]
486    fn test_cast_i32_u32() -> Result<()> {
487        generic_test_cast!(
488            Int32Array,
489            DataType::Int32,
490            vec![1, 2, 3, 4, 5],
491            UInt32Array,
492            DataType::UInt32,
493            [
494                Some(1_u32),
495                Some(2_u32),
496                Some(3_u32),
497                Some(4_u32),
498                Some(5_u32)
499            ]
500        );
501        Ok(())
502    }
503
504    #[test]
505    fn test_cast_i32_utf8() -> Result<()> {
506        generic_test_cast!(
507            Int32Array,
508            DataType::Int32,
509            vec![1, 2, 3, 4, 5],
510            StringArray,
511            DataType::Utf8,
512            [Some("1"), Some("2"), Some("3"), Some("4"), Some("5")]
513        );
514        Ok(())
515    }
516
517    #[test]
518    fn test_try_cast_utf8_i32() -> Result<()> {
519        generic_test_cast!(
520            StringArray,
521            DataType::Utf8,
522            vec!["a", "2", "3", "b", "5"],
523            Int32Array,
524            DataType::Int32,
525            [None, Some(2), Some(3), None, Some(5)]
526        );
527        Ok(())
528    }
529
530    #[test]
531    fn test_cast_i64_t64() -> Result<()> {
532        let original = vec![1, 2, 3, 4, 5];
533        let expected: Vec<Option<i64>> = original
534            .iter()
535            .map(|i| Some(Time64NanosecondArray::from(vec![*i]).value(0)))
536            .collect();
537        generic_test_cast!(
538            Int64Array,
539            DataType::Int64,
540            original,
541            TimestampNanosecondArray,
542            DataType::Timestamp(TimeUnit::Nanosecond, None),
543            expected
544        );
545        Ok(())
546    }
547
548    #[test]
549    fn invalid_cast() {
550        // Ensure a useful error happens at plan time if invalid casts are used
551        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
552
553        let result = try_cast(
554            col("a", &schema).unwrap(),
555            &schema,
556            DataType::Interval(IntervalUnit::MonthDayNano),
557        );
558        result.expect_err("expected Invalid TRY_CAST");
559    }
560
561    // create decimal array with the specified precision and scale
562    fn create_decimal_array(array: &[i128], precision: u8, scale: i8) -> Decimal128Array {
563        let mut decimal_builder = Decimal128Builder::with_capacity(array.len());
564        for value in array {
565            decimal_builder.append_value(*value);
566        }
567        decimal_builder.append_null();
568        decimal_builder
569            .finish()
570            .with_precision_and_scale(precision, scale)
571            .unwrap()
572    }
573
574    #[test]
575    fn test_fmt_sql() -> Result<()> {
576        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
577
578        // Test numeric casting
579        let expr = try_cast(col("a", &schema)?, &schema, DataType::Int64)?;
580        let display_string = expr.to_string();
581        assert_eq!(display_string, "TRY_CAST(a@0 AS Int64)");
582        let sql_string = fmt_sql(expr.as_ref()).to_string();
583        assert_eq!(sql_string, "TRY_CAST(a AS Int64)");
584
585        // Test string casting
586        let schema = Schema::new(vec![Field::new("b", DataType::Utf8, true)]);
587        let expr = try_cast(col("b", &schema)?, &schema, DataType::Int32)?;
588        let display_string = expr.to_string();
589        assert_eq!(display_string, "TRY_CAST(b@0 AS Int32)");
590        let sql_string = fmt_sql(expr.as_ref()).to_string();
591        assert_eq!(sql_string, "TRY_CAST(b AS Int32)");
592
593        Ok(())
594    }
595}