|
| 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 | +//! [`CastToTypeFunc`]: Implementation of the `cast_to_type` function |
| 19 | +
|
| 20 | +use arrow::datatypes::{DataType, Field, FieldRef}; |
| 21 | +use datafusion_common::{Result, internal_err, utils::take_function_args}; |
| 22 | +use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext}; |
| 23 | +use datafusion_expr::{ |
| 24 | + Coercion, ColumnarValue, Documentation, Expr, ReturnFieldArgs, ScalarFunctionArgs, |
| 25 | + ScalarUDFImpl, Signature, TypeSignatureClass, Volatility, |
| 26 | +}; |
| 27 | +use datafusion_macros::user_doc; |
| 28 | + |
| 29 | +/// Casts the first argument to the data type of the second argument. |
| 30 | +/// |
| 31 | +/// Only the type of the second argument is used; its value is ignored. |
| 32 | +/// This is useful in macros or generic SQL where you need to preserve |
| 33 | +/// or match types dynamically. |
| 34 | +/// |
| 35 | +/// For example: |
| 36 | +/// ```sql |
| 37 | +/// select cast_to_type('42', NULL::INTEGER); |
| 38 | +/// ``` |
| 39 | +#[user_doc( |
| 40 | + doc_section(label = "Other Functions"), |
| 41 | + description = "Casts the first argument to the data type of the second argument. Only the type of the second argument is used; its value is ignored.", |
| 42 | + syntax_example = "cast_to_type(expression, reference)", |
| 43 | + sql_example = r#"```sql |
| 44 | +> select cast_to_type('42', NULL::INTEGER) as a; |
| 45 | ++----+ |
| 46 | +| a | |
| 47 | ++----+ |
| 48 | +| 42 | |
| 49 | ++----+ |
| 50 | +
|
| 51 | +> select cast_to_type(1 + 2, NULL::DOUBLE) as b; |
| 52 | ++-----+ |
| 53 | +| b | |
| 54 | ++-----+ |
| 55 | +| 3.0 | |
| 56 | ++-----+ |
| 57 | +```"#, |
| 58 | + argument( |
| 59 | + name = "expression", |
| 60 | + description = "The expression to cast. It can be a constant, column, or function, and any combination of operators." |
| 61 | + ), |
| 62 | + argument( |
| 63 | + name = "reference", |
| 64 | + description = "Reference expression whose data type determines the target cast type. The value is ignored." |
| 65 | + ) |
| 66 | +)] |
| 67 | +#[derive(Debug, PartialEq, Eq, Hash)] |
| 68 | +pub struct CastToTypeFunc { |
| 69 | + signature: Signature, |
| 70 | +} |
| 71 | + |
| 72 | +impl Default for CastToTypeFunc { |
| 73 | + fn default() -> Self { |
| 74 | + Self::new() |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +impl CastToTypeFunc { |
| 79 | + pub fn new() -> Self { |
| 80 | + Self { |
| 81 | + signature: Signature::coercible( |
| 82 | + vec![ |
| 83 | + Coercion::new_exact(TypeSignatureClass::Any), |
| 84 | + Coercion::new_exact(TypeSignatureClass::Any), |
| 85 | + ], |
| 86 | + Volatility::Immutable, |
| 87 | + ), |
| 88 | + } |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +impl ScalarUDFImpl for CastToTypeFunc { |
| 93 | + fn name(&self) -> &str { |
| 94 | + "cast_to_type" |
| 95 | + } |
| 96 | + |
| 97 | + fn signature(&self) -> &Signature { |
| 98 | + &self.signature |
| 99 | + } |
| 100 | + |
| 101 | + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { |
| 102 | + internal_err!("return_field_from_args should be called instead") |
| 103 | + } |
| 104 | + |
| 105 | + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { |
| 106 | + let [source_field, reference_field] = |
| 107 | + take_function_args(self.name(), args.arg_fields)?; |
| 108 | + let target_type = reference_field.data_type().clone(); |
| 109 | + // Nullability is inherited only from the first argument (the value |
| 110 | + // being cast). The second argument is used solely for its type, so |
| 111 | + // its own nullability is irrelevant. The one exception is when the |
| 112 | + // target type is Null – that type is inherently nullable. |
| 113 | + let nullable = source_field.is_nullable() || target_type == DataType::Null; |
| 114 | + Ok(Field::new(self.name(), target_type, nullable).into()) |
| 115 | + } |
| 116 | + |
| 117 | + fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> { |
| 118 | + internal_err!("cast_to_type should have been simplified to cast") |
| 119 | + } |
| 120 | + |
| 121 | + fn simplify( |
| 122 | + &self, |
| 123 | + args: Vec<Expr>, |
| 124 | + info: &SimplifyContext, |
| 125 | + ) -> Result<ExprSimplifyResult> { |
| 126 | + let [source_arg, type_arg] = take_function_args(self.name(), args)?; |
| 127 | + let target_type = info.get_data_type(&type_arg)?; |
| 128 | + let source_type = info.get_data_type(&source_arg)?; |
| 129 | + let new_expr = if source_type == target_type { |
| 130 | + // the argument's data type is already the correct type |
| 131 | + source_arg |
| 132 | + } else { |
| 133 | + let nullable = info.nullable(&source_arg)? || target_type == DataType::Null; |
| 134 | + // Use an actual cast to get the correct type |
| 135 | + Expr::Cast(datafusion_expr::Cast { |
| 136 | + expr: Box::new(source_arg), |
| 137 | + field: Field::new("", target_type, nullable).into(), |
| 138 | + }) |
| 139 | + }; |
| 140 | + Ok(ExprSimplifyResult::Simplified(new_expr)) |
| 141 | + } |
| 142 | + |
| 143 | + fn documentation(&self) -> Option<&Documentation> { |
| 144 | + self.doc() |
| 145 | + } |
| 146 | +} |
0 commit comments