use arrow::datatypes::{DataType, Field};
use datafusion_common::{Result, plan_datafusion_err, plan_err};
use super::binary::{comparison_coercion, type_union_coercion};
fn fold_coerce(
initial_type: &DataType,
types: &[DataType],
coerce_fn: fn(&DataType, &DataType) -> Option<DataType>,
) -> Option<DataType> {
types
.iter()
.try_fold(initial_type.clone(), |left_type, right_type| {
coerce_fn(&left_type, right_type)
})
}
pub fn coerce_union_type<'a>(
fields: impl IntoIterator<Item = &'a Field>,
) -> Result<DataType> {
let mut fields = fields.into_iter();
let Some(first) = fields.next() else {
return plan_err!("UNION requires at least one input field");
};
fields.try_fold(first.data_type().clone(), |data_type, field| {
type_union_coercion(&data_type, field.data_type()).ok_or_else(|| {
plan_datafusion_err!(
"Incompatible inputs for Union: Previous inputs were \
of type {}, but got incompatible type {} on column '{}'",
data_type,
field.data_type(),
field.name()
)
})
})
}
#[deprecated(
since = "56.0.0",
note = "Fold `comparison_coercion_with_session_timezone` over the values instead, so `IN` coerces exactly as `=` does"
)]
pub fn get_coerce_type_for_list(
expr_type: &DataType,
list_types: &[DataType],
) -> Option<DataType> {
fold_coerce(expr_type, list_types, comparison_coercion)
}
#[deprecated(
since = "56.0.0",
note = "Fold `comparison_coercion_with_session_timezone` over the values instead, so `CASE expr WHEN` coerces exactly as `=` does"
)]
pub fn get_coerce_type_for_case_when(
when_types: &[DataType],
case_type: &DataType,
) -> Option<DataType> {
fold_coerce(case_type, when_types, comparison_coercion)
}
pub fn get_coerce_type_for_case_expression(
then_types: &[DataType],
else_type: Option<&DataType>,
) -> Option<DataType> {
let (initial_type, remaining) = match else_type {
None => then_types.split_first()?,
Some(data_type) => (data_type, then_types),
};
fold_coerce(initial_type, remaining, type_union_coercion)
}