-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
Add type coercion for UDFs in logical plan #3254
Merged
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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 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 |
---|---|---|
|
@@ -23,9 +23,10 @@ use datafusion_expr::binary_rule::coerce_types; | |
use datafusion_expr::expr_rewriter::{ExprRewritable, ExprRewriter, RewriteRecursion}; | ||
use datafusion_expr::logical_plan::builder::build_join_schema; | ||
use datafusion_expr::logical_plan::JoinType; | ||
use datafusion_expr::type_coercion::data_types; | ||
use datafusion_expr::utils::from_plan; | ||
use datafusion_expr::ExprSchemable; | ||
use datafusion_expr::{Expr, LogicalPlan}; | ||
use datafusion_expr::{ExprSchemable, Signature}; | ||
|
||
#[derive(Default)] | ||
pub struct TypeCoercion {} | ||
|
@@ -96,18 +97,61 @@ impl ExprRewriter for TypeCoercionRewriter { | |
right: Box::new(right.cast_to(&coerced_type, &self.schema)?), | ||
}) | ||
} | ||
Expr::ScalarUDF { fun, args } => { | ||
let new_expr = coerce_arguments_for_signature( | ||
args.as_slice(), | ||
&self.schema, | ||
&fun.signature, | ||
)?; | ||
Ok(Expr::ScalarUDF { | ||
fun, | ||
args: new_expr, | ||
}) | ||
} | ||
expr => Ok(expr), | ||
} | ||
} | ||
} | ||
|
||
/// Returns `expressions` coerced to types compatible with | ||
/// `signature`, if possible. | ||
/// | ||
/// See the module level documentation for more detail on coercion. | ||
pub fn coerce_arguments_for_signature( | ||
expressions: &[Expr], | ||
schema: &DFSchema, | ||
signature: &Signature, | ||
) -> Result<Vec<Expr>> { | ||
if expressions.is_empty() { | ||
return Ok(vec![]); | ||
} | ||
|
||
let current_types = expressions | ||
.iter() | ||
.map(|e| e.get_type(schema)) | ||
.collect::<Result<Vec<_>>>()?; | ||
|
||
let new_types = data_types(¤t_types, signature)?; | ||
|
||
expressions | ||
.iter() | ||
.enumerate() | ||
.map(|(i, expr)| expr.clone().cast_to(&new_types[i], schema)) | ||
.collect::<Result<Vec<_>>>() | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
use crate::type_coercion::TypeCoercion; | ||
use crate::{OptimizerConfig, OptimizerRule}; | ||
use arrow::datatypes::DataType; | ||
use datafusion_common::{DFSchema, Result}; | ||
use datafusion_expr::logical_plan::{EmptyRelation, Projection}; | ||
use datafusion_expr::{lit, LogicalPlan}; | ||
use datafusion_expr::{ | ||
lit, | ||
logical_plan::{EmptyRelation, Projection}, | ||
Expr, LogicalPlan, ReturnTypeFunction, ScalarFunctionImplementation, ScalarUDF, | ||
Signature, Volatility, | ||
}; | ||
use std::sync::Arc; | ||
|
||
#[test] | ||
|
@@ -147,4 +191,63 @@ mod test { | |
\n EmptyRelation", &format!("{:?}", plan)); | ||
Ok(()) | ||
} | ||
|
||
#[test] | ||
fn scalar_udf() -> Result<()> { | ||
let empty = empty(); | ||
let return_type: ReturnTypeFunction = | ||
Arc::new(move |_| Ok(Arc::new(DataType::Utf8))); | ||
let fun: ScalarFunctionImplementation = Arc::new(move |_| unimplemented!()); | ||
let udf = Expr::ScalarUDF { | ||
fun: Arc::new(ScalarUDF::new( | ||
"TestScalarUDF", | ||
&Signature::uniform(1, vec![DataType::Float32], Volatility::Stable), | ||
&return_type, | ||
&fun, | ||
)), | ||
args: vec![lit(123_i32)], | ||
}; | ||
let plan = LogicalPlan::Projection(Projection::try_new(vec![udf], empty, None)?); | ||
let rule = TypeCoercion::new(); | ||
let mut config = OptimizerConfig::default(); | ||
let plan = rule.optimize(&plan, &mut config)?; | ||
assert_eq!( | ||
"Projection: TestScalarUDF(CAST(Int32(123) AS Float32))\n EmptyRelation", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
&format!("{:?}", plan) | ||
); | ||
Ok(()) | ||
} | ||
|
||
#[test] | ||
fn scalar_udf_invalid_input() -> Result<()> { | ||
let empty = empty(); | ||
let return_type: ReturnTypeFunction = | ||
Arc::new(move |_| Ok(Arc::new(DataType::Utf8))); | ||
let fun: ScalarFunctionImplementation = Arc::new(move |_| unimplemented!()); | ||
let udf = Expr::ScalarUDF { | ||
fun: Arc::new(ScalarUDF::new( | ||
"TestScalarUDF", | ||
&Signature::uniform(1, vec![DataType::Int32], Volatility::Stable), | ||
&return_type, | ||
&fun, | ||
)), | ||
args: vec![lit("Apple")], | ||
}; | ||
let plan = LogicalPlan::Projection(Projection::try_new(vec![udf], empty, None)?); | ||
let rule = TypeCoercion::new(); | ||
let mut config = OptimizerConfig::default(); | ||
let plan = rule.optimize(&plan, &mut config).err().unwrap(); | ||
assert_eq!( | ||
"Plan(\"Coercion from [Utf8] to the signature Uniform(1, [Int32]) failed.\")", | ||
&format!("{:?}", plan) | ||
); | ||
Ok(()) | ||
} | ||
|
||
fn empty() -> Arc<LogicalPlan> { | ||
Arc::new(LogicalPlan::EmptyRelation(EmptyRelation { | ||
produce_one_row: false, | ||
schema: Arc::new(DFSchema::empty()), | ||
})) | ||
} | ||
} |
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.
I feel like this code should already exist somewhere and it would be great to consolidate into a single implementation rather than have multiple implementations around
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.
Yes, this is adapted from the
coerce
method in thephysical-expr
crate that operates on physical expressions rather than logical expressions.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.
Do we need to public this method?
I think it's better to make it private.