-
Notifications
You must be signed in to change notification settings - Fork 2k
feat: add cast_to_type UDF for type-based casting #21322
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
7fc781f
feat: add cast_to_type UDF for type-based casting
adriangb 421be8e
feat: add try_cast_to_type UDF (fallible variant)
adriangb 7013469
chore: regenerate scalar_functions.md docs
adriangb 7891a1f
fix: cast_to_type nullability should only depend on the first argument
adriangb 09147ea
Update datafusion/functions/src/core/cast_to_type.rs
adriangb 954e029
update tests
adriangb 06b93b0
Update datafusion/functions/src/core/cast_to_type.rs
adriangb 2a4bdd7
Update docs/source/user-guide/sql/scalar_functions.md
adriangb be6aabf
Update docs/source/user-guide/sql/scalar_functions.md
adriangb bcc40d0
Update datafusion/functions/src/core/try_cast_to_type.rs
adriangb 1007af6
Update datafusion/functions/src/core/cast_to_type.rs
adriangb 8f896dc
Update datafusion/functions/src/core/try_cast_to_type.rs
adriangb bcfd87f
get rid of `pop().unwrap()`s
adriangb 0da8d3e
clean up data_type_from_args()
adriangb be67a29
rename
adriangb 38de438
whitespace
adriangb 717d51b
update
adriangb 08b7edb
Add error message regex and invalid type test for cast_to_type
adriangb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| //! [`CastToTypeFunc`]: Implementation of the `cast_to_type` function | ||
|
|
||
| use arrow::datatypes::{DataType, Field, FieldRef}; | ||
| use datafusion_common::{Result, internal_err, utils::take_function_args}; | ||
| use datafusion_expr::simplify::{ExprSimplifyResult, SimplifyContext}; | ||
| use datafusion_expr::{ | ||
| Coercion, ColumnarValue, Documentation, Expr, ReturnFieldArgs, ScalarFunctionArgs, | ||
| ScalarUDFImpl, Signature, TypeSignatureClass, Volatility, | ||
| }; | ||
| use datafusion_macros::user_doc; | ||
|
|
||
| /// 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. | ||
| /// This is useful in macros or generic SQL where you need to preserve | ||
| /// or match types dynamically. | ||
| /// | ||
| /// For example: | ||
| /// ```sql | ||
| /// select cast_to_type('42', NULL::INTEGER); | ||
| /// ``` | ||
| #[user_doc( | ||
| doc_section(label = "Other Functions"), | ||
| 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.", | ||
| syntax_example = "cast_to_type(expression, reference)", | ||
| sql_example = r#"```sql | ||
| > select cast_to_type('42', NULL::INTEGER) as a; | ||
| +----+ | ||
| | a | | ||
| +----+ | ||
| | 42 | | ||
| +----+ | ||
|
|
||
| > select cast_to_type(1 + 2, NULL::DOUBLE) as b; | ||
| +-----+ | ||
| | b | | ||
| +-----+ | ||
| | 3.0 | | ||
| +-----+ | ||
| ```"#, | ||
| argument( | ||
| name = "expression", | ||
| description = "The expression to cast. It can be a constant, column, or function, and any combination of operators." | ||
| ), | ||
| argument( | ||
| name = "reference", | ||
| description = "Reference expression whose data type determines the target cast type. The value is ignored." | ||
| ) | ||
| )] | ||
| #[derive(Debug, PartialEq, Eq, Hash)] | ||
| pub struct CastToTypeFunc { | ||
| signature: Signature, | ||
| } | ||
|
|
||
| impl Default for CastToTypeFunc { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| impl CastToTypeFunc { | ||
| pub fn new() -> Self { | ||
| Self { | ||
| signature: Signature::coercible( | ||
| vec![ | ||
| Coercion::new_exact(TypeSignatureClass::Any), | ||
| Coercion::new_exact(TypeSignatureClass::Any), | ||
| ], | ||
| Volatility::Immutable, | ||
| ), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl ScalarUDFImpl for CastToTypeFunc { | ||
| fn name(&self) -> &str { | ||
| "cast_to_type" | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { | ||
| internal_err!("return_field_from_args should be called instead") | ||
| } | ||
|
|
||
| fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { | ||
| let [source_field, reference_field] = | ||
| take_function_args(self.name(), args.arg_fields)?; | ||
| let target_type = reference_field.data_type().clone(); | ||
| // Nullability is inherited only from the first argument (the value | ||
| // being cast). The second argument is used solely for its type, so | ||
| // its own nullability is irrelevant. The one exception is when the | ||
| // target type is Null – that type is inherently nullable. | ||
| let nullable = source_field.is_nullable() || target_type == DataType::Null; | ||
| Ok(Field::new(self.name(), target_type, nullable).into()) | ||
| } | ||
|
|
||
| fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> { | ||
| internal_err!("cast_to_type should have been simplified to cast") | ||
| } | ||
|
|
||
| fn simplify( | ||
| &self, | ||
| args: Vec<Expr>, | ||
| info: &SimplifyContext, | ||
| ) -> Result<ExprSimplifyResult> { | ||
| let [source_arg, type_arg] = take_function_args(self.name(), args)?; | ||
| let target_type = info.get_data_type(&type_arg)?; | ||
| let source_type = info.get_data_type(&source_arg)?; | ||
| let new_expr = if source_type == target_type { | ||
| // the argument's data type is already the correct type | ||
| source_arg | ||
| } else { | ||
| let nullable = info.nullable(&source_arg)? || target_type == DataType::Null; | ||
| // Use an actual cast to get the correct type | ||
| Expr::Cast(datafusion_expr::Cast { | ||
| expr: Box::new(source_arg), | ||
| field: Field::new("", target_type, nullable).into(), | ||
| }) | ||
| }; | ||
| Ok(ExprSimplifyResult::Simplified(new_expr)) | ||
| } | ||
|
|
||
| fn documentation(&self) -> Option<&Documentation> { | ||
| self.doc() | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@adriangb This piece will drop extension metadata from the
totype. Was this intentional?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The actual implementation does as well, #21322 (comment)
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm...I thought the logical cast errored when converted to a physical expression but preserved metadata after #18136 . I will also try to fix in #21071 since it will make a whole lot more sense what a cast to an extension type should actually do in that case 🙂