use super::*;
use datafusion::arrow::datatypes::{Field, Schema};
use datafusion::common::ScalarValue;
use datafusion::logical_expr::{case, col, expr::Cast, lit, when};
use std::sync::Arc;
fn nullable_schema(
fields: impl IntoIterator<Item = (&'static str, DataType)>,
) -> DFSchema {
DFSchema::try_from(Schema::new(
fields
.into_iter()
.map(|(name, data_type)| Field::new(name, data_type, true))
.collect::<Vec<_>>(),
))
.unwrap()
}
fn ree(value: DataType) -> DataType {
DataType::RunEndEncoded(
Arc::new(Field::new("run_ends", DataType::Int32, false)),
Arc::new(Field::new("values", value, true)),
)
}
fn dict(value: DataType) -> DataType {
DataType::Dictionary(Box::new(DataType::Int32), Box::new(value))
}
fn map_of(value: DataType) -> DataType {
DataType::Map(
Arc::new(Field::new(
"entries",
DataType::Struct(
vec![
Field::new("key", DataType::Utf8, false),
Field::new("value", value, true),
]
.into(),
),
false,
)),
false,
)
}
fn simple_case(base: Expr, probe: Expr) -> Expr {
case(base)
.when(probe, lit(1_i64))
.otherwise(lit(0_i64))
.unwrap()
}
#[test]
fn coalesce_preparation_rejects_dictionary_bearing_results() {
let dictionary =
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8));
let nested = DataType::new_list(dictionary.clone(), true);
let coalesce = datafusion::functions::core::coalesce();
for (data_type, safe) in [
(dictionary, false),
(nested, false),
(DataType::Utf8, true),
(DataType::Int64, true),
] {
let schema = nullable_schema([("a", data_type.clone()), ("b", data_type)]);
let expr = coalesce.call(vec![col("a"), col("b")]);
assert_eq!(can_precompute(&expr, &schema), safe);
}
}
#[test]
fn dictionary_equality_requires_comparable_values_after_one_lookup() {
let strings = dict(DataType::Utf8);
let nested = dict(strings.clone());
let schema = nullable_schema([("strings", strings), ("nested", nested)]);
for (left, right, safe) in [
("strings", "strings", true),
("nested", "nested", false),
("strings", "nested", false),
("nested", "strings", false),
] {
assert_eq!(can_precompute(&col(left).eq(col(right)), &schema), safe);
}
}
#[test]
fn dictionary_between_and_in_list_require_comparable_values_after_one_lookup() {
for (value_type, safe) in [
(DataType::Int64, true),
(dict(DataType::Int64), false),
(DataType::new_list(DataType::Int64, true), false),
] {
let schema = nullable_schema([("d", dict(value_type))]);
for expr in [
col("d").between(col("d"), col("d")),
col("d").in_list(vec![col("d")], false),
] {
assert_eq!(can_precompute(&expr, &schema), safe, "{expr}");
assert_eq!(can_discard_scalar(&expr, Some(&schema)), safe, "{expr}");
}
}
}
#[test]
fn between_preparation_checks_all_operands_against_the_final_type() {
let schema = nullable_schema([
("i", DataType::Int64),
("f", DataType::Float64),
("d", DataType::Decimal128(15, 2)),
("wide", DataType::Decimal128(38, 0)),
("s", DataType::Utf8),
]);
for (value, low, high, safe) in [
(lit(ScalarValue::Null), lit(1_i32), col("i"), true),
(lit(ScalarValue::Null), col("s"), col("i"), false),
(lit(ScalarValue::Null), col("i"), col("s"), false),
(col("i"), lit(1_i32), col("f"), true),
(col("d"), lit(1_i32), col("i"), true),
(col("i"), col("f"), col("d"), false),
(col("i"), col("wide"), col("d"), false),
] {
for negated in [false, true] {
let expr = Expr::Between(Between::new(
Box::new(value.clone()),
negated,
Box::new(low.clone()),
Box::new(high.clone()),
));
assert_eq!(can_precompute(&expr, &schema), safe, "{expr}");
}
}
}
#[test]
fn integer_remainder_requires_a_nonzero_literal_and_safe_operands() {
let schema = DFSchema::try_from(Schema::new(vec![
Field::new("ord", DataType::Int32, true),
Field::new("text", DataType::Utf8, false),
]))
.unwrap();
for (expr, safe) in [
((col("ord") % lit(2_i64)).eq(lit(0_i64)), true),
(lit(i64::MIN) % lit(-1_i64), true),
(lit(u64::MAX) % lit(3_u64), true),
(col("ord") % lit(0_i32), false),
(col("ord") % col("ord"), false),
(col("text") % lit(2_i64), false),
(
Expr::Cast(Cast::new(Box::new(col("text")), DataType::Int64)) % lit(2_i64),
false,
),
] {
assert_eq!(can_precompute(&expr, &schema), safe, "{expr}");
}
}
#[test]
fn decimal_comparisons_distinguish_a_fitting_literal_from_an_unbounded_column() {
let schema = nullable_schema([
("amount", DataType::Decimal128(15, 2)),
("limit", DataType::Float64),
]);
assert!(can_precompute(&col("amount").lt(lit(0.02_f64)), &schema));
assert!(!can_precompute(&col("amount").lt(col("limit")), &schema));
assert!(cast_is_safe(
&DataType::Decimal128(15, 2),
&DataType::Decimal128(17, 4)
));
assert!(!cast_is_safe(
&DataType::Decimal128(15, 2),
&DataType::Decimal128(16, 4)
));
}
#[test]
fn in_list_preparation_checks_every_cast_to_the_final_type() {
let timestamp = |zone: Option<&str>| {
lit(ScalarValue::TimestampNanosecond(
Some(0),
zone.map(Into::into),
))
};
let null = || lit(ScalarValue::Null);
for (probe, values, safe) in [
(lit(1_i32), vec![lit(2_i64), null()], true),
(null(), vec![lit("bad"), lit(1_i64)], false),
(null(), vec![lit(1_i64), lit("bad")], false),
(timestamp(None), vec![timestamp(None)], true),
(timestamp(Some("UTC")), vec![timestamp(Some("UTC"))], true),
(timestamp(None), vec![timestamp(Some("UTC"))], false),
(timestamp(Some("UTC")), vec![timestamp(None)], false),
(null(), vec![timestamp(None), timestamp(Some("UTC"))], false),
(
timestamp(Some("UTC")),
vec![timestamp(Some("+08:00"))],
false,
),
] {
let expr = probe.in_list(values, false);
assert_eq!(can_precompute(&expr, &DFSchema::empty()), safe, "{expr}");
}
}
#[test]
fn decimal_preparation_requires_bounded_arithmetic_and_safe_children() {
let decimal =
|precision, scale| lit(ScalarValue::Decimal128(Some(1), precision, scale));
let cast = |value, data_type| Expr::Cast(Cast::new(Box::new(value), data_type));
for (value, safe) in [
(decimal(37, 2) + decimal(37, 2), true),
(decimal(37, 2) - decimal(37, 2), true),
(decimal(38, 2) + decimal(37, 2), false),
(decimal(15, 2) + decimal(15, 3), true),
(decimal(15, 2) - decimal(15, 3), true),
(decimal(37, 0) + decimal(37, 2), false),
(decimal(19, 2) * decimal(19, 2), true),
(decimal(20, 0) * decimal(19, 0), false),
(
decimal(19, 2) * lit(ScalarValue::Decimal128(None, 19, 2)),
true,
),
(decimal(19, 2) * decimal(19, 2) + decimal(38, 4), false),
(decimal(15, -1) + decimal(15, -1), false),
(decimal(15, i8::MIN) + decimal(15, i8::MIN), false),
(decimal(15, i8::MIN) * decimal(15, 2), false),
(lit(1_i64) + lit(2_i64), false),
(decimal(15, 2) / decimal(15, 2), false),
(decimal(15, 2) % decimal(15, 2), false),
(
cast(lit("bad"), DataType::Decimal128(15, 2)) + decimal(15, 2),
false,
),
(
cast(decimal(14, 2), DataType::Decimal128(15, 2)) + decimal(15, 2),
true,
),
((decimal(15, 2) + decimal(15, 2)) + decimal(15, 2), true),
] {
assert_eq!(can_precompute(&value, &DFSchema::empty()), safe, "{value}");
assert_eq!(
can_precompute(&value.clone().gt(lit(0_i64)), &DFSchema::empty()),
safe,
"comparison containing {value}"
);
}
}
#[test]
fn nested_float_preparation_keeps_width_and_rejects_mixed_arithmetic() {
assert!(can_precompute(
&((lit(2_f32) * lit(3_f32)) + lit(1_f32)),
&DFSchema::empty()
));
for (value, expected_type) in [
(lit(2_f32), DataType::Float32),
(lit(2_f64), DataType::Float64),
] {
let nested = (value.clone() * value.clone()) + (value.clone() - value.clone());
assert!(can_precompute(&nested, &DFSchema::empty()));
assert_eq!(nested.get_type(&DFSchema::empty()).unwrap(), expected_type);
assert!(can_precompute(
&nested.gt(value.clone()),
&DFSchema::empty()
));
assert!(can_precompute(
&(value.clone() / value.clone()),
&DFSchema::empty()
));
assert!(can_precompute(&(value.clone() % value), &DFSchema::empty()));
}
assert!(can_precompute(
&(lit(1_f64) / lit(0_f64)),
&DFSchema::empty()
));
assert!(can_precompute(
&(lit(1_f64) % lit(0_f64)),
&DFSchema::empty()
));
assert!(!can_precompute(
&(lit(1_f32) / lit(1_f64)),
&DFSchema::empty()
));
assert!(!can_precompute(
&(lit(1_f32) + lit(1_f64)),
&DFSchema::empty()
));
assert!(!can_precompute(
&(lit(1_f64) * lit(1_i64)),
&DFSchema::empty()
));
assert!(!can_precompute(
&(lit(1_i64) / lit(2_i64)),
&DFSchema::empty()
));
}
#[test]
fn nested_decimal_input_uses_coerced_child_types() {
let schema = nullable_schema([
("price", DataType::Decimal128(15, 2)),
("discount", DataType::Decimal128(15, 2)),
]);
let net = col("price") * (lit(1_i64) - col("discount"));
assert!(can_precompute(&net, &schema));
assert!(can_precompute(&net.clone().gt(lit(100_i64)), &schema));
assert_eq!(net.get_type(&schema).unwrap(), DataType::Decimal128(38, 4));
assert!(!can_precompute(&(net * col("price")), &schema));
}
#[test]
fn string_preparation_rejects_narrower_storage() {
use DataType::{LargeUtf8, Utf8, Utf8View};
for scalar in [Utf8, LargeUtf8, Utf8View] {
assert!(cast_is_safe(&scalar, &scalar));
}
for (source, target, safe) in [
(Utf8, LargeUtf8, true),
(Utf8, Utf8View, true),
(Utf8View, LargeUtf8, true),
(LargeUtf8, Utf8, false),
(LargeUtf8, Utf8View, false),
(Utf8View, Utf8, false),
(DataType::Decimal128(15, 2), DataType::Float64, true),
(DataType::Decimal128(38, 0), DataType::Float64, true),
(DataType::Decimal128(15, -1), DataType::Float64, false),
(DataType::Float64, DataType::Decimal128(15, 2), false),
] {
assert_eq!(cast_is_safe(&source, &target), safe, "{source} → {target}");
}
}
#[test]
fn like_preparation_requires_safe_string_coercion_literal_pattern_and_no_escape() {
let schema = nullable_schema([
("instruct", DataType::Utf8View),
("pat", DataType::Utf8),
("raw", DataType::Binary),
]);
let make_like = |expr, pattern, escape_char, case_insensitive| {
Expr::Like(Like::new(
false,
Box::new(expr),
Box::new(pattern),
escape_char,
case_insensitive,
))
};
for (expr, safe) in [
(
make_like(col("instruct"), lit("%DELIVER%"), None, false),
true,
),
(
make_like(col("instruct"), lit("%deliver%"), None, true),
true,
),
(
make_like(col("instruct"), lit(ScalarValue::Utf8(None)), None, false),
true,
),
(
make_like(col("instruct"), lit(ScalarValue::Null), None, false),
true,
),
(make_like(col("instruct"), col("pat"), None, false), false),
(
make_like(col("instruct"), lit("%DELIVER%"), Some('\\'), false),
false,
),
(make_like(col("raw"), lit("%DELIVER%"), None, false), false),
] {
assert_eq!(can_precompute(&expr, &schema), safe, "{expr}");
}
}
#[test]
fn scalar_function_preparation_admits_only_proven_infallible_builtins() {
use datafusion::logical_expr::{ScalarUDF, Volatility, create_udf};
let schema = nullable_schema([
("mode", DataType::Utf8View),
("large_text", DataType::LargeUtf8),
("raw_bytes", DataType::Binary),
("pos", DataType::Int64),
("u_pos", DataType::UInt64),
("ratio", DataType::Float64),
("amount", DataType::Decimal128(15, 2)),
("dict_str", dict(DataType::Utf8)),
("day", DataType::Date32),
("day64", DataType::Date64),
("ts_naive", DataType::Timestamp(TimeUnit::Microsecond, None)),
(
"ts_utc",
DataType::Timestamp(TimeUnit::Microsecond, Some("UTC".into())),
),
("part_name", DataType::Utf8),
]);
let substr = datafusion::functions::unicode::substr();
let char_len = datafusion::functions::unicode::character_length();
let octet_len = datafusion::functions::string::octet_length();
let lower = datafusion::functions::string::lower();
let upper = datafusion::functions::string::upper();
let btrim = datafusion::functions::string::btrim();
let ltrim = datafusion::functions::string::ltrim();
let rtrim = datafusion::functions::string::rtrim();
let starts_with = datafusion::functions::string::starts_with();
let ends_with = datafusion::functions::string::ends_with();
let contains = datafusion::functions::string::contains();
let abs = datafusion::functions::math::abs();
let coalesce = datafusion::functions::core::coalesce();
let date_part = datafusion::functions::datetime::date_part();
let fake_substr: ScalarUDF = create_udf(
"substr",
vec![DataType::Utf8View, DataType::Int64, DataType::Int64],
DataType::Utf8View,
Volatility::Immutable,
Arc::new(|_| unreachable!()),
);
for (expr, safe) in [
(
substr
.call(vec![col("mode"), lit(1_i64), lit(1_i64)])
.in_list(vec![lit("A"), lit("R"), lit("S")], false),
true,
),
(substr.call(vec![col("mode"), lit(2_i32)]), true),
(substr.call(vec![col("mode"), lit(1_i64), lit(0_i64)]), true),
(
substr.call(vec![col("mode"), lit(ScalarValue::Null), lit(1_i64)]),
true,
),
(
substr.call(vec![col("mode"), lit(1_i64), lit(-1_i64)]),
false,
),
(
substr.call(vec![col("mode"), lit(i64::MIN), lit(1_i64)]),
false,
),
(
substr.call(vec![col("mode"), col("pos"), lit(1_i64)]),
false,
),
(
Expr::ScalarFunction(ScalarFunction::new_udf(
Arc::new(fake_substr),
vec![col("mode"), lit(1_i64), lit(1_i64)],
)),
false,
),
(
coalesce
.call(vec![col("mode"), lit("NONE")])
.not_eq(lit("RAIL")),
true,
),
(coalesce.call(vec![col("amount"), lit(0_i64)]), true),
(coalesce.call(vec![col("mode"), lit(1_i64)]), false),
(coalesce.call(vec![col("ts_naive"), col("ts_utc")]), false),
(coalesce.call(vec![]), false),
(
date_part
.call(vec![lit("YEAR"), col("day")])
.eq(lit(1992_i32)),
true,
),
(
date_part
.call(vec![lit("month"), col("day")])
.lt_eq(lit(6_i32)),
true,
),
(date_part.call(vec![lit("year"), col("day")]), true),
(date_part.call(vec![lit(" year"), col("day")]), false),
(date_part.call(vec![lit("year "), col("day")]), false),
(date_part.call(vec![lit("day"), col("day64")]), true),
(date_part.call(vec![lit("hour"), col("ts_naive")]), true),
(date_part.call(vec![lit("year"), col("ts_utc")]), false),
(date_part.call(vec![lit("year"), col("mode")]), false),
(date_part.call(vec![lit("epoch"), col("day")]), false),
(
date_part.call(vec![lit("nanosecond"), col("ts_naive")]),
false,
),
(date_part.call(vec![lit("bogus"), col("day")]), false),
(date_part.call(vec![col("part_name"), col("day")]), false),
(date_part.call(vec![lit("quarter"), col("day")]), true),
(date_part.call(vec![lit("isoyear"), col("day")]), true),
(date_part.call(vec![lit("week"), col("day")]), true),
(date_part.call(vec![lit("dow"), col("day")]), true),
(date_part.call(vec![lit("isodow"), col("day")]), true),
(date_part.call(vec![lit("doy"), col("day")]), true),
(date_part.call(vec![lit("quarters"), col("day")]), true),
(date_part.call(vec![lit("isoweek"), col("day")]), true),
(date_part.call(vec![lit("dayofweek"), col("day")]), true),
(date_part.call(vec![lit("dow1"), col("day")]), true),
(date_part.call(vec![lit("dayofweek1"), col("day")]), true),
(date_part.call(vec![lit("isodow0"), col("day")]), true),
(date_part.call(vec![lit("dayofyear"), col("day")]), true),
(char_len.call(vec![col("mode")]).gt_eq(lit(20_i32)), true),
(char_len.call(vec![col("large_text")]).gt(lit(5_i64)), true),
(char_len.call(vec![col("part_name")]), true),
(char_len.call(vec![col("dict_str")]), false),
(char_len.call(vec![col("raw_bytes")]), false),
(octet_len.call(vec![col("mode")]).gt(lit(0_i32)), true),
(octet_len.call(vec![col("raw_bytes")]), true),
(octet_len.call(vec![col("dict_str")]), false),
(lower.call(vec![col("mode")]).eq(lit("air")), true),
(upper.call(vec![col("mode")]), true),
(lower.call(vec![col("part_name")]), true),
(upper.call(vec![col("part_name")]), true),
(lower.call(vec![col("large_text")]), true),
(upper.call(vec![col("large_text")]), true),
(lower.call(vec![col("dict_str")]), false),
(upper.call(vec![col("pos")]), false),
(btrim.call(vec![col("mode")]), true),
(ltrim.call(vec![col("mode"), lit(" ")]), true),
(rtrim.call(vec![col("part_name"), lit("x")]), true),
(btrim.call(vec![col("part_name"), col("mode")]), false),
(btrim.call(vec![col("dict_str")]), false),
(starts_with.call(vec![col("mode"), lit("AIR")]), true),
(ends_with.call(vec![col("part_name"), lit("1")]), true),
(contains.call(vec![col("mode"), col("part_name")]), true),
(contains.call(vec![col("mode"), col("dict_str")]), false),
(abs.call(vec![col("ratio")]).gt(lit(50000.0_f64)), true),
(abs.call(vec![col("u_pos")]), true),
(abs.call(vec![col("amount")]), true),
(abs.call(vec![lit(ScalarValue::Null)]), true),
(abs.call(vec![col("pos")]), false),
(abs.call(vec![col("mode")]), false),
] {
assert_eq!(can_precompute(&expr, &schema), safe, "{expr}");
}
}
#[test]
fn run_end_encoded_comparisons_allow_at_most_one_ree_layer() {
for (data_type, safe) in [
(ree(DataType::Int64), true),
(ree(dict(DataType::Int64)), true),
(ree(ree(DataType::Int64)), false),
(ree(dict(dict(DataType::Int64))), false),
(ree(dict(ree(DataType::Int64))), false),
(ree(DataType::new_list(DataType::Int64, true)), false),
(dict(ree(DataType::Int64)), false),
] {
assert_eq!(
comparison_type_is_safe(&data_type, false),
safe,
"{data_type}"
);
assert_eq!(
comparison_type_is_safe(&data_type, true),
safe,
"{data_type}"
);
let schema = nullable_schema([("r", data_type.clone())]);
for expr in [col("r").eq(col("r")), col("r").between(col("r"), col("r"))] {
assert_eq!(can_precompute(&expr, &schema), safe, "{data_type}: {expr}");
assert_eq!(
can_discard_scalar(&expr, Some(&schema)),
safe,
"{data_type}: {expr}"
);
}
let simple_case = simple_case(col("r"), col("r"));
for expr in [col("r").in_list(vec![col("r")], false), simple_case] {
assert!(!can_precompute(&expr, &schema), "{data_type}: {expr}");
assert!(
!can_discard_scalar(&expr, Some(&schema)),
"{data_type}: {expr}"
);
}
}
for run_ends_type in [DataType::Int16, DataType::Int32] {
let run_ends_field = Arc::new(Field::new("run_ends", run_ends_type, false));
let values_field = Arc::new(Field::new("values", DataType::Int64, true));
let ree_type = DataType::RunEndEncoded(
Arc::clone(&run_ends_field),
Arc::clone(&values_field),
);
let schema = nullable_schema([("r", ree_type)]);
let ree_lit = lit(ScalarValue::RunEndEncoded(
run_ends_field,
values_field,
Box::new(ScalarValue::Int64(Some(1))),
));
let lit_simple_case = simple_case(ree_lit.clone(), col("r"));
for expr in [
ree_lit.clone(),
ree_lit.clone().eq(col("r")),
ree_lit.in_list(vec![col("r")], false),
lit_simple_case,
] {
assert!(!can_precompute(&expr, &schema), "ree lit: {expr}");
assert!(
!can_discard_scalar(&expr, Some(&schema)),
"ree lit (discard): {expr}"
);
}
}
}
#[test]
fn case_expressions_precompute_only_when_every_branch_is_infallible() {
let schema = DFSchema::try_from(Schema::new(vec![
Field::new("price", DataType::Decimal128(15, 2), false),
Field::new("qty", DataType::Decimal128(15, 2), false),
Field::new("discount", DataType::Decimal128(15, 2), false),
Field::new("mode", DataType::Utf8View, false),
Field::new("k", DataType::Int64, false),
Field::new(
"dict",
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
true,
),
]))
.unwrap();
let searched_case = when(
col("mode").in_list(vec![lit("AIR"), lit("REG AIR")], false),
lit(2_i64),
)
.otherwise(lit(1_i64))
.unwrap();
assert!(can_precompute(
&searched_case.clone().eq(lit(2_i64)),
&schema
));
let a_tier = searched_case
.eq(lit(2_i64))
.and((col("k") % lit(3_i64)).not_eq(lit(0_i64)));
assert!(can_precompute(&a_tier, &schema), "a_tier: {a_tier}");
let decimal_case = when(
col("qty").gt(lit(25_i64)),
col("price") * (lit(1_i64) - col("discount")),
)
.otherwise(col("price"))
.unwrap();
assert!(can_precompute(
&decimal_case.clone().gt(lit(20000_i64)),
&schema
));
let b_tier = datafusion::functions::core::coalesce()
.call(vec![col("discount"), lit(0_i64)])
.lt_eq(lit(0.06_f64))
.and(decimal_case.gt(lit(20000_i64)));
assert!(can_precompute(&b_tier, &schema), "b_tier: {b_tier}");
let simple_case = case(col("k"))
.when(lit(1_i64), lit(10_i64))
.when(lit(2_i64), lit(20_i64))
.otherwise(lit(0_i64))
.unwrap();
assert!(can_precompute(&simple_case.gt(lit(5_i64)), &schema));
let fallible_case = when(col("k").gt(lit(0_i64)), lit(10_i64) / col("k"))
.otherwise(lit(0_i64))
.unwrap();
assert!(!can_precompute(&fallible_case.gt(lit(1_i64)), &schema));
let dict_case = when(col("k").gt(lit(0_i64)), col("dict"))
.otherwise(col("dict"))
.unwrap();
assert!(!can_precompute(&dict_case.is_not_null(), &schema));
let coercion_schema = nullable_schema([
("str_col", DataType::Utf8),
("int_col", DataType::Int64),
("i32_col", DataType::Int32),
("dec38_2_col", DataType::Decimal128(38, 2)),
("dec10_5_col", DataType::Decimal128(10, 5)),
("flag", DataType::Boolean),
("f64_col", DataType::Float64),
]);
let null_base_mixed_when = case(lit(ScalarValue::Null))
.when(col("str_col"), lit(1_i64))
.when(col("int_col"), lit(2_i64))
.otherwise(lit(0_i64))
.unwrap();
assert!(
!can_precompute(&null_base_mixed_when, &coercion_schema),
"{null_base_mixed_when}"
);
let decimal_scale_mixed_when = case(col("i32_col"))
.when(col("dec38_2_col"), lit(1_i64))
.when(col("dec10_5_col"), lit(2_i64))
.otherwise(lit(0_i64))
.unwrap();
assert!(
!can_precompute(&decimal_scale_mixed_when, &coercion_schema),
"{decimal_scale_mixed_when}"
);
let string_float_then_else = when(col("flag"), lit("1"))
.otherwise(col("f64_col"))
.unwrap()
.eq(lit(1_i64));
assert!(
!can_precompute(&string_float_then_else, &coercion_schema),
"{string_float_then_else}"
);
}
#[test]
fn map_comparisons_allow_equality_only_and_reject_ordering() {
let map_type = map_of(DataType::Int64);
let struct_with_map =
DataType::Struct(vec![Field::new("m", map_type.clone(), true)].into());
let list_of_map = DataType::new_list(map_type.clone(), true);
let supported_struct = DataType::Struct(
vec![
Field::new("a", DataType::Int64, true),
Field::new("b", DataType::Utf8, true),
]
.into(),
);
let supported_list = DataType::new_list(DataType::Int64, true);
let schema = nullable_schema([
("m", map_type.clone()),
("s_map", struct_with_map.clone()),
("l_map", list_of_map.clone()),
("s_ok", supported_struct.clone()),
("l_ok", supported_list.clone()),
]);
let binary = |name: &str, op: Operator| {
Expr::BinaryExpr(BinaryExpr::new(
Box::new(col(name)),
op,
Box::new(col(name)),
))
};
for (name, data_type) in [
("m", &map_type),
("s_map", &struct_with_map),
("l_map", &list_of_map),
] {
assert!(comparison_type_is_safe(data_type, false), "{name}");
assert!(!comparison_type_is_safe(data_type, true), "{name}");
let simple_case = simple_case(col(name), col(name));
for expr in [
col(name).eq(col(name)),
col(name).not_eq(col(name)),
binary(name, Operator::IsDistinctFrom),
binary(name, Operator::IsNotDistinctFrom),
col(name).in_list(vec![col(name)], false),
simple_case,
] {
assert!(can_precompute(&expr, &schema), "{name}: {expr}");
assert!(can_discard_scalar(&expr, Some(&schema)), "{name}: {expr}");
}
for expr in [
col(name).lt(col(name)),
col(name).lt_eq(col(name)),
col(name).gt(col(name)),
col(name).gt_eq(col(name)),
col(name).between(col(name), col(name)),
] {
assert!(!can_precompute(&expr, &schema), "{name}: {expr}");
assert!(!can_discard_scalar(&expr, Some(&schema)), "{name}: {expr}");
}
}
for (name, data_type) in [("s_ok", &supported_struct), ("l_ok", &supported_list)] {
assert!(comparison_type_is_safe(data_type, false), "{name}");
assert!(comparison_type_is_safe(data_type, true), "{name}");
for expr in [
col(name).eq(col(name)),
col(name).lt(col(name)),
col(name).between(col(name), col(name)),
col(name).in_list(vec![col(name)], false),
] {
assert!(can_precompute(&expr, &schema), "{name}: {expr}");
assert!(can_discard_scalar(&expr, Some(&schema)), "{name}: {expr}");
}
}
}
#[test]
fn nested_container_comparisons_reject_unsupported_children() {
use datafusion::arrow::datatypes::{UnionFields, UnionMode};
let list_view =
|value: DataType| DataType::ListView(Arc::new(Field::new("item", value, true)));
let large_list_view = |value: DataType| {
DataType::LargeListView(Arc::new(Field::new("item", value, true)))
};
let union_type = DataType::Union(
UnionFields::from_iter([(
0,
Arc::new(Field::new("value", DataType::Int64, true)),
)]),
UnionMode::Sparse,
);
let rejected_types = [
("list_view", list_view(DataType::Int64)),
("large_list_view", large_list_view(DataType::Int64)),
(
"struct_list_view",
DataType::Struct(
vec![Field::new("lv", list_view(DataType::Int64), true)].into(),
),
),
(
"list_large_list_view",
DataType::new_list(large_list_view(DataType::Int64), true),
),
("map_list_view", map_of(list_view(DataType::Int64))),
(
"struct_ree",
DataType::Struct(vec![Field::new("r", ree(DataType::Int64), true)].into()),
),
("list_ree", DataType::new_list(ree(DataType::Int64), true)),
(
"large_list_ree",
DataType::new_large_list(ree(DataType::Int64), true),
),
(
"fixed_size_list_ree",
DataType::new_fixed_size_list(ree(DataType::Int64), 2, true),
),
("map_ree", map_of(ree(DataType::Int64))),
(
"struct_dict",
DataType::Struct(vec![Field::new("d", dict(DataType::Utf8), true)].into()),
),
(
"struct_double_dict",
DataType::Struct(
vec![Field::new("dd", dict(dict(DataType::Utf8)), true)].into(),
),
),
(
"list_double_dict",
DataType::new_list(dict(dict(DataType::Int64)), true),
),
("map_double_dict", map_of(dict(dict(DataType::Int64)))),
("union", union_type.clone()),
(
"struct_union",
DataType::Struct(vec![Field::new("u", union_type, true)].into()),
),
];
for (label, data_type) in rejected_types {
assert!(!comparison_type_is_safe(&data_type, false), "{label}");
assert!(!comparison_type_is_safe(&data_type, true), "{label}");
let schema = nullable_schema([("x", data_type)]);
let simple_case = simple_case(col("x"), col("x"));
for expr in [
col("x").eq(col("x")),
col("x").lt(col("x")),
col("x").between(col("x"), col("x")),
col("x").in_list(vec![col("x")], false),
simple_case,
] {
assert!(!can_precompute(&expr, &schema), "{label}: {expr}");
assert!(!can_discard_scalar(&expr, Some(&schema)), "{label}: {expr}");
}
}
}
#[test]
fn run_end_encoded_results_are_rejected_in_case_coalesce_and_null_casts() {
let ree_i16 = DataType::RunEndEncoded(
Arc::new(Field::new("run_ends", DataType::Int16, false)),
Arc::new(Field::new("values", DataType::Int64, true)),
);
let ree_non_null = DataType::RunEndEncoded(
Arc::new(Field::new("run_ends", DataType::Int32, false)),
Arc::new(Field::new("values", DataType::Int64, false)),
);
let list_ree = DataType::new_list(ree_i16.clone(), true);
let struct_ree =
DataType::Struct(vec![Field::new("r", ree_i16.clone(), true)].into());
let coalesce = datafusion::functions::core::coalesce();
for (label, data_type) in [
("ree_i16", ree_i16.clone()),
("ree_non_null", ree_non_null),
("list_ree", list_ree),
("struct_ree", struct_ree),
] {
let schema = nullable_schema([
("flag", DataType::Boolean),
("a", data_type.clone()),
("b", data_type.clone()),
]);
let case_expr = when(col("flag"), col("a")).end().unwrap();
let coalesce_expr = coalesce.call(vec![col("a"), col("b")]);
let null_cast = Expr::Cast(Cast::new(
Box::new(lit(ScalarValue::Null)),
data_type.clone(),
));
assert!(!can_precompute(&case_expr, &schema), "{label}: CASE");
assert!(
!can_precompute(&coalesce_expr, &schema),
"{label}: COALESCE"
);
assert!(
!can_precompute(&null_cast, &schema),
"{label}: CAST(NULL AS REE)"
);
assert!(
!cast_is_safe(&DataType::Null, &data_type),
"{label}: Null -> {data_type}"
);
}
assert!(cast_is_safe(&ree_i16, &ree_i16));
assert!(cast_is_safe(&DataType::Null, &DataType::Int64));
assert!(cast_is_safe(&DataType::Null, &DataType::Boolean));
}
#[test]
fn uncoerced_null_type_is_rejected_in_boolean_positions() {
let schema =
nullable_schema([("null_col", DataType::Null), ("flag", DataType::Boolean)]);
let cast_bool = |expr| Expr::Cast(Cast::new(Box::new(expr), DataType::Boolean));
for (label, expr, safe) in [
("NOT null_col", Expr::Not(Box::new(col("null_col"))), false),
(
"NOT untyped NULL",
Expr::Not(Box::new(lit(ScalarValue::Null))),
false,
),
(
"CASE WHEN null_col",
when(col("null_col"), lit(1_i64))
.otherwise(lit(0_i64))
.unwrap(),
false,
),
(
"CASE WHEN untyped NULL",
when(lit(ScalarValue::Null), lit(1_i64))
.otherwise(lit(0_i64))
.unwrap(),
false,
),
("null_col AND flag", col("null_col").and(col("flag")), false),
(
"null_col IS TRUE",
Expr::IsTrue(Box::new(col("null_col"))),
false,
),
("NOT flag", Expr::Not(Box::new(col("flag"))), true),
(
"NOT Boolean(None)",
Expr::Not(Box::new(lit(ScalarValue::Boolean(None)))),
true,
),
(
"CASE WHEN Boolean(None)",
when(lit(ScalarValue::Boolean(None)), lit(1_i64))
.otherwise(lit(0_i64))
.unwrap(),
true,
),
(
"NOT CAST(null_col AS BOOLEAN)",
Expr::Not(Box::new(cast_bool(col("null_col")))),
true,
),
] {
assert_eq!(can_precompute(&expr, &schema), safe, "{label}: {expr}");
}
}
#[test]
fn cast_is_safe_validates_decimal_and_null_target_bounds() {
use datafusion::arrow::datatypes::{UnionFields, UnionMode};
let union_type = DataType::Union(
UnionFields::from_iter([(
0,
Arc::new(Field::new("value", DataType::Int64, true)),
)]),
UnionMode::Sparse,
);
let invalid_dict =
DataType::Dictionary(Box::new(DataType::Utf8), Box::new(DataType::Int64));
let valid_dict = dict(DataType::Utf8);
for (source, target, safe) in [
(
DataType::Decimal128(10, 2),
DataType::Decimal128(12, 4),
true,
),
(
DataType::Decimal128(10, 2),
DataType::Decimal128(39, 2),
false,
),
(
DataType::Decimal128(10, 2),
DataType::Decimal128(0, 0),
false,
),
(
DataType::Decimal128(10, 2),
DataType::Decimal128(10, 11),
false,
),
(
DataType::Decimal128(0, 0),
DataType::Decimal128(10, 2),
false,
),
(DataType::Int32, DataType::Decimal128(10, 0), true),
(DataType::Int32, DataType::Decimal128(39, 0), false),
(DataType::Int32, DataType::Decimal128(10, 11), false),
(DataType::Int32, DataType::Decimal128(10, -1), false),
(DataType::Null, DataType::Decimal128(38, 2), true),
(DataType::Null, DataType::Decimal128(39, 0), false),
(DataType::Null, DataType::Decimal128(0, 0), false),
(DataType::Null, DataType::Decimal128(10, 11), false),
(DataType::Null, DataType::FixedSizeBinary(-1), false),
(
DataType::Null,
DataType::Time32(TimeUnit::Nanosecond),
false,
),
(DataType::Null, invalid_dict, false),
(DataType::Null, valid_dict, true),
(DataType::Null, union_type, false),
] {
assert_eq!(cast_is_safe(&source, &target), safe, "{source} -> {target}");
}
let schema = nullable_schema([("i", DataType::Int32)]);
let bad_int_cast =
Expr::Cast(Cast::new(Box::new(col("i")), DataType::Decimal128(39, 0)));
let bad_null_cast = Expr::Cast(Cast::new(
Box::new(lit(ScalarValue::Null)),
DataType::Decimal128(39, 0),
));
assert!(!can_precompute(&bad_int_cast, &schema));
assert!(!can_precompute(&bad_null_cast, &schema));
}
#[test]
fn starts_with_preparation_probes_escaped_like_regex_for_wildcard_literals() {
let schema = nullable_schema([
("text", DataType::Utf8View),
("large_text", DataType::LargeUtf8),
("prefix", DataType::Utf8),
]);
let starts_with = datafusion::functions::string::starts_with();
let lower = datafusion::functions::string::lower();
let coalesce = datafusion::functions::core::coalesce();
let filler = "a".repeat(1_000_000);
for (label, expr, safe) in [
(
"normal literal",
starts_with.call(vec![col("text"), lit("AIR")]),
true,
),
(
"oversized literal without LIKE metacharacters",
starts_with.call(vec![col("text"), lit(filler.clone())]),
true,
),
(
"short wildcard/escape Utf8 literal",
starts_with.call(vec![col("text"), lit("a_b%c\\d")]),
true,
),
(
"short aliased wildcard Utf8View literal",
starts_with.call(vec![
col("text"),
lit(ScalarValue::Utf8View(Some("a_b%c\\d".into()))).alias("p"),
]),
true,
),
(
"short wildcard LargeUtf8 literal",
starts_with.call(vec![
col("large_text"),
lit(ScalarValue::LargeUtf8(Some("a_b%c\\d".into()))),
]),
true,
),
(
"null literal prefix",
starts_with.call(vec![col("text"), lit(ScalarValue::Utf8(None))]),
true,
),
(
"null Utf8View literal prefix",
starts_with.call(vec![col("text"), lit(ScalarValue::Utf8View(None))]),
true,
),
(
"non-literal column prefix",
starts_with.call(vec![col("text"), col("prefix")]),
false,
),
(
"aliased non-literal column prefix",
starts_with.call(vec![col("text"), col("prefix").alias("p")]),
false,
),
(
"oversized underscore Utf8 literal",
starts_with.call(vec![col("text"), lit(format!("_{filler}"))]),
false,
),
(
"oversized percent LargeUtf8 literal",
starts_with.call(vec![
col("large_text"),
lit(ScalarValue::LargeUtf8(Some(format!("%{filler}")))),
]),
false,
),
(
"oversized aliased backslash Utf8View literal",
starts_with.call(vec![
col("text"),
lit(ScalarValue::Utf8View(Some(format!("\\{filler}")))).alias("p"),
]),
false,
),
(
"constant-foldable function prefix",
starts_with.call(vec![col("text"), lower.call(vec![lit("_abc")])]),
false,
),
(
"constant-foldable cast prefix",
starts_with.call(vec![
col("text"),
Expr::Cast(Cast::new(Box::new(lit("_abc")), DataType::Utf8View)),
]),
false,
),
(
"partially-simplifiable coalesce prefix",
starts_with.call(vec![
col("text"),
coalesce.call(vec![lit("_abc"), col("prefix")]),
]),
false,
),
(
"constant-foldable case prefix",
starts_with.call(vec![
col("text"),
when(lit(true), lit("_abc")).end().unwrap(),
]),
false,
),
] {
assert_eq!(can_precompute(&expr, &schema), safe, "{label}");
assert_eq!(
can_discard_scalar(&expr, Some(&schema)),
safe,
"{label} (discard)"
);
}
}
#[test]
fn union_results_are_rejected_in_case_and_coalesce() {
use datafusion::arrow::datatypes::{UnionFields, UnionMode};
let empty_union = DataType::Union(UnionFields::empty(), UnionMode::Sparse);
let non_null_union = DataType::Union(
UnionFields::from_iter([(
0,
Arc::new(Field::new("value", DataType::Int64, false)),
)]),
UnionMode::Sparse,
);
let nullable_union = DataType::Union(
UnionFields::from_iter([(
0,
Arc::new(Field::new("value", DataType::Int64, true)),
)]),
UnionMode::Dense,
);
let struct_empty_union =
DataType::Struct(vec![Field::new("u", empty_union.clone(), true)].into());
let struct_non_null_union =
DataType::Struct(vec![Field::new("u", non_null_union.clone(), true)].into());
let list_union = DataType::new_list(non_null_union.clone(), true);
let plain_struct =
DataType::Struct(vec![Field::new("i", DataType::Int64, true)].into());
let coalesce = datafusion::functions::core::coalesce();
for (label, data_type, safe) in [
("empty_union", empty_union, false),
("non_null_union", non_null_union, false),
("nullable_union", nullable_union, false),
("struct_empty_union", struct_empty_union, false),
("struct_non_null_union", struct_non_null_union, false),
("list_union", list_union, false),
("plain_struct", plain_struct, true),
] {
let schema = nullable_schema([
("flag", DataType::Boolean),
("a", data_type.clone()),
("b", data_type),
]);
let case_with_else = when(col("flag"), col("a")).otherwise(col("b")).unwrap();
let case_without_else = when(col("flag"), col("a")).end().unwrap();
let coalesce_expr = coalesce.call(vec![col("a"), col("b")]);
for (kind, expr) in [
("CASE with ELSE", case_with_else),
("CASE without ELSE", case_without_else),
("COALESCE", coalesce_expr),
] {
assert_eq!(can_precompute(&expr, &schema), safe, "{label}: {kind}");
assert_eq!(
can_discard_scalar(&expr, Some(&schema)),
safe,
"{label}: {kind} (discard)"
);
}
}
}
#[test]
fn literal_and_null_cast_validate_decimal_bounds_map_nullability_and_fixed_binary() {
use datafusion::arrow::array::ListArray;
use datafusion::arrow::datatypes::i256;
let empty_schema = DFSchema::empty();
let dict_of = |scalar: ScalarValue| {
ScalarValue::Dictionary(Box::new(DataType::Int32), Box::new(scalar))
};
for (label, scalar, safe) in [
("d32 valid", ScalarValue::Decimal32(Some(1), 9, 2), true),
("d32 prec=0", ScalarValue::Decimal32(Some(1), 0, 0), false),
("d32 prec=10", ScalarValue::Decimal32(Some(1), 10, 0), false),
("d32 scale>p", ScalarValue::Decimal32(Some(1), 5, 6), false),
(
"d32 scale<-p",
ScalarValue::Decimal32(Some(1), 5, -6),
false,
),
("d64 valid", ScalarValue::Decimal64(Some(1), 18, 2), true),
("d64 prec=19", ScalarValue::Decimal64(Some(1), 19, 0), false),
(
"d64 scale>p",
ScalarValue::Decimal64(Some(1), 10, 11),
false,
),
("d128 valid", ScalarValue::Decimal128(Some(1), 38, 2), true),
(
"d128 valid neg scale",
ScalarValue::Decimal128(Some(0), 19, -10),
true,
),
(
"d128 prec=39",
ScalarValue::Decimal128(Some(1), 39, 0),
false,
),
("d128 prec=0", ScalarValue::Decimal128(Some(1), 0, 0), false),
(
"d128 scale>p",
ScalarValue::Decimal128(Some(1), 10, 11),
false,
),
(
"d128 scale=i8::MIN",
ScalarValue::Decimal128(Some(1), 15, i8::MIN),
false,
),
(
"d256 valid",
ScalarValue::Decimal256(Some(i256::from(1)), 76, 4),
true,
),
(
"d256 prec=77",
ScalarValue::Decimal256(Some(i256::from(1)), 77, 0),
false,
),
(
"d256 scale>p",
ScalarValue::Decimal256(Some(i256::from(1)), 20, 21),
false,
),
] {
assert_eq!(
scalar_value_type_is_safe(&scalar.data_type()),
safe,
"{label}: type"
);
assert_eq!(
can_precompute(&lit(scalar.clone()), &empty_schema),
safe,
"{label}: direct"
);
assert_eq!(
can_precompute(&lit(dict_of(scalar)), &empty_schema),
safe,
"{label}: dictionary"
);
}
let make_map = |entries_nullable: bool, key_nullable: bool| {
DataType::Map(
Arc::new(Field::new(
"entries",
DataType::Struct(
vec![
Field::new("key", DataType::Utf8, key_nullable),
Field::new("value", DataType::Int64, true),
]
.into(),
),
entries_nullable,
)),
false,
)
};
for (label, map_type, safe) in [
("valid map", make_map(false, false), true),
("nullable entries map", make_map(true, false), false),
("nullable key map", make_map(false, true), false),
("nullable entries and key map", make_map(true, true), false),
] {
assert_eq!(scalar_value_type_is_safe(&map_type), safe, "{label}: type");
assert_eq!(
cast_is_safe(&DataType::Null, &map_type),
safe,
"{label}: null cast"
);
let null_cast = Expr::Cast(Cast::new(
Box::new(lit(ScalarValue::Null)),
map_type.clone(),
));
assert_eq!(
can_precompute(&null_cast, &empty_schema),
safe,
"{label}: CAST(NULL AS Map)"
);
let map_scalar = ScalarValue::try_from(&map_type).unwrap();
assert_eq!(
can_precompute(&lit(map_scalar), &empty_schema),
safe,
"{label}: literal"
);
}
let empty_list = ScalarValue::List(Arc::new(ListArray::new_null(
Arc::new(Field::new("item", DataType::Int64, true)),
0,
)));
let one_row_list = ScalarValue::List(Arc::new(ListArray::new_null(
Arc::new(Field::new("item", DataType::Int64, true)),
1,
)));
for (label, scalar, safe) in [
(
"fixed binary matching len",
ScalarValue::FixedSizeBinary(4, Some(vec![1, 2, 3, 4])),
true,
),
(
"fixed binary null",
ScalarValue::FixedSizeBinary(4, None),
true,
),
(
"fixed binary mismatched len",
ScalarValue::FixedSizeBinary(4, Some(vec![1, 2])),
false,
),
(
"fixed binary negative len",
ScalarValue::FixedSizeBinary(-1, Some(vec![])),
false,
),
("list len=1", one_row_list, true),
("list len=0", empty_list, false),
] {
assert_eq!(
can_precompute(&lit(scalar.clone()), &empty_schema),
safe,
"{label}: direct"
);
assert_eq!(
can_precompute(&lit(dict_of(scalar)), &empty_schema),
safe,
"{label}: dictionary"
);
}
}
#[test]
fn type_bounds_are_validated_in_ordering_case_coalesce_abs_and_octet_length() {
let make_map = |entries_nullable: bool, key_nullable: bool| {
DataType::Map(
Arc::new(Field::new(
"entries",
DataType::Struct(
vec![
Field::new("key", DataType::Utf8, key_nullable),
Field::new("value", DataType::Int64, true),
]
.into(),
),
entries_nullable,
)),
false,
)
};
for (label, data_type, safe) in [
("d32 valid", DataType::Decimal32(9, 2), true),
("d32 prec=10", DataType::Decimal32(10, 0), false),
("d32 scale>p", DataType::Decimal32(5, 6), false),
("d64 valid", DataType::Decimal64(18, 2), true),
("d64 prec=19", DataType::Decimal64(19, 0), false),
("d128 valid", DataType::Decimal128(38, 2), true),
("d128 prec=39", DataType::Decimal128(39, 0), false),
("d128 prec=0", DataType::Decimal128(0, 0), false),
("d128 scale>p", DataType::Decimal128(10, 11), false),
("d256 valid", DataType::Decimal256(76, 4), true),
("d256 prec=77", DataType::Decimal256(77, 0), false),
("time32 s", DataType::Time32(TimeUnit::Second), true),
("time32 ms", DataType::Time32(TimeUnit::Millisecond), true),
("time32 us", DataType::Time32(TimeUnit::Microsecond), false),
("time32 ns", DataType::Time32(TimeUnit::Nanosecond), false),
("time64 us", DataType::Time64(TimeUnit::Microsecond), true),
("time64 ns", DataType::Time64(TimeUnit::Nanosecond), true),
("time64 s", DataType::Time64(TimeUnit::Second), false),
("time64 ms", DataType::Time64(TimeUnit::Millisecond), false),
("fsb valid", DataType::FixedSizeBinary(4), true),
("fsb negative", DataType::FixedSizeBinary(-1), false),
] {
assert_eq!(
scalar_ordering_type_is_safe(&data_type),
safe,
"{label}: scalar_ordering_type_is_safe"
);
assert_eq!(
comparison_type_is_safe(&data_type, false),
safe,
"{label}: eq comparison_type_is_safe"
);
assert_eq!(
comparison_type_is_safe(&data_type, true),
safe,
"{label}: ord comparison_type_is_safe"
);
let schema = nullable_schema([("x", data_type)]);
assert_eq!(
can_precompute(&col("x").eq(col("x")), &schema),
safe,
"{label}: eq"
);
assert_eq!(
can_precompute(&col("x").lt(col("x")), &schema),
safe,
"{label}: lt"
);
}
assert!(comparison_type_is_safe(
&DataType::new_fixed_size_list(DataType::Int64, 2, true),
true
));
assert!(!comparison_type_is_safe(
&DataType::new_fixed_size_list(DataType::Int64, -1, true),
false
));
let coalesce = datafusion::functions::core::coalesce();
for (label, data_type, safe) in [
("valid map", make_map(false, false), true),
("nullable entries map", make_map(true, false), false),
("nullable key map", make_map(false, true), false),
("d128 valid", DataType::Decimal128(15, 2), true),
("d128 prec=39", DataType::Decimal128(39, 0), false),
("d128 scale>p", DataType::Decimal128(10, 11), false),
("d32 prec=10", DataType::Decimal32(10, 0), false),
("d64 prec=19", DataType::Decimal64(19, 0), false),
("d256 prec=77", DataType::Decimal256(77, 0), false),
("time32 valid", DataType::Time32(TimeUnit::Second), true),
("time32 ns", DataType::Time32(TimeUnit::Nanosecond), false),
("time64 s", DataType::Time64(TimeUnit::Second), false),
("fsb valid", DataType::FixedSizeBinary(4), true),
("fsb negative", DataType::FixedSizeBinary(-1), false),
(
"fsl valid",
DataType::new_fixed_size_list(DataType::Int64, 2, true),
true,
),
(
"fsl negative",
DataType::new_fixed_size_list(DataType::Int64, -1, true),
false,
),
] {
let schema = nullable_schema([
("flag", DataType::Boolean),
("a", data_type.clone()),
("b", data_type),
]);
let case_with_else = when(col("flag"), col("a")).otherwise(col("b")).unwrap();
let case_without_else = when(col("flag"), col("a")).end().unwrap();
let coalesce_expr = coalesce.call(vec![col("a"), col("b")]);
for (kind, expr) in [
("CASE with ELSE", case_with_else),
("CASE without ELSE", case_without_else),
("COALESCE", coalesce_expr),
] {
assert_eq!(can_precompute(&expr, &schema), safe, "{label}: {kind}");
assert_eq!(
can_discard_scalar(&expr, Some(&schema)),
safe,
"{label}: {kind} (discard)"
);
}
}
let abs = datafusion::functions::math::abs();
for (label, data_type, safe) in [
("d32 valid", DataType::Decimal32(9, 2), true),
("d32 prec=10", DataType::Decimal32(10, 0), false),
("d64 valid", DataType::Decimal64(18, 2), true),
("d64 prec=19", DataType::Decimal64(19, 0), false),
("d128 valid", DataType::Decimal128(38, 2), true),
("d128 prec=39", DataType::Decimal128(39, 0), false),
("d128 prec=0", DataType::Decimal128(0, 0), false),
("d128 scale>p", DataType::Decimal128(10, 11), false),
("d256 valid", DataType::Decimal256(76, 4), true),
("d256 prec=77", DataType::Decimal256(77, 0), false),
] {
let schema = nullable_schema([("d", data_type)]);
let expr = abs.call(vec![col("d")]);
assert_eq!(can_precompute(&expr, &schema), safe, "{label}: abs");
}
let octet_len = datafusion::functions::string::octet_length();
for (len, safe) in [(0, true), (4, true), (-1, false)] {
let schema = nullable_schema([("b", DataType::FixedSizeBinary(len))]);
let expr = octet_len.call(vec![col("b")]);
assert_eq!(
can_precompute(&expr, &schema),
safe,
"octet_length FixedSizeBinary({len})"
);
}
}
#[test]
fn date_part_and_two_arg_trim_match_datafusion_return_types() {
let schema = nullable_schema([
("day", DataType::Date32),
("ts_naive", DataType::Timestamp(TimeUnit::Microsecond, None)),
("utf8_col", DataType::Utf8),
("large_col", DataType::LargeUtf8),
("view_col", DataType::Utf8View),
]);
let date_part = datafusion::functions::datetime::date_part();
for (part, col_name) in [
("hour", "day"),
("minute", "day"),
("second", "day"),
("second", "ts_naive"),
] {
let expr = date_part.call(vec![lit(part), col(col_name)]);
assert_eq!(
expr.get_type(&schema).unwrap(),
DataType::Int32,
"date_part({part}, {col_name})"
);
assert!(
can_precompute(&expr, &schema),
"date_part({part}, {col_name})"
);
}
let btrim = datafusion::functions::string::btrim();
let large_with_view = btrim.call(vec![col("large_col"), col("view_col")]);
assert_eq!(
large_with_view.get_type(&schema).unwrap(),
DataType::LargeUtf8
);
assert!(can_precompute(&large_with_view, &schema));
let utf8_with_view = btrim.call(vec![col("utf8_col"), col("view_col")]);
assert_eq!(utf8_with_view.get_type(&schema).unwrap(), DataType::Utf8);
assert!(!can_precompute(&utf8_with_view, &schema));
}
#[test]
fn nullif_preparation_requires_safe_comparison_and_null_values() {
for (data_type, safe) in [
(DataType::Int64, true),
(DataType::Utf8, true),
(
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
false,
),
(DataType::new_list(DataType::Int64, true), false),
] {
let schema = nullable_schema([("a", data_type.clone()), ("b", data_type)]);
let expr = datafusion::functions::core::nullif().call(vec![col("a"), col("b")]);
assert_eq!(can_precompute(&expr, &schema), safe);
}
}
#[test]
fn null_function_results_use_coerced_types_in_enclosing_comparisons() {
use datafusion::common::tree_node::TreeNode;
use datafusion::optimizer::analyzer::type_coercion::TypeCoercionRewriter;
let schema =
nullable_schema([("txt", DataType::Utf8), ("large_text", DataType::LargeUtf8)]);
for (value, expected_type, other) in [
(
datafusion::functions::math::abs().call(vec![lit(ScalarValue::Null)]),
DataType::Float64,
col("txt"),
),
(
datafusion::functions::core::nullif()
.call(vec![lit(ScalarValue::Null), lit(ScalarValue::Null)]),
DataType::Utf8View,
col("large_text"),
),
] {
let coerced = value
.clone()
.rewrite(&mut TypeCoercionRewriter::new(&schema))
.unwrap()
.data;
assert_eq!(coerced.get_type(&schema).unwrap(), expected_type);
assert!(can_precompute(&value, &schema));
let comparison = value.eq(other);
assert!(
!can_precompute(&comparison, &schema),
"implicit casts must remain candidate-local: {comparison}"
);
}
}
#[cfg(feature = "sql")]
#[tokio::test]
async fn abs_null_comparison_does_not_cast_text_on_unreached_rows() -> Result<()> {
use crate::planning::logical::MatchRecognize;
use datafusion::arrow::array::{ArrayRef, Int32Array, StringArray};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::tree_node::TreeNode;
use datafusion::execution::SessionStateBuilder;
use datafusion::logical_expr::LogicalPlan;
let ctx = crate::new_match_recognize_context(
SessionStateBuilder::new().with_default_features(),
)?;
ctx.register_batch(
"input",
RecordBatch::try_from_iter(vec![
("ord", Arc::new(Int32Array::from(vec![1, 2])) as ArrayRef),
(
"txt",
Arc::new(StringArray::from(vec!["not_a_number", "2"])) as ArrayRef,
),
])?,
)?;
assert!(
ctx.sql("SELECT CAST(txt AS DOUBLE) FROM input WHERE ord = 1")
.await?
.collect()
.await
.is_err()
);
let df = ctx
.sql(
"SELECT ord FROM input MATCH_RECOGNIZE (
ORDER BY ord ALL ROWS PER MATCH PATTERN (A B)
DEFINE A AS ord = 1, B AS (ABS(NULL) = txt) IS NULL
) ORDER BY ord",
)
.await?;
assert!(df.logical_plan().exists(|plan| {
let LogicalPlan::Extension(extension) = plan else {
return Ok(false);
};
let Some(matcher) = extension.node.as_any().downcast_ref::<MatchRecognize>()
else {
return Ok(false);
};
let symbol = matcher
.program()
.symbols()
.iter()
.find(|symbol| symbol.name() == "B")
.expect("B must remain in the match program");
assert!(
symbol.demanded_expr().is_some(),
"B's fallible comparison must remain candidate-local: {symbol:?}"
);
Ok(true)
})?);
let batches = df.collect().await?;
let rows = batches
.iter()
.flat_map(|batch| {
batch
.column(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.values()
.iter()
.copied()
})
.collect::<Vec<_>>();
assert_eq!(rows, vec![1, 2]);
Ok(())
}
#[test]
fn expanded_scalar_functions_match_datafusion_coercion_and_return_types() {
use datafusion::common::tree_node::TreeNode;
use datafusion::optimizer::analyzer::type_coercion::TypeCoercionRewriter;
let schema = nullable_schema([
("s", DataType::Utf8),
("sv", DataType::Utf8View),
("sl", DataType::LargeUtf8),
("i32", DataType::Int32),
("i64", DataType::Int64),
("u64", DataType::UInt64),
("f32", DataType::Float32),
("f64", DataType::Float64),
("d", DataType::Decimal128(10, 2)),
(
"dict",
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8)),
),
]);
let precomputable = [
datafusion::functions::string::replace().call(vec![col("s"), lit("A"), lit("B")]),
datafusion::functions::string::replace().call(vec![
col("sv"),
lit("A"),
lit("B"),
]),
datafusion::functions::string::replace().call(vec![
col("sl"),
lit("A"),
lit("B"),
]),
datafusion::functions::string::concat().call(vec![col("s"), lit("-"), col("sv")]),
datafusion::functions::string::concat().call(vec![
col("s"),
lit("x"),
lit(ScalarValue::Null),
]),
datafusion::functions::string::concat_ws().call(vec![
lit("-"),
col("s"),
col("sv"),
lit("x"),
]),
datafusion::functions::string::concat_ws()
.call(vec![lit(ScalarValue::Null), col("s")]),
datafusion::functions::string::ascii().call(vec![col("sv")]),
datafusion::functions::string::bit_length().call(vec![col("sv")]),
datafusion::functions::string::bit_length().call(vec![col("sl")]),
datafusion::functions::unicode::reverse().call(vec![col("sv")]),
datafusion::functions::unicode::initcap().call(vec![col("s")]),
datafusion::functions::unicode::left().call(vec![col("sv"), col("i32")]),
datafusion::functions::unicode::right().call(vec![col("s"), col("i64")]),
datafusion::functions::unicode::strpos().call(vec![col("sv"), col("s")]),
datafusion::functions::unicode::strpos().call(vec![col("sl"), col("s")]),
datafusion::functions::unicode::translate().call(vec![
col("sv"),
lit("a"),
lit("b"),
]),
datafusion::functions::math::signum().call(vec![col("f32")]),
datafusion::functions::math::signum().call(vec![col("i64")]),
datafusion::functions::math::isnan().call(vec![col("f64")]),
datafusion::functions::math::isnan().call(vec![col("i32")]),
datafusion::functions::math::iszero().call(vec![col("d")]),
datafusion::functions::math::nanvl().call(vec![col("f32"), col("f32")]),
datafusion::functions::math::nanvl().call(vec![col("f32"), col("f64")]),
datafusion::functions::core::nvl().call(vec![col("s"), col("sv")]),
datafusion::functions::core::greatest().call(vec![col("i32"), col("i64")]),
datafusion::functions::core::least().call(vec![col("s"), col("sv")]),
];
for expr in precomputable {
let coerced = expr
.clone()
.rewrite(&mut TypeCoercionRewriter::new(&schema))
.unwrap()
.data;
let expected_ty = coerced.get_type(&schema).unwrap();
assert!(
can_precompute(&expr, &schema),
"expected precomputable: {expr}"
);
let Expr::ScalarFunction(func) = &expr else {
unreachable!()
};
let inferred = scalar_function_type(func, &schema, &HashMap::new()).unwrap();
assert_eq!(
inferred, expected_ty,
"return type mismatch for {expr} (coerced: {coerced})"
);
}
let rejected = [
datafusion::functions::string::concat().call(vec![
col("sl"),
lit("-"),
col("sv"),
]),
datafusion::functions::string::replace().call(vec![
col("sl"),
col("sv"),
lit("x"),
]),
datafusion::functions::unicode::left().call(vec![col("s"), col("u64")]),
datafusion::functions::unicode::translate().call(vec![
col("s"),
col("sv"),
lit("b"),
]),
datafusion::functions::core::nvl().call(vec![col("dict"), col("dict")]),
datafusion::functions::core::greatest().call(vec![col("dict"), col("dict")]),
datafusion::functions::core::nvl().call(vec![col("s")]),
datafusion::functions::core::nvl().call(vec![col("s"), col("s"), col("s")]),
datafusion::functions::core::greatest()
.call(vec![lit(ScalarValue::Null), lit(ScalarValue::Null)]),
];
for expr in rejected {
assert!(
!can_precompute(&expr, &schema),
"expected candidate-local rejection: {expr}"
);
}
}
#[test]
fn concat_and_concat_ws_guard_against_simplifier_argument_collapse() {
let schema = nullable_schema([
("sep", DataType::Utf8),
("col_a", DataType::Utf8),
("col_b", DataType::Utf8),
("col_v", DataType::Utf8View),
("col_l", DataType::LargeUtf8),
]);
let concat = datafusion::functions::string::concat();
let concat_ws = datafusion::functions::string::concat_ws();
for (label, expr, safe) in [
(
"concat_ws(sep, NULL)",
concat_ws.call(vec![col("sep"), lit(ScalarValue::Null)]),
false,
),
(
"concat_ws(sep, col_v)",
concat_ws.call(vec![col("sep"), col("col_v")]),
false,
),
(
"concat_ws('-', col_a, col_v)",
concat_ws.call(vec![lit("-"), col("col_a"), col("col_v")]),
false,
),
(
"concat_ws('', col_v, '')",
concat_ws.call(vec![lit(""), col("col_v"), lit("")]),
false,
),
(
"concat_ws(NULL AS sep, NULL)",
concat_ws.call(vec![
lit(ScalarValue::Null).alias("sep"),
lit(ScalarValue::Null),
]),
false,
),
(
"concat_ws(NULL) arity 1",
concat_ws.call(vec![lit(ScalarValue::Null)]),
false,
),
(
"concat_ws(sep, col_v, 'x')",
concat_ws.call(vec![col("sep"), col("col_v"), lit("x")]),
true,
),
(
"concat_ws('', col_v, 'x')",
concat_ws.call(vec![lit(""), col("col_v"), lit("x")]),
true,
),
(
"concat_ws(NULL, col_v)",
concat_ws.call(vec![lit(ScalarValue::Null), col("col_v")]),
true,
),
(
"concat_ws(LargeUtf8(None), col_l)",
concat_ws.call(vec![lit(ScalarValue::LargeUtf8(None)), col("col_l")]),
true,
),
(
"concat(CAST(NULL AS Utf8View))",
concat.call(vec![Expr::Cast(Cast::new(
Box::new(lit(ScalarValue::Null)),
DataType::Utf8View,
))]),
false,
),
(
"concat(Utf8View(None))",
concat.call(vec![lit(ScalarValue::Utf8View(None))]),
false,
),
(
"concat(col_a, '')",
concat.call(vec![col("col_a"), lit("")]),
false,
),
(
"concat(col_a, NULL)",
concat.call(vec![col("col_a"), lit(ScalarValue::Null)]),
false,
),
(
"concat(col_a, col_b)",
concat.call(vec![col("col_a"), col("col_b")]),
false,
),
(
"concat(col_a, '|', col_b)",
concat.call(vec![col("col_a"), lit("|"), col("col_b")]),
true,
),
(
"concat(col_v, '|', col_b)",
concat.call(vec![col("col_v"), lit("|"), col("col_b")]),
true,
),
(
"concat(col_l, '|')",
concat.call(vec![col("col_l"), lit("|")]),
true,
),
] {
assert_eq!(can_precompute(&expr, &schema), safe, "{label}");
assert_eq!(
can_discard_scalar(&expr, Some(&schema)),
safe,
"{label} (discard)"
);
}
}