|
| 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 | + |
| 18 | +//! [`ArrowTryCastFunc`]: Implementation of the `arrow_try_cast` |
| 19 | +
|
| 20 | +use arrow::datatypes::{DataType, Field, FieldRef}; |
| 21 | +use arrow::error::ArrowError; |
| 22 | +use datafusion_common::{ |
| 23 | + Result, arrow_datafusion_err, datatype::DataTypeExt, exec_datafusion_err, exec_err, |
| 24 | + internal_err, types::logical_string, utils::take_function_args, |
| 25 | +}; |
| 26 | +use std::any::Any; |
| 27 | + |
| 28 | +use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext}; |
| 29 | +use datafusion_expr::{ |
| 30 | + Coercion, ColumnarValue, Documentation, Expr, ReturnFieldArgs, ScalarFunctionArgs, |
| 31 | + ScalarUDFImpl, Signature, TypeSignatureClass, Volatility, |
| 32 | +}; |
| 33 | +use datafusion_macros::user_doc; |
| 34 | + |
| 35 | +use super::arrow_cast::data_type_from_args; |
| 36 | + |
| 37 | +/// Like [`arrow_cast`] but returns NULL on cast failure instead of erroring. |
| 38 | +/// |
| 39 | +/// This is implemented by simplifying `arrow_try_cast(expr, 'Type')` into |
| 40 | +/// `Expr::TryCast` during optimization. |
| 41 | +#[user_doc( |
| 42 | + doc_section(label = "Other Functions"), |
| 43 | + description = "Casts a value to a specific Arrow data type, returning NULL if the cast fails.", |
| 44 | + syntax_example = "arrow_try_cast(expression, datatype)", |
| 45 | + sql_example = r#"```sql |
| 46 | +> select arrow_try_cast('123', 'Int64') as a, |
| 47 | + arrow_try_cast('not_a_number', 'Int64') as b; |
| 48 | +
|
| 49 | ++-----+------+ |
| 50 | +| a | b | |
| 51 | ++-----+------+ |
| 52 | +| 123 | NULL | |
| 53 | ++-----+------+ |
| 54 | +```"#, |
| 55 | + argument( |
| 56 | + name = "expression", |
| 57 | + description = "Expression to cast. The expression can be a constant, column, or function, and any combination of operators." |
| 58 | + ), |
| 59 | + argument( |
| 60 | + name = "datatype", |
| 61 | + description = "[Arrow data type](https://docs.rs/arrow/latest/arrow/datatypes/enum.DataType.html) name to cast to, as a string. The format is the same as that returned by [`arrow_typeof`]" |
| 62 | + ) |
| 63 | +)] |
| 64 | +#[derive(Debug, PartialEq, Eq, Hash)] |
| 65 | +pub struct ArrowTryCastFunc { |
| 66 | + signature: Signature, |
| 67 | +} |
| 68 | + |
| 69 | +impl Default for ArrowTryCastFunc { |
| 70 | + fn default() -> Self { |
| 71 | + Self::new() |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +impl ArrowTryCastFunc { |
| 76 | + pub fn new() -> Self { |
| 77 | + Self { |
| 78 | + signature: Signature::coercible( |
| 79 | + vec![ |
| 80 | + Coercion::new_exact(TypeSignatureClass::Any), |
| 81 | + Coercion::new_exact(TypeSignatureClass::Native(logical_string())), |
| 82 | + ], |
| 83 | + Volatility::Immutable, |
| 84 | + ), |
| 85 | + } |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +impl ScalarUDFImpl for ArrowTryCastFunc { |
| 90 | + fn as_any(&self) -> &dyn Any { |
| 91 | + self |
| 92 | + } |
| 93 | + |
| 94 | + fn name(&self) -> &str { |
| 95 | + "arrow_try_cast" |
| 96 | + } |
| 97 | + |
| 98 | + fn signature(&self) -> &Signature { |
| 99 | + &self.signature |
| 100 | + } |
| 101 | + |
| 102 | + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { |
| 103 | + internal_err!("return_field_from_args should be called instead") |
| 104 | + } |
| 105 | + |
| 106 | + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { |
| 107 | + // TryCast can always return NULL (on cast failure), so always nullable |
| 108 | + let [_, type_arg] = take_function_args(self.name(), args.scalar_arguments)?; |
| 109 | + |
| 110 | + type_arg |
| 111 | + .and_then(|sv| sv.try_as_str().flatten().filter(|s| !s.is_empty())) |
| 112 | + .map_or_else( |
| 113 | + || { |
| 114 | + exec_err!( |
| 115 | + "{} requires its second argument to be a non-empty constant string", |
| 116 | + self.name() |
| 117 | + ) |
| 118 | + }, |
| 119 | + |casted_type| match casted_type.parse::<DataType>() { |
| 120 | + Ok(data_type) => { |
| 121 | + Ok(Field::new(self.name(), data_type, true).into()) |
| 122 | + } |
| 123 | + Err(ArrowError::ParseError(e)) => Err(exec_datafusion_err!("{e}")), |
| 124 | + Err(e) => Err(arrow_datafusion_err!(e)), |
| 125 | + }, |
| 126 | + ) |
| 127 | + } |
| 128 | + |
| 129 | + fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> { |
| 130 | + internal_err!("arrow_try_cast should have been simplified to try_cast") |
| 131 | + } |
| 132 | + |
| 133 | + fn simplify( |
| 134 | + &self, |
| 135 | + mut args: Vec<Expr>, |
| 136 | + info: &SimplifyContext, |
| 137 | + ) -> Result<ExprSimplifyResult> { |
| 138 | + let target_type = data_type_from_args(self.name(), &args)?; |
| 139 | + // remove second (type) argument |
| 140 | + args.pop().unwrap(); |
| 141 | + let arg = args.pop().unwrap(); |
| 142 | + |
| 143 | + let source_type = info.get_data_type(&arg)?; |
| 144 | + let new_expr = if source_type == target_type { |
| 145 | + arg |
| 146 | + } else { |
| 147 | + Expr::TryCast(datafusion_expr::TryCast { |
| 148 | + expr: Box::new(arg), |
| 149 | + field: target_type.into_nullable_field_ref(), |
| 150 | + }) |
| 151 | + }; |
| 152 | + Ok(ExprSimplifyResult::Simplified(new_expr)) |
| 153 | + } |
| 154 | + |
| 155 | + fn documentation(&self) -> Option<&Documentation> { |
| 156 | + self.doc() |
| 157 | + } |
| 158 | +} |
0 commit comments