use super::{Between, Expr, Like, predicate_bounds};
use crate::ValueOrLambda;
use crate::expr::{
AggregateFunction, AggregateFunctionParams, Alias, BinaryExpr, Cast, InList,
InSubquery, Lambda, Placeholder, ScalarFunction, TryCast, Unnest, WindowFunction,
WindowFunctionParams, in_subquery_tuple_values,
};
use crate::expr::{FieldMetadata, LambdaVariable};
use crate::higher_order_function::HigherOrderReturnFieldArgs;
use crate::type_coercion::functions::value_fields_with_higher_order_udf_and_lambdas;
use crate::type_coercion::functions::{UDFCoercionExt, fields_with_udf};
use crate::type_coercion::other::get_coerce_type_for_case_expression;
use crate::udf::ReturnFieldArgs;
use crate::{
LogicalPlan, Operator, Projection, Subquery, WindowFunctionDefinition, utils,
};
use arrow::compute::can_cast_types;
use arrow::datatypes::FieldRef;
use arrow::datatypes::{DataType, Field};
use arrow_schema::extension::{EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY};
use datafusion_common::datatype::FieldExt;
use datafusion_common::{
Column, DataFusionError, ExprSchema, Result, ScalarValue, Spans, TableReference,
not_impl_err, plan_datafusion_err, plan_err,
};
use datafusion_expr_common::type_coercion::binary::BinaryTypeCoercer;
use datafusion_functions_window_common::field::WindowUDFFieldArgs;
use std::sync::Arc;
pub trait ExprSchemable {
fn get_type(&self, schema: &dyn ExprSchema) -> Result<DataType>;
fn nullable(&self, input_schema: &dyn ExprSchema) -> Result<bool>;
fn metadata(&self, schema: &dyn ExprSchema) -> Result<FieldMetadata>;
fn to_field(
&self,
input_schema: &dyn ExprSchema,
) -> Result<(Option<TableReference>, Arc<Field>)>;
fn cast_to(self, cast_to_type: &DataType, schema: &dyn ExprSchema) -> Result<Expr>;
#[deprecated(
since = "51.0.0",
note = "Use `to_field().1.is_nullable` and `to_field().1.data_type()` directly instead"
)]
fn data_type_and_nullable(&self, schema: &dyn ExprSchema)
-> Result<(DataType, bool)>;
}
fn cast_output_field(
source_field: &FieldRef,
target_field: &FieldRef,
force_nullable: bool,
) -> Arc<Field> {
let is_type_only = target_field.name().is_empty()
&& target_field.is_nullable()
&& target_field.metadata().is_empty();
let metadata = if is_type_only {
let mut meta = source_field.metadata().clone();
meta.remove(EXTENSION_TYPE_NAME_KEY);
meta.remove(EXTENSION_TYPE_METADATA_KEY);
meta
} else {
target_field.metadata().clone()
};
let mut f = source_field
.as_ref()
.clone()
.with_data_type(target_field.data_type().clone())
.with_metadata(metadata);
if force_nullable {
f = f.with_nullable(true);
}
Arc::new(f)
}
fn scalar_arguments_for_fields(
args: &[Expr],
arg_fields: &[FieldRef],
) -> Vec<Option<ScalarValue>> {
args.iter()
.zip(arg_fields)
.map(|(expr, field)| scalar_argument_for_field(expr, field))
.collect()
}
fn scalar_argument_for_field(expr: &Expr, arg_field: &FieldRef) -> Option<ScalarValue> {
match expr {
Expr::Literal(sv, _) => Some(
sv.cast_to(arg_field.data_type())
.unwrap_or_else(|_| sv.clone()),
),
_ => None,
}
}
impl ExprSchemable for Expr {
#[cfg_attr(feature = "recursive_protection", recursive::recursive)]
fn get_type(&self, schema: &dyn ExprSchema) -> Result<DataType> {
match self {
Expr::Alias(Alias { expr, .. }) | Expr::Negative(expr) => {
expr.get_type(schema)
}
Expr::Column(c) => Ok(schema.data_type(c)?.clone()),
Expr::OuterReferenceColumn(field, _) => Ok(field.data_type().clone()),
Expr::ScalarVariable(field, _) => Ok(field.data_type().clone()),
Expr::Literal(l, _) => Ok(l.data_type()),
Expr::Case(case) => {
let then_types = case
.when_then_expr
.iter()
.map(|(_, expr)| expr.get_type(schema))
.collect::<Result<Vec<_>>>()?;
let else_type = case
.else_expr
.as_ref()
.map(|expr| expr.get_type(schema))
.transpose()?;
let common_type =
get_coerce_type_for_case_expression(&then_types, else_type.as_ref());
let result_type = common_type.unwrap_or_else(|| {
then_types
.into_iter()
.find(|t| !t.is_null())
.or(else_type)
.unwrap_or(DataType::Null)
});
Ok(result_type)
}
Expr::Cast(Cast { field, .. }) | Expr::TryCast(TryCast { field, .. }) => {
Ok(field.data_type().clone())
}
Expr::Unnest(Unnest { expr, .. }) => {
let arg_data_type = expr.get_type(schema)?;
match arg_data_type {
DataType::List(field)
| DataType::LargeList(field)
| DataType::FixedSizeList(field, _)
| DataType::ListView(field)
| DataType::LargeListView(field) => Ok(field.data_type().clone()),
DataType::Struct(_) => Ok(arg_data_type),
DataType::Null => {
not_impl_err!("unnest() does not support null yet")
}
_ => {
plan_err!(
"unnest() can only be applied to array, struct and null"
)
}
}
}
Expr::ScalarFunction(_)
| Expr::WindowFunction(_)
| Expr::AggregateFunction(_) => {
Ok(self.to_field(schema)?.1.data_type().clone())
}
Expr::Not(_)
| Expr::IsNull(_)
| Expr::Exists { .. }
| Expr::InSubquery(_)
| Expr::SetComparison(_)
| Expr::Between { .. }
| Expr::InList { .. }
| Expr::IsNotNull(_)
| Expr::IsTrue(_)
| Expr::IsFalse(_)
| Expr::IsUnknown(_)
| Expr::IsNotTrue(_)
| Expr::IsNotFalse(_)
| Expr::IsNotUnknown(_) => Ok(DataType::Boolean),
Expr::ScalarSubquery(subquery) => {
Ok(subquery.subquery.schema().field(0).data_type().clone())
}
Expr::BinaryExpr(BinaryExpr { left, right, op }) => BinaryTypeCoercer::new(
&left.get_type(schema)?,
op,
&right.get_type(schema)?,
)
.get_result_type(),
Expr::Like { .. } | Expr::SimilarTo { .. } => Ok(DataType::Boolean),
Expr::Placeholder(Placeholder { field, .. }) => {
if let Some(field) = field {
Ok(field.data_type().clone())
} else {
Ok(DataType::Null)
}
}
#[expect(deprecated)]
Expr::Wildcard { .. } => Ok(DataType::Null),
Expr::GroupingSet(_) => {
Ok(DataType::Null)
}
Expr::HigherOrderFunction(_func) => {
Ok(self.to_field(schema)?.1.data_type().clone())
}
Expr::Lambda(_lambda) => Ok(DataType::Null),
Expr::LambdaVariable(LambdaVariable { field, .. }) => match field {
Some(f) => Ok(f.data_type().clone()),
None => Ok(DataType::Null),
},
}
}
fn nullable(&self, input_schema: &dyn ExprSchema) -> Result<bool> {
match self {
Expr::Alias(Alias { expr, .. }) | Expr::Not(expr) | Expr::Negative(expr) => {
expr.nullable(input_schema)
}
Expr::InList(InList { expr, list, .. }) => {
const MAX_INSPECT_LIMIT: usize = 6;
let has_nullable = std::iter::once(expr.as_ref())
.chain(list)
.take(MAX_INSPECT_LIMIT)
.find_map(|e| {
e.nullable(input_schema)
.map(|nullable| if nullable { Some(()) } else { None })
.transpose()
})
.transpose()?;
Ok(match has_nullable {
Some(_) => true,
None if list.len() + 1 > MAX_INSPECT_LIMIT => true,
_ => false,
})
}
Expr::Between(Between {
expr, low, high, ..
}) => Ok(expr.nullable(input_schema)?
|| low.nullable(input_schema)?
|| high.nullable(input_schema)?),
Expr::Column(c) => input_schema.nullable(c),
Expr::OuterReferenceColumn(field, _) => Ok(field.is_nullable()),
Expr::Literal(value, _) => Ok(value.is_null()),
Expr::Case(case) => {
let nullable_then = case.when_then_expr.iter().find_map(|(w, t)| {
let is_nullable = match t.nullable(input_schema) {
Err(e) => return Some(Err(e)),
Ok(n) => n,
};
if !is_nullable {
return None;
}
if case.expr.is_some() {
return Some(Ok(()));
}
let bounds = match predicate_bounds::evaluate_bounds(
w,
Some(unwrap_certainly_null_expr(t)),
input_schema,
) {
Err(e) => return Some(Err(e)),
Ok(b) => b,
};
let can_be_true =
match bounds.contains_value(ScalarValue::Boolean(Some(true))) {
Err(e) => return Some(Err(e)),
Ok(b) => b,
};
if !can_be_true {
None
} else {
Some(Ok(()))
}
});
if let Some(nullable_then) = nullable_then {
nullable_then.map(|_| true)
} else if let Some(e) = &case.else_expr {
e.nullable(input_schema)
} else {
Ok(true)
}
}
Expr::Cast(Cast { expr, .. }) => expr.nullable(input_schema),
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(_)
| Expr::IsNotNull(_)
| Expr::IsTrue(_)
| Expr::IsFalse(_)
| Expr::IsUnknown(_)
| Expr::IsNotTrue(_)
| Expr::IsNotFalse(_)
| Expr::IsNotUnknown(_)
| Expr::Exists { .. } => Ok(false),
Expr::SetComparison(_) => Ok(true),
Expr::InSubquery(InSubquery { expr, subquery, .. }) => {
if let Some(values) = in_subquery_tuple_values(expr, &subquery.subquery)?
{
let mut nullable = subquery
.subquery
.schema()
.fields()
.iter()
.any(|field| field.is_nullable());
for value in values.iter() {
nullable |= value.nullable(input_schema)?;
}
return Ok(nullable);
}
let expr_nullable = expr.nullable(input_schema)?;
let subquery_nullable = subquery.subquery.schema().fields().first().ok_or_else(|| {
plan_datafusion_err!("subquery must return exactly one column of data to compare against")
})?.is_nullable();
Ok(expr_nullable | subquery_nullable)
}
Expr::ScalarSubquery(subquery) => Ok(scalar_subquery_nullable(subquery)),
Expr::BinaryExpr(BinaryExpr { left, right, op }) => match op {
Operator::IsDistinctFrom | Operator::IsNotDistinctFrom => Ok(false),
_ => Ok(left.nullable(input_schema)? || right.nullable(input_schema)?),
},
Expr::Like(Like { expr, pattern, .. })
| Expr::SimilarTo(Like { expr, pattern, .. }) => {
Ok(expr.nullable(input_schema)? || pattern.nullable(input_schema)?)
}
#[expect(deprecated)]
Expr::Wildcard { .. } => Ok(false),
Expr::GroupingSet(_) => {
Ok(true)
}
Expr::HigherOrderFunction(_func) => {
Ok(self.to_field(input_schema)?.1.is_nullable())
}
Expr::Lambda(_lambda) => Ok(true),
Expr::LambdaVariable(LambdaVariable { field, .. }) => match field {
Some(f) => Ok(f.is_nullable()),
None => Ok(true),
},
}
}
fn metadata(&self, schema: &dyn ExprSchema) -> Result<FieldMetadata> {
self.to_field(schema)
.map(|(_, field)| FieldMetadata::from(field.metadata()))
}
fn data_type_and_nullable(
&self,
schema: &dyn ExprSchema,
) -> Result<(DataType, bool)> {
let field = self.to_field(schema)?.1;
Ok((field.data_type().clone(), field.is_nullable()))
}
fn to_field(
&self,
schema: &dyn ExprSchema,
) -> Result<(Option<TableReference>, Arc<Field>)> {
let (relation, schema_name) = self.qualified_name();
#[expect(deprecated)]
let field = match self {
Expr::Alias(Alias {
expr,
name: _,
metadata,
..
}) => {
let field = expr.to_field(schema)?.1;
let mut combined_metadata = FieldMetadata::from(field.metadata());
if let Some(metadata) = metadata {
combined_metadata.extend(metadata.clone());
}
Ok(field.with_field_metadata(&combined_metadata))
}
Expr::Negative(expr) => expr.to_field(schema).map(|(_, f)| f),
Expr::Column(c) => schema.field_from_column(c).map(Arc::clone),
Expr::OuterReferenceColumn(field, _) => {
Ok(Arc::clone(field).renamed(&schema_name))
}
Expr::ScalarVariable(field, _) => Ok(Arc::clone(field).renamed(&schema_name)),
Expr::Literal(l, metadata) => Ok(Arc::new(
Field::new(&schema_name, l.data_type(), l.is_null())
.with_field_metadata_opt(metadata.as_ref()),
)),
Expr::IsNull(_)
| Expr::IsNotNull(_)
| Expr::IsTrue(_)
| Expr::IsFalse(_)
| Expr::IsUnknown(_)
| Expr::IsNotTrue(_)
| Expr::IsNotFalse(_)
| Expr::IsNotUnknown(_)
| Expr::Exists { .. } => {
Ok(Arc::new(Field::new(&schema_name, DataType::Boolean, false)))
}
Expr::ScalarSubquery(subquery) => {
let field = subquery.subquery.schema().field(0);
Ok(Arc::new(
field
.as_ref()
.clone()
.with_nullable(scalar_subquery_nullable(subquery)),
))
}
Expr::BinaryExpr(BinaryExpr { left, right, op }) => {
let (left_field, right_field) =
(left.to_field(schema)?.1, right.to_field(schema)?.1);
let (lhs_type, lhs_nullable) =
(left_field.data_type(), left_field.is_nullable());
let (rhs_type, rhs_nullable) =
(right_field.data_type(), right_field.is_nullable());
let mut coercer = BinaryTypeCoercer::new(lhs_type, op, rhs_type);
coercer.set_lhs_spans(left.spans().cloned().unwrap_or_default());
coercer.set_rhs_spans(right.spans().cloned().unwrap_or_default());
let nullable = match op {
Operator::IsDistinctFrom | Operator::IsNotDistinctFrom => false,
_ => lhs_nullable || rhs_nullable,
};
Ok(Arc::new(Field::new(
&schema_name,
coercer.get_result_type()?,
nullable,
)))
}
Expr::WindowFunction(window_function) => {
let WindowFunction {
fun,
params: WindowFunctionParams { args, .. },
} = window_function.as_ref();
let fields = args
.iter()
.map(|e| e.to_field(schema).map(|(_, f)| f))
.collect::<Result<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 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)?;
let arguments = scalar_arguments_for_fields(args, &new_fields);
let argument_refs =
arguments.iter().map(Option::as_ref).collect::<Vec<_>>();
let args = ReturnFieldArgs {
arg_fields: &new_fields,
scalar_arguments: &argument_refs,
};
func.return_field_from_args(args)
}
Expr::Cast(Cast { expr, field }) => expr
.to_field(schema)
.map(|(_table_ref, src)| cast_output_field(&src, field, false)),
Expr::Placeholder(Placeholder {
id: _,
field: Some(field),
}) => Ok(Arc::clone(field).renamed(&schema_name)),
Expr::TryCast(TryCast { expr, field }) => expr
.to_field(schema)
.map(|(_table_ref, src)| cast_output_field(&src, field, true)),
Expr::LambdaVariable(LambdaVariable {
field: Some(field), ..
}) => Ok(Arc::clone(field).renamed(&schema_name)),
Expr::Unnest(Unnest { expr, .. }) => {
let nullable = self.nullable(schema)?;
match expr.get_type(schema)? {
DataType::List(field)
| DataType::LargeList(field)
| DataType::FixedSizeList(field, _)
| DataType::ListView(field)
| DataType::LargeListView(field) => Ok(Arc::new(
field
.as_ref()
.clone()
.with_name(&schema_name)
.with_nullable(nullable),
)),
_ => Ok(Arc::new(Field::new(
&schema_name,
self.get_type(schema)?,
nullable,
))),
}
}
Expr::Like(_)
| Expr::SimilarTo(_)
| Expr::Not(_)
| Expr::Between(_)
| Expr::Case(_)
| Expr::InList(_)
| Expr::InSubquery(_)
| Expr::SetComparison(_)
| Expr::Wildcard { .. }
| Expr::GroupingSet(_)
| Expr::Placeholder(_)
| Expr::Lambda(_)
| Expr::LambdaVariable(_) => Ok(Arc::new(Field::new(
&schema_name,
self.get_type(schema)?,
self.nullable(schema)?,
))),
Expr::HigherOrderFunction(func) => {
let arg_fields = func
.args
.iter()
.map(|arg| match arg {
Expr::Lambda(Lambda { params: _, body }) => {
Ok(ValueOrLambda::Lambda(Arc::new(Field::new(
arg.qualified_name().1,
body.get_type(schema)?,
body.nullable(schema)?,
))))
}
_ => Ok(ValueOrLambda::Value(arg.to_field(schema)?.1)),
})
.collect::<Result<Vec<_>>>()?;
let new_fields = value_fields_with_higher_order_udf_and_lambdas(
&arg_fields,
func.func.as_ref(),
)?;
let arguments = func
.args
.iter()
.map(|e| match e {
Expr::Literal(sv, _) => Some(sv),
_ => None,
})
.collect::<Vec<_>>();
let args = HigherOrderReturnFieldArgs {
arg_fields: &new_fields,
scalar_arguments: &arguments,
};
func.func.return_field_from_args(args)
}
}?;
Ok((
relation,
field.renamed(&schema_name),
))
}
fn cast_to(self, cast_to_type: &DataType, schema: &dyn ExprSchema) -> Result<Expr> {
let this_type = self.get_type(schema)?;
if this_type == *cast_to_type {
return Ok(self);
}
let can_cast = match (&this_type, cast_to_type) {
(DataType::Struct(_), DataType::Struct(_)) => {
true
}
_ => can_cast_types(&this_type, cast_to_type),
};
if can_cast {
match self {
Expr::ScalarSubquery(subquery) => {
Ok(Expr::ScalarSubquery(cast_subquery(subquery, cast_to_type)?))
}
_ => Ok(Expr::Cast(Cast::new(Box::new(self), cast_to_type.clone()))),
}
} else {
plan_err!("Cannot automatically convert {this_type} to {cast_to_type}")
}
}
}
fn verify_function_arguments<F: UDFCoercionExt>(
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
)
)
})
}
fn unwrap_certainly_null_expr(expr: &Expr) -> &Expr {
match expr {
Expr::Not(e) => unwrap_certainly_null_expr(e),
Expr::Negative(e) => unwrap_certainly_null_expr(e),
Expr::Cast(e) => unwrap_certainly_null_expr(e.expr.as_ref()),
_ => expr,
}
}
fn scalar_subquery_nullable(subquery: &Subquery) -> bool {
subquery.subquery.schema().field(0).is_nullable() || subquery.subquery.min_rows() == 0
}
pub fn cast_subquery(subquery: Subquery, cast_to_type: &DataType) -> Result<Subquery> {
cast_subquery_columns(subquery, std::slice::from_ref(cast_to_type))
}
pub fn cast_subquery_columns(
subquery: Subquery,
cast_to_types: &[DataType],
) -> Result<Subquery> {
let schema = subquery.subquery.schema();
if schema
.fields()
.iter()
.zip(cast_to_types)
.all(|(field, cast_to_type)| field.data_type() == cast_to_type)
{
return Ok(subquery);
}
let plan = subquery.subquery.as_ref();
let new_plan = match plan {
LogicalPlan::Projection(projection) => {
let cast_exprs = projection
.expr
.iter()
.zip(cast_to_types)
.map(|(expr, cast_to_type)| {
expr.clone()
.cast_to(cast_to_type, projection.input.schema())
})
.collect::<Result<Vec<_>>>()?;
LogicalPlan::Projection(Projection::try_new(
cast_exprs,
Arc::clone(&projection.input),
)?)
}
_ => {
let cast_exprs = cast_to_types
.iter()
.enumerate()
.map(|(i, cast_to_type)| {
Expr::Column(Column::from(plan.schema().qualified_field(i)))
.cast_to(cast_to_type, subquery.subquery.schema())
})
.collect::<Result<Vec<_>>>()?;
LogicalPlan::Projection(Projection::try_new(
cast_exprs,
Arc::clone(&subquery.subquery),
)?)
}
};
Ok(Subquery {
subquery: Arc::new(new_plan),
outer_ref_columns: subquery.outer_ref_columns,
spans: Spans::new(),
})
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::*;
use crate::logical_plan::builder::LogicalTableSource;
use crate::test::function_stub::count;
use crate::{
LogicalPlanBuilder, and, col, in_subquery, lit, not, or,
out_ref_col_with_metadata, scalar_subquery, when,
};
use arrow::datatypes::Schema;
use datafusion_common::{DFSchema, assert_or_internal_err};
macro_rules! test_is_expr_nullable {
($EXPR_TYPE:ident) => {{
let expr = lit(ScalarValue::Null).$EXPR_TYPE();
assert!(!expr.nullable(&MockExprSchema::new()).unwrap());
}};
}
#[test]
fn scalar_arguments_match_coerced_fields() {
let int16_field: FieldRef = Field::new("arg", DataType::Int16, true).into();
assert_eq!(
scalar_argument_for_field(&lit(1_i64), &int16_field),
Some(ScalarValue::Int16(Some(1)))
);
assert_eq!(
scalar_argument_for_field(&lit(ScalarValue::Null), &int16_field),
Some(ScalarValue::Int16(None))
);
let int32_list = ScalarValue::List(ScalarValue::new_list(
&[ScalarValue::Int32(Some(1))],
&DataType::Int32,
true,
));
let int64_list_type = DataType::new_list(DataType::Int64, true);
let int64_list_field: FieldRef =
Field::new("arg", int64_list_type.clone(), true).into();
assert_eq!(
scalar_argument_for_field(&lit(int32_list.clone()), &int64_list_field),
Some(int32_list.cast_to(&int64_list_type).unwrap())
);
}
#[test]
fn scalar_arguments_exclude_expression_casts_and_preserve_invalid_values() {
let int16_field: FieldRef = Field::new("arg", DataType::Int16, true).into();
let int32_field: FieldRef = Field::new("arg", DataType::Int32, true).into();
let explicit_cast = Expr::Cast(Cast::new(Box::new(lit(1_i64)), DataType::Int16));
let explicit_try_cast =
Expr::TryCast(TryCast::new(Box::new(lit(1_i64)), DataType::Int16));
let out_of_i32_range = i64::from(i32::MAX) + 1;
assert_eq!(
scalar_argument_for_field(&explicit_cast, &int16_field),
None
);
assert_eq!(
scalar_argument_for_field(&explicit_try_cast, &int16_field),
None
);
assert_eq!(
scalar_argument_for_field(&lit("not an integer"), &int16_field),
Some(ScalarValue::Utf8(Some("not an integer".to_string())))
);
assert_eq!(
scalar_argument_for_field(&lit(out_of_i32_range), &int32_field),
Some(ScalarValue::Int64(Some(out_of_i32_range)))
);
}
#[test]
fn expr_schema_nullability() {
let cases = [
(Operator::Eq, false, false),
(Operator::Eq, true, true),
(Operator::IsDistinctFrom, true, false),
(Operator::IsNotDistinctFrom, true, false),
];
for (op, input_nullable, expected) in cases {
let expr = Expr::BinaryExpr(BinaryExpr::new(
Box::new(col("foo")),
op,
Box::new(col("bar")),
));
let schema = MockExprSchema::new()
.with_data_type(DataType::Boolean)
.with_nullable(input_nullable);
assert_eq!(expr.nullable(&schema).unwrap(), expected, "{op}");
assert_eq!(
expr.to_field(&schema).unwrap().1.is_nullable(),
expected,
"{op}"
);
}
test_is_expr_nullable!(is_null);
test_is_expr_nullable!(is_not_null);
test_is_expr_nullable!(is_true);
test_is_expr_nullable!(is_not_true);
test_is_expr_nullable!(is_false);
test_is_expr_nullable!(is_not_false);
test_is_expr_nullable!(is_unknown);
test_is_expr_nullable!(is_not_unknown);
}
#[test]
fn test_between_nullability() {
let get_schema = |nullable| {
MockExprSchema::new()
.with_data_type(DataType::Int32)
.with_nullable(nullable)
};
let expr = col("foo").between(lit(1), lit(2));
assert!(!expr.nullable(&get_schema(false)).unwrap());
assert!(expr.nullable(&get_schema(true)).unwrap());
let null = lit(ScalarValue::Int32(None));
let expr = col("foo").between(null.clone(), lit(2));
assert!(expr.nullable(&get_schema(false)).unwrap());
let expr = col("foo").between(lit(1), null.clone());
assert!(expr.nullable(&get_schema(false)).unwrap());
let expr = col("foo").between(null.clone(), null);
assert!(expr.nullable(&get_schema(false)).unwrap());
}
fn assert_nullability(expr: &Expr, schema: &dyn ExprSchema, expected: bool) {
assert_eq!(
expr.nullable(schema).unwrap(),
expected,
"Nullability of '{expr}' should be {expected}"
);
}
fn assert_not_nullable(expr: &Expr, schema: &dyn ExprSchema) {
assert_nullability(expr, schema, false);
}
fn assert_nullable(expr: &Expr, schema: &dyn ExprSchema) {
assert_nullability(expr, schema, true);
}
#[test]
fn test_case_expression_nullability() -> Result<()> {
let nullable_schema = MockExprSchema::new()
.with_data_type(DataType::Int32)
.with_nullable(true);
let not_nullable_schema = MockExprSchema::new()
.with_data_type(DataType::Int32)
.with_nullable(false);
let e = when(col("x").is_not_null(), col("x")).otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(not(col("x").is_null()), col("x")).otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(col("x").eq(lit(5)), col("x")).otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(and(col("x").is_not_null(), col("x").eq(lit(5))), col("x"))
.otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(and(col("x").eq(lit(5)), col("x").is_not_null()), col("x"))
.otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(or(col("x").is_not_null(), col("x").eq(lit(5))), col("x"))
.otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(or(col("x").eq(lit(5)), col("x").is_not_null()), col("x"))
.otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(
or(
and(col("x").eq(lit(5)), col("x").is_not_null()),
and(col("x").eq(col("bar")), col("x").is_not_null()),
),
col("x"),
)
.otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(or(col("x").eq(lit(5)), col("x").is_null()), col("x"))
.otherwise(lit(0))?;
assert_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(col("x").is_true(), col("x")).otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(col("x").is_not_true(), col("x")).otherwise(lit(0))?;
assert_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(col("x").is_false(), col("x")).otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(col("x").is_not_false(), col("x")).otherwise(lit(0))?;
assert_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(col("x").is_unknown(), col("x")).otherwise(lit(0))?;
assert_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(col("x").is_not_unknown(), col("x")).otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(col("x").like(lit("x")), col("x")).otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(lit(0), col("x")).otherwise(lit(0))?;
assert_not_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
let e = when(lit(1), col("x")).otherwise(lit(0))?;
assert_nullable(&e, &nullable_schema);
assert_not_nullable(&e, ¬_nullable_schema);
Ok(())
}
#[test]
fn test_inlist_nullability() {
let get_schema = |nullable| {
MockExprSchema::new()
.with_data_type(DataType::Int32)
.with_nullable(nullable)
};
let expr = col("foo").in_list(vec![lit(1); 5], false);
assert!(!expr.nullable(&get_schema(false)).unwrap());
assert!(expr.nullable(&get_schema(true)).unwrap());
assert!(
expr.nullable(&get_schema(false).with_error_on_nullable(true))
.is_err()
);
let null = lit(ScalarValue::Int32(None));
let expr = col("foo").in_list(vec![null, lit(1)], false);
assert!(expr.nullable(&get_schema(false)).unwrap());
let expr = col("foo").in_list(vec![lit(1); 6], false);
assert!(expr.nullable(&get_schema(false)).unwrap());
}
#[test]
fn test_like_nullability() {
let get_schema = |nullable| {
MockExprSchema::new()
.with_data_type(DataType::Utf8)
.with_nullable(nullable)
};
let expr = col("foo").like(lit("bar"));
assert!(!expr.nullable(&get_schema(false)).unwrap());
assert!(expr.nullable(&get_schema(true)).unwrap());
let expr = col("foo").like(lit(ScalarValue::Utf8(None)));
assert!(expr.nullable(&get_schema(false)).unwrap());
}
#[test]
fn expr_schema_data_type() {
let expr = col("foo");
assert_eq!(
DataType::Utf8,
expr.get_type(&MockExprSchema::new().with_data_type(DataType::Utf8))
.unwrap()
);
}
#[test]
fn test_expr_metadata() {
let mut meta = HashMap::new();
meta.insert("bar".to_string(), "buzz".to_string());
let meta = FieldMetadata::from(meta);
let expr = col("foo");
let schema = MockExprSchema::new()
.with_data_type(DataType::Int32)
.with_metadata(meta.clone());
assert_eq!(meta, expr.metadata(&schema).unwrap());
assert_eq!(meta, expr.clone().alias("bar").metadata(&schema).unwrap());
assert_eq!(
meta,
expr.clone()
.cast_to(&DataType::Int64, &schema)
.unwrap()
.metadata(&schema)
.unwrap()
);
let schema = DFSchema::from_unqualified_fields(
vec![meta.add_to_field(Field::new("foo", DataType::Int32, true))].into(),
HashMap::new(),
)
.unwrap();
assert_eq!(meta, expr.metadata(&schema).unwrap());
let outer_ref = out_ref_col_with_metadata(
DataType::Int32,
meta.to_hashmap(),
Column::from_name("foo"),
);
assert_eq!(meta, outer_ref.metadata(&schema).unwrap());
}
#[test]
fn test_alias_metadata_is_preserved_in_field_metadata() {
let schema = MockExprSchema::new().with_data_type(DataType::Int32);
let alias_metadata = FieldMetadata::from(HashMap::from([(
"some_key".to_string(),
"some_value".to_string(),
)]));
let Expr::Alias(alias) = col("foo").alias("alias") else {
unreachable!();
};
let expr = Expr::Alias(alias.with_metadata(Some(alias_metadata.clone())));
let field = expr.to_field(&schema).unwrap().1;
assert_eq!(
field.metadata().get("some_key"),
Some(&"some_value".to_string())
);
assert_eq!(expr.metadata(&schema).unwrap(), alias_metadata);
}
#[test]
fn test_nested_alias_resolves_child_field_once() -> Result<()> {
#[derive(Debug)]
struct CountingSchema {
field: FieldRef,
lookups: std::cell::Cell<usize>,
}
impl ExprSchema for CountingSchema {
fn nullable(&self, _col: &Column) -> Result<bool> {
Ok(self.field.is_nullable())
}
fn field_from_column(&self, _col: &Column) -> Result<&FieldRef> {
self.lookups.set(self.lookups.get() + 1);
Ok(&self.field)
}
}
let schema = CountingSchema {
field: Arc::new(Field::new("value", DataType::Int32, false).with_metadata(
HashMap::from([
("override".to_string(), "base".to_string()),
("keep".to_string(), "base".to_string()),
]),
)),
lookups: std::cell::Cell::new(0),
};
let mut expr = col("value");
for index in 0..12 {
let metadata = Some(FieldMetadata::from(HashMap::from([(
"override".to_string(),
index.to_string(),
)])));
expr = if index == 11 {
expr.alias_qualified_with_metadata(
Some("outer"),
format!("alias_{index}"),
metadata,
)
} else {
expr.alias_with_metadata(format!("alias_{index}"), metadata)
};
}
let (relation, field) = expr.to_field(&schema)?;
assert_eq!(schema.lookups.get(), 1);
assert_eq!(relation, Some(TableReference::bare("outer")));
assert_eq!(field.name(), "alias_11");
assert_eq!(field.data_type(), &DataType::Int32);
assert!(!field.is_nullable());
assert_eq!(field.metadata().get("override"), Some(&"11".to_string()));
assert_eq!(field.metadata().get("keep"), Some(&"base".to_string()));
Ok(())
}
#[test]
fn test_expr_placeholder() {
let schema = MockExprSchema::new();
let mut placeholder_meta = HashMap::new();
placeholder_meta.insert("bar".to_string(), "buzz".to_string());
let placeholder_meta = FieldMetadata::from(placeholder_meta);
let expr = Expr::Placeholder(Placeholder::new_with_field(
"".to_string(),
Some(
Field::new("", DataType::Utf8, true)
.with_metadata(placeholder_meta.to_hashmap())
.into(),
),
));
let field = expr.to_field(&schema).unwrap().1;
assert_eq!(
(field.data_type(), field.is_nullable()),
(&DataType::Utf8, true)
);
assert_eq!(placeholder_meta, expr.metadata(&schema).unwrap());
let expr_alias = expr.alias("a placeholder by any other name");
let expr_alias_field = expr_alias.to_field(&schema).unwrap().1;
assert_eq!(
(expr_alias_field.data_type(), expr_alias_field.is_nullable()),
(&DataType::Utf8, true)
);
assert_eq!(placeholder_meta, expr_alias.metadata(&schema).unwrap());
let expr = Expr::Placeholder(Placeholder::new_with_field(
"".to_string(),
Some(Field::new("", DataType::Utf8, false).into()),
));
let expr_field = expr.to_field(&schema).unwrap().1;
assert_eq!(
(expr_field.data_type(), expr_field.is_nullable()),
(&DataType::Utf8, false)
);
let expr_alias = expr.alias("a placeholder by any other name");
let expr_alias_field = expr_alias.to_field(&schema).unwrap().1;
assert_eq!(
(expr_alias_field.data_type(), expr_alias_field.is_nullable()),
(&DataType::Utf8, false)
);
}
#[test]
fn test_untyped_aliased_placeholder_in_empty_schema() {
let schema = DFSchema::empty();
let expr = Expr::Placeholder(Placeholder::new_with_field("$1".to_string(), None))
.alias("a");
assert_eq!(expr.get_type(&schema).unwrap(), DataType::Null);
assert_eq!(
expr.to_field(&schema).unwrap().1.data_type(),
&DataType::Null
);
}
#[derive(Debug)]
struct MockExprSchema {
field: FieldRef,
error_on_nullable: bool,
}
impl MockExprSchema {
fn new() -> Self {
Self {
field: Arc::new(Field::new("mock_field", DataType::Null, false)),
error_on_nullable: false,
}
}
fn with_nullable(mut self, nullable: bool) -> Self {
Arc::make_mut(&mut self.field).set_nullable(nullable);
self
}
fn with_data_type(mut self, data_type: DataType) -> Self {
Arc::make_mut(&mut self.field).set_data_type(data_type);
self
}
fn with_error_on_nullable(mut self, error_on_nullable: bool) -> Self {
self.error_on_nullable = error_on_nullable;
self
}
fn with_metadata(mut self, metadata: FieldMetadata) -> Self {
self.field =
Arc::new(metadata.add_to_field(Arc::unwrap_or_clone(self.field)));
self
}
}
impl ExprSchema for MockExprSchema {
fn nullable(&self, _col: &Column) -> Result<bool> {
assert_or_internal_err!(!self.error_on_nullable, "nullable error");
Ok(self.field.is_nullable())
}
fn field_from_column(&self, _col: &Column) -> Result<&FieldRef> {
Ok(&self.field)
}
}
fn scan_t(a_nullable: bool) -> LogicalPlanBuilder {
let schema = Schema::new(vec![Field::new("a", DataType::Int32, a_nullable)]);
let source = Arc::new(LogicalTableSource::new(Arc::new(schema)));
LogicalPlanBuilder::scan("t", source, None).unwrap()
}
#[test]
fn in_subquery_nullability() {
let cases = [
(false, false, false),
(false, true, true),
(true, false, true),
(true, true, true),
];
for (x_nullable, a_nullable, expected) in cases {
let subquery = scan_t(a_nullable)
.project(vec![col("a")])
.unwrap()
.build()
.unwrap();
let expr = in_subquery(col("x"), Arc::new(subquery));
let schema = MockExprSchema::new().with_nullable(x_nullable);
assert_eq!(expr.nullable(&schema).unwrap(), expected);
}
}
#[test]
fn in_subquery_nullability_uses_subquery_output_schema() {
let subquery = scan_t(true)
.project(vec![col("a")])
.unwrap()
.distinct()
.unwrap()
.build()
.unwrap();
let expr = in_subquery(col("x"), Arc::new(subquery));
assert!(expr.nullable(&MockExprSchema::new()).unwrap());
let subquery = scan_t(false)
.project(vec![col("a") + lit(1)])
.unwrap()
.build()
.unwrap();
let expr = in_subquery(col("x"), Arc::new(subquery));
assert!(!expr.nullable(&MockExprSchema::new()).unwrap());
}
#[test]
fn in_subquery_nullability_errors_for_no_subquery_columns() {
let subquery = LogicalPlanBuilder::empty(false).build().unwrap();
let expr = in_subquery(col("x"), Arc::new(subquery));
let err = expr.nullable(&MockExprSchema::new()).unwrap_err();
assert_eq!(
err.strip_backtrace(),
"Error during planning: subquery must return exactly one column of data to compare against"
);
}
#[test]
fn scalar_subquery_nullability_accounts_for_min_rows() {
let possibly_empty = LogicalPlanBuilder::empty(false)
.project(vec![lit(1)])
.unwrap()
.build()
.unwrap();
assert!(!possibly_empty.schema().field(0).is_nullable());
let expr = scalar_subquery(Arc::new(possibly_empty));
assert!(expr.nullable(&MockExprSchema::new()).unwrap());
let field = expr.to_field(&MockExprSchema::new()).unwrap().1;
assert_eq!(field.data_type(), &DataType::Int32);
assert!(field.is_nullable());
let always_one = LogicalPlanBuilder::empty(false)
.aggregate(Vec::<Expr>::new(), vec![count(lit(1))])
.unwrap()
.build()
.unwrap();
assert!(!always_one.schema().field(0).is_nullable());
let expr = scalar_subquery(Arc::new(always_one));
assert!(!expr.nullable(&MockExprSchema::new()).unwrap());
assert!(
!expr
.to_field(&MockExprSchema::new())
.unwrap()
.1
.is_nullable()
);
}
#[test]
fn test_scalar_variable() {
let mut meta = HashMap::new();
meta.insert("bar".to_string(), "buzz".to_string());
let meta = FieldMetadata::from(meta);
let field = Field::new("foo", DataType::Int32, true);
let field = meta.add_to_field(field);
let field = Arc::new(field);
let expr = Expr::ScalarVariable(field, vec!["foo".to_string()]);
let schema = MockExprSchema::new();
assert_eq!(meta, expr.metadata(&schema).unwrap());
}
#[test]
fn test_cast_and_try_cast_extension_type_metadata() {
use crate::expr::{Cast, TryCast};
use arrow_schema::extension::{
EXTENSION_TYPE_METADATA_KEY, EXTENSION_TYPE_NAME_KEY,
};
fn make_cast_expr(
expr: Expr,
target_field: FieldRef,
use_try_cast: bool,
) -> Expr {
if use_try_cast {
Expr::TryCast(TryCast {
expr: Box::new(expr),
field: target_field,
})
} else {
Expr::Cast(Cast {
expr: Box::new(expr),
field: target_field,
})
}
}
for use_try_cast in [false, true] {
let cast_name = if use_try_cast { "TryCast" } else { "Cast" };
let mut source_meta = HashMap::new();
source_meta.insert(
EXTENSION_TYPE_NAME_KEY.to_string(),
"arrow.uuid".to_string(),
);
source_meta.insert("custom_key".to_string(), "custom_value".to_string());
let source_field = Field::new("foo", DataType::FixedSizeBinary(16), false)
.with_metadata(source_meta);
let schema = MockExprSchema::new()
.with_data_type(DataType::FixedSizeBinary(16))
.with_metadata(FieldMetadata::from(source_field.metadata().clone()));
let cast_expr = make_cast_expr(
col("foo"),
Arc::new(Field::new("", DataType::Utf8, true)),
use_try_cast,
);
let (_, result_field) = cast_expr.to_field(&schema).unwrap();
assert!(
result_field
.metadata()
.get(EXTENSION_TYPE_NAME_KEY)
.is_none(),
"{cast_name}: Extension type name should be stripped when target has no extension metadata"
);
assert_eq!(
result_field.metadata().get("custom_key"),
Some(&"custom_value".to_string()),
"{cast_name}: Non-extension metadata should be preserved"
);
if use_try_cast {
assert!(
result_field.is_nullable(),
"TryCast result should be nullable"
);
}
let mut target_meta = HashMap::new();
target_meta.insert(
EXTENSION_TYPE_NAME_KEY.to_string(),
"arrow.json".to_string(),
);
target_meta.insert(EXTENSION_TYPE_METADATA_KEY.to_string(), "{}".to_string());
let target_field =
Field::new("", DataType::Utf8, true).with_metadata(target_meta);
let cast_expr =
make_cast_expr(col("foo"), Arc::new(target_field), use_try_cast);
let (_, result_field) = cast_expr.to_field(&schema).unwrap();
assert_eq!(
result_field.metadata().get(EXTENSION_TYPE_NAME_KEY),
Some(&"arrow.json".to_string()),
"{cast_name}: Extension type name should come from target field"
);
assert_eq!(
result_field.metadata().get(EXTENSION_TYPE_METADATA_KEY),
Some(&"{}".to_string()),
"{cast_name}: Extension type metadata should come from target field"
);
assert!(
result_field.metadata().get("custom_key").is_none(),
"{cast_name}: Source metadata should NOT propagate when target has explicit metadata"
);
if use_try_cast {
assert!(
result_field.is_nullable(),
"TryCast result should be nullable"
);
}
}
}
#[test]
fn case_infers_all_result_types_without_casting() -> Result<()> {
use crate::expr::Case;
let schema = DFSchema::empty();
let nested = Expr::Case(Case::new(
None,
vec![(Box::new(lit(false)), Box::new(lit(1_i64)))],
Some(Box::new(lit(2.5))),
));
for (then_values, else_value, expected) in [
(vec![lit(1_i64)], Some(lit(2.5)), DataType::Float64),
(vec![lit(1_i64), lit(2.5)], None, DataType::Float64),
(vec![lit(2.5), lit(1_i64)], None, DataType::Float64),
(vec![lit(2.5)], Some(lit(1_i64)), DataType::Float64),
(vec![lit(3_i64)], Some(nested), DataType::Float64),
(vec![lit(ScalarValue::Null)], None, DataType::Null),
(vec![lit(true)], Some(lit("a")), DataType::Boolean),
] {
let when_then = then_values
.into_iter()
.map(|value| (Box::new(lit(true)), Box::new(value)))
.collect();
let expr = Expr::Case(Case::new(None, when_then, else_value.map(Box::new)));
assert_eq!(expr.get_type(&schema)?, expected);
}
Ok(())
}
}