Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ impl OddCounter {
impl SimpleWindowUDF {
fn new(test_state: Arc<TestState>) -> Self {
let signature =
Signature::exact(vec![DataType::Float64], Volatility::Immutable);
Signature::exact(vec![DataType::Int64], Volatility::Immutable);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sample UDF declared it accepted f64's but internally it acted as if input was i64; this was never caught because apparently type coercion wasn't being run on non-aggregate window functions, and the input data was already i64. Nice little fix.

Self {
signature,
test_state: test_state.into(),
Expand Down
2 changes: 1 addition & 1 deletion datafusion/expr/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -953,7 +953,7 @@ impl AggregateFunction {
pub enum WindowFunctionDefinition {
/// A user defined aggregate function
AggregateUDF(Arc<AggregateUDF>),
/// A user defined aggregate function
/// A user defined window function
WindowUDF(Arc<WindowUDF>),
}

Expand Down
265 changes: 68 additions & 197 deletions datafusion/expr/src/expr_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ use crate::expr::{
InSubquery, Placeholder, ScalarFunction, TryCast, Unnest, WindowFunction,
WindowFunctionParams,
};
use crate::type_coercion::functions::fields_with_udf;
use crate::type_coercion::functions::{UDFCoercionExt, fields_with_udf};
use crate::udf::ReturnFieldArgs;
use crate::{LogicalPlan, Projection, Subquery, WindowFunctionDefinition, utils};
use arrow::compute::can_cast_types;
use arrow::datatypes::{DataType, Field};
use arrow::datatypes::{DataType, Field, FieldRef};
use datafusion_common::datatype::FieldExt;
use datafusion_common::metadata::FieldMetadata;
use datafusion_common::{
Expand Down Expand Up @@ -152,43 +152,10 @@ impl ExprSchemable for Expr {
}
}
}
Expr::ScalarFunction(_func) => {
let return_type = self.to_field(schema)?.1.data_type().clone();
Ok(return_type)
}
Expr::WindowFunction(window_function) => self
.data_type_and_nullable_with_window_function(schema, window_function)
.map(|(return_type, _)| return_type),
Expr::AggregateFunction(AggregateFunction {
func,
params: AggregateFunctionParams { args, .. },
}) => {
let fields = args
.iter()
.map(|e| e.to_field(schema).map(|(_, f)| f))
.collect::<Result<Vec<_>>>()?;
let new_fields = fields_with_udf(&fields, func.as_ref())
.map_err(|err| {
let data_types = fields
.iter()
.map(|f| f.data_type().clone())
.collect::<Vec<_>>();
plan_datafusion_err!(
"{} {}",
match err {
DataFusionError::Plan(msg) => msg,
err => err.to_string(),
},
utils::generate_signature_error_msg(
func.name(),
func.signature().clone(),
&data_types
)
)
})?
.into_iter()
.collect::<Vec<_>>();
Ok(func.return_field(&new_fields)?.data_type().clone())
Expr::ScalarFunction(_)
| Expr::WindowFunction(_)
| Expr::AggregateFunction(_) => {
Ok(self.to_field(schema)?.1.data_type().clone())
Comment on lines +155 to +158
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reusing existing logic from to_field() implementation

}
Expr::Not(_)
| Expr::IsNull(_)
Expand Down Expand Up @@ -348,21 +315,9 @@ impl ExprSchemable for Expr {
}
}
Expr::Cast(Cast { expr, .. }) => expr.nullable(input_schema),
Expr::ScalarFunction(_func) => {
let field = self.to_field(input_schema)?.1;

let nullable = field.is_nullable();
Ok(nullable)
}
Expr::AggregateFunction(AggregateFunction { func, .. }) => {
Ok(func.is_nullable())
}
Expr::WindowFunction(window_function) => self
.data_type_and_nullable_with_window_function(
input_schema,
window_function,
)
.map(|(_, nullable)| nullable),
Expr::ScalarFunction(_)
| Expr::AggregateFunction(_)
| Expr::WindowFunction(_) => Ok(self.to_field(input_schema)?.1.is_nullable()),
Expr::ScalarVariable(field, _) => Ok(field.is_nullable()),
Expr::TryCast { .. } | Expr::Unnest(_) | Expr::Placeholder(_) => Ok(true),
Expr::IsNull(_)
Expand Down Expand Up @@ -534,73 +489,49 @@ impl ExprSchemable for Expr {
)))
}
Expr::WindowFunction(window_function) => {
let (dt, nullable) = self.data_type_and_nullable_with_window_function(
schema,
window_function,
)?;
Ok(Arc::new(Field::new(&schema_name, dt, nullable)))
}
Expr::AggregateFunction(aggregate_function) => {
let AggregateFunction {
func,
params: AggregateFunctionParams { args, .. },
let WindowFunction {
fun,
params: WindowFunctionParams { args, .. },
..
} = aggregate_function;
} = window_function.as_ref();

let fields = args
.iter()
.map(|e| e.to_field(schema).map(|(_, f)| f))
.collect::<Result<Vec<_>>>()?;
// Verify that function is invoked with correct number and type of arguments as defined in `TypeSignature`
let new_fields = fields_with_udf(&fields, func.as_ref())
.map_err(|err| {
let arg_types = fields
.iter()
.map(|f| f.data_type())
.cloned()
.collect::<Vec<_>>();
plan_datafusion_err!(
"{} {}",
match err {
DataFusionError::Plan(msg) => msg,
err => err.to_string(),
},
utils::generate_signature_error_msg(
func.name(),
func.signature().clone(),
&arg_types,
)
)
})?
.into_iter()
.collect::<Vec<_>>();

match fun {
WindowFunctionDefinition::AggregateUDF(udaf) => {
let new_fields =
verify_function_arguments(udaf.as_ref(), &fields)?;
let return_field = udaf.return_field(&new_fields)?;
Ok(return_field)
}
WindowFunctionDefinition::WindowUDF(udwf) => {
let new_fields =
verify_function_arguments(udwf.as_ref(), &fields)?;
let return_field = udwf
.field(WindowUDFFieldArgs::new(&new_fields, &schema_name))?;
Ok(return_field)
}
}
}
Expr::AggregateFunction(AggregateFunction {
func,
params: AggregateFunctionParams { args, .. },
}) => {
let fields = args
.iter()
.map(|e| e.to_field(schema).map(|(_, f)| f))
.collect::<Result<Vec<_>>>()?;
let new_fields = verify_function_arguments(func.as_ref(), &fields)?;
func.return_field(&new_fields)
}
Expr::ScalarFunction(ScalarFunction { func, args }) => {
let (arg_types, fields): (Vec<DataType>, Vec<Arc<Field>>) = args
let fields = args
.iter()
.map(|e| e.to_field(schema).map(|(_, f)| f))
.collect::<Result<Vec<_>>>()?
.into_iter()
.map(|f| (f.data_type().clone(), f))
.unzip();
// Verify that function is invoked with correct number and type of arguments as defined in `TypeSignature`
let new_fields =
fields_with_udf(&fields, func.as_ref()).map_err(|err| {
plan_datafusion_err!(
"{} {}",
match err {
DataFusionError::Plan(msg) => msg,
err => err.to_string(),
},
utils::generate_signature_error_msg(
func.name(),
func.signature().clone(),
&arg_types,
)
)
})?;
.collect::<Result<Vec<_>>>()?;
let new_fields = verify_function_arguments(func.as_ref(), &fields)?;

let arguments = args
.iter()
Expand Down Expand Up @@ -678,6 +609,33 @@ impl ExprSchemable for Expr {
}
}

/// Verify that function is invoked with correct number and type of arguments as
/// defined in `TypeSignature`.
fn verify_function_arguments<F: UDFCoercionExt>(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the new UDFCoercionExt trait we can now more easily share common code between scalar, aggregate and window UDFs

function: &F,
input_fields: &[FieldRef],
) -> Result<Vec<FieldRef>> {
fields_with_udf(input_fields, function).map_err(|err| {
let data_types = input_fields
.iter()
.map(|f| f.data_type())
.cloned()
.collect::<Vec<_>>();
plan_datafusion_err!(
"{} {}",
match err {
DataFusionError::Plan(msg) => msg,
err => err.to_string(),
},
utils::generate_signature_error_message(
function.name(),
function.signature(),
&data_types
)
)
})
}

/// Returns the innermost [Expr] that is provably null if `expr` is null.
fn unwrap_certainly_null_expr(expr: &Expr) -> &Expr {
match expr {
Expand All @@ -688,93 +646,6 @@ fn unwrap_certainly_null_expr(expr: &Expr) -> &Expr {
}
}

impl Expr {
/// Common method for window functions that applies type coercion
/// to all arguments of the window function to check if it matches
/// its signature.
///
/// If successful, this method returns the data type and
/// nullability of the window function's result.
///
/// Otherwise, returns an error if there's a type mismatch between
/// the window function's signature and the provided arguments.
fn data_type_and_nullable_with_window_function(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has been inlined to to_field()

&self,
schema: &dyn ExprSchema,
window_function: &WindowFunction,
) -> Result<(DataType, bool)> {
let WindowFunction {
fun,
params: WindowFunctionParams { args, .. },
..
} = window_function;

let fields = args
.iter()
.map(|e| e.to_field(schema).map(|(_, f)| f))
.collect::<Result<Vec<_>>>()?;
match fun {
WindowFunctionDefinition::AggregateUDF(udaf) => {
let data_types = fields
.iter()
.map(|f| f.data_type())
.cloned()
.collect::<Vec<_>>();
let new_fields = fields_with_udf(&fields, udaf.as_ref())
.map_err(|err| {
plan_datafusion_err!(
"{} {}",
match err {
DataFusionError::Plan(msg) => msg,
err => err.to_string(),
},
utils::generate_signature_error_msg(
fun.name(),
fun.signature(),
&data_types
)
)
})?
.into_iter()
.collect::<Vec<_>>();

let return_field = udaf.return_field(&new_fields)?;

Ok((return_field.data_type().clone(), return_field.is_nullable()))
}
WindowFunctionDefinition::WindowUDF(udwf) => {
let data_types = fields
.iter()
.map(|f| f.data_type())
.cloned()
.collect::<Vec<_>>();
let new_fields = fields_with_udf(&fields, udwf.as_ref())
.map_err(|err| {
plan_datafusion_err!(
"{} {}",
match err {
DataFusionError::Plan(msg) => msg,
err => err.to_string(),
},
utils::generate_signature_error_msg(
fun.name(),
fun.signature(),
&data_types
)
)
})?
.into_iter()
.collect::<Vec<_>>();
let (_, function_name) = self.qualified_name();
let field_args = WindowUDFFieldArgs::new(&new_fields, &function_name);

udwf.field(field_args)
.map(|field| (field.data_type().clone(), field.is_nullable()))
}
}
}
}

/// Cast subquery in InSubquery/ScalarSubquery to a given type.
///
/// 1. **Projection plan**: If the subquery is a projection (i.e. a SELECT statement with specific
Expand Down
Loading