use std::sync::Arc;
use crate::core::{
AfterMatchSkip, MatchRecognizeNullOrdering, MatchRecognizeSortExpr, Pattern, Symbol,
};
use datafusion::arrow::datatypes::{DataType, Field, Metadata, Schema};
use datafusion::logical_expr::utils::find_window_exprs;
use datafusion::logical_expr::{
AggregateUDF, EmptyRelation, Expr, LogicalPlan, Operator,
};
use super::*;
use crate::planning::define::{StaticAnalysis, is_static};
use crate::planning::expressions::test_support::{SameNameCustomAggregate, bound_binary};
use crate::planning::logical::{sequence_sort_expr, valid_match_row_expr};
use crate::planning::source::{
BoundMatchAggregateCall, MatchAggregateCall, MatchNavigation, MatchPatternFieldRef,
MatchRecognizePlanningCapabilities,
};
fn test_input_schema() -> DFSchema {
DFSchema::try_from_qualified_schema(
"t",
&Schema::new(vec![
Field::new("company", DataType::Utf8, true),
Field::new("ts", DataType::Int64, true),
Field::new("price", DataType::Int64, true),
]),
)
.expect("test schema")
}
fn define_normalizer<'a>(
context: &'a mut dyn MatchRecognizePlanningContext,
input_schema: &'a DFSchema,
) -> BoundExprLowerer<'a> {
define_normalizer_with_symbols(context, input_schema, BTreeSet::from(["A".into()]))
}
fn define_normalizer_with_symbols<'a>(
context: &'a mut dyn MatchRecognizePlanningContext,
input_schema: &'a DFSchema,
pattern_symbols: BTreeSet<String>,
) -> BoundExprLowerer<'a> {
let expression_schema =
build_match_aware_schema(&Arc::new(input_schema.clone()), &pattern_symbols)
.expect("test expression schema");
BoundExprLowerer {
context,
input_schema,
expression_schema,
rows_per_match: RowsPerMatch::OneRow,
pattern_symbols,
source_partition_by: vec![col("company")],
source_order_by: vec![SortExpr::new(col("ts"), true, false)],
partition_by: vec![col("company")],
order_by: vec![SortExpr::new(col("ts"), true, false)],
current_row: CurrentRow::Enabled,
}
}
#[test]
fn timestamp_casts_use_seconds_for_int64_match_values() -> Result<()> {
use datafusion::arrow::datatypes::TimeUnit;
let input_schema = test_input_schema();
let mut context = datafusion_common::config::ConfigOptions::default();
let target = DataType::Timestamp(TimeUnit::Nanosecond, Some("+02:00".into()));
for (clause, value, seconds) in [
(
SourceClause::Define { symbol: "A" },
BoundMatchExpr::Metadata(MatchMetadataFunction::MatchNumber),
true,
),
(
SourceClause::Measures,
BoundMatchExpr::Metadata(MatchMetadataFunction::MatchNumber),
true,
),
(
SourceClause::Measures,
BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".into(),
column: Column::new(Some("t"), "price"),
}),
true,
),
(
SourceClause::Measures,
BoundMatchExpr::Literal(ScalarValue::Int32(Some(2))),
false,
),
] {
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
clause,
ExprRole::Scalar,
BoundMatchExpr::Cast {
expr: Box::new(value),
data_type: target.clone(),
},
)?;
let Expr::Cast(cast) = lowered.expr else {
panic!("expected timestamp cast")
};
assert_eq!(cast.field.data_type(), &target);
match cast.expr.as_ref() {
Expr::Cast(inner) if seconds => assert_eq!(
inner.field.data_type(),
&DataType::Timestamp(TimeUnit::Second, Some("+02:00".into())),
),
Expr::Literal(ScalarValue::Int32(Some(2)), _) if !seconds => {}
value => panic!("unexpected timestamp operand: {value:?}"),
}
}
Ok(())
}
fn lower_define_window(expr: BoundMatchExpr) -> Result<WindowFunction> {
let mut context = datafusion_common::config::ConfigOptions::default();
let input_schema = test_input_schema();
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
expr,
)?;
let Expr::WindowFunction(window) = lowered.expr else {
panic!("expected DEFINE aggregate to lower to a window expression");
};
Ok(*window)
}
fn plain_aggregate(name: &str, args: Vec<BoundMatchExpr>) -> BoundMatchAggregateCall {
MatchAggregateCall {
name: name.to_string(),
args,
distinct: false,
filter: None,
order_by: vec![],
null_treatment: None,
wildcard_symbol: None,
}
}
fn aggregate_call(
name: &str,
args: Vec<BoundMatchExpr>,
order_by: Vec<BoundMatchExprSort>,
) -> BoundMatchExpr {
BoundMatchExpr::Aggregate(MatchAggregateCall {
order_by,
..plain_aggregate(name, args)
})
}
fn source_price_column() -> BoundMatchExpr {
BoundMatchExpr::InputColumn(Column::new(Some("t"), "price"))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NavigationDirection {
Previous,
Next,
}
use NavigationDirection::{Next, Previous};
fn source_navigation(direction: NavigationDirection, offset: i64) -> BoundMatchExpr {
let expr = Box::new(source_price_column());
let int_literal = |value| {
Some(Box::new(BoundMatchExpr::Literal(ScalarValue::Int64(Some(
value,
)))))
};
let offset = int_literal(offset);
let default = int_literal(0);
BoundMatchExpr::Navigation(match direction {
Previous => MatchNavigation::Prev {
expr,
offset,
default,
},
Next => MatchNavigation::Next {
expr,
offset,
default,
},
})
}
fn positive(expr: BoundMatchExpr) -> BoundMatchExpr {
bound_binary(
expr,
Operator::Gt,
BoundMatchExpr::Literal(ScalarValue::Int64(Some(0))),
)
}
struct CustomCountContext {
options: datafusion_common::config::ConfigOptions,
}
impl MatchRecognizePlanningContext for CustomCountContext {
fn options(&self) -> &datafusion_common::config::ConfigOptions {
&self.options
}
fn aggregate_udf(&self, name: &str) -> Option<Arc<AggregateUDF>> {
name.eq_ignore_ascii_case("count").then(|| {
Arc::new(AggregateUDF::new_from_impl(SameNameCustomAggregate {
name: "count",
}))
})
}
}
fn source_price_sort(asc: bool, nulls_first: bool) -> BoundMatchExprSort {
BoundMatchExprSort {
expr: Box::new(source_price_column()),
asc,
nulls_first,
}
}
fn price_column() -> Expr {
Expr::Column(Column::new(Some("t"), "price"))
}
#[test]
fn deep_binary_lowering_preserves_operand_order() -> Result<()> {
const DEPTH: i64 = 96;
let input_schema = test_input_schema();
let mut context = datafusion_common::config::ConfigOptions::default();
for right_deep in [false, true] {
let mut expr = BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".to_string(),
column: Column::new(Some("t"), "price"),
});
for index in 0..DEPTH {
let input = BoundMatchExpr::Literal(ScalarValue::Int64(Some(index)));
let (left, right) = if right_deep {
(input, expr)
} else {
(expr, input)
};
expr = bound_binary(left, Operator::Minus, right);
}
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::AggregateArg,
expr,
)?;
assert_eq!(lowered.symbols, BTreeSet::from(["A".to_string()]));
assert!(lowered.max_prev_offset.is_zero());
assert!(lowered.max_next_offset.is_zero());
let mut expr = lowered.expr;
for index in (0..DEPTH).rev() {
let Expr::BinaryExpr(binary) = expr else {
panic!("expected binary chain at {index}");
};
assert_eq!(binary.op, Operator::Minus);
let (next, input) = if right_deep {
(binary.right, binary.left)
} else {
(binary.left, binary.right)
};
assert_eq!(*input, lit(index));
expr = *next;
}
assert_eq!(expr, price_column());
}
Ok(())
}
#[test]
fn binary_lowering_preserves_leaf_roles_symbols_and_navigation_offsets() -> Result<()> {
let input_schema = test_input_schema();
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer_with_symbols(
&mut context,
&input_schema,
BTreeSet::from(["A".into(), "B".into()]),
);
let field = |symbol: &str| {
BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: symbol.to_string(),
column: Column::new(Some("t"), "price"),
})
};
let binary = |left, right| bound_binary(left, Operator::Minus, right);
for role in [ExprRole::Scalar, ExprRole::AggregateArg] {
let lowered = normalizer.lower_expr(
SourceClause::Measures,
role,
binary(field("A"), field("B")),
)?;
let Expr::BinaryExpr(expr) = lowered.expr else {
panic!("expected binary measure");
};
if role == ExprRole::Scalar {
assert!(lowered.symbols.is_empty());
for (operand, symbol) in [(expr.left, "a"), (expr.right, "b")] {
let Expr::AggregateFunction(aggregate) = *operand else {
panic!("scalar measure leaves need individual LAST aggregates");
};
assert_eq!(aggregate.func.name(), "last_value");
assert_eq!(aggregate.params.args, [price_column()]);
assert_eq!(
aggregate.params.filter.as_deref(),
Some(&col(format!("__mr_classifier_{symbol}")))
);
}
} else {
assert_eq!(
lowered.symbols,
BTreeSet::from(["A".to_string(), "B".to_string()])
);
assert_eq!(*expr.left, price_column());
assert_eq!(*expr.right, price_column());
}
}
let lowered = normalizer.lower_expr(
SourceClause::Measures,
ExprRole::AggregateArg,
binary(
binary(field("A"), source_navigation(Previous, 3)),
binary(
binary(field("B"), source_navigation(Next, 7)),
source_navigation(Previous, 2),
),
),
)?;
assert_eq!(
lowered.symbols,
BTreeSet::from(["A".to_string(), "B".to_string()])
);
assert_eq!(lowered.max_prev_offset.as_usize(), 3);
assert_eq!(lowered.max_next_offset.as_usize(), 7);
Ok(())
}
#[test]
fn binary_lowering_reports_isolated_child_errors() {
let input_schema = test_input_schema();
let mut context = datafusion_common::config::ConfigOptions::default();
let field = |name| BoundMatchExpr::InputColumn(Column::from_name(name));
for (left, right, expected) in [
("__mr_left", "price", "__mr_left"),
("price", "__mr_right", "__mr_right"),
] {
let error = define_normalizer(&mut context, &input_schema)
.lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
bound_binary(field(left), Operator::Minus, field(right)),
)
.unwrap_err()
.to_string();
assert!(
error.contains(&format!("internal column '{expected}'")),
"{error}"
);
}
}
#[test]
fn builtin_count_of_each_exact_metadata_value_becomes_count_one() -> Result<()> {
for metadata in [
MatchMetadataFunction::Classifier,
MatchMetadataFunction::MatchNumber,
MatchMetadataFunction::MatchSequenceNumber,
MatchMetadataFunction::Excluded,
] {
let window = lower_define_window(aggregate_call(
"count",
vec![BoundMatchExpr::Metadata(metadata.clone())],
vec![],
))?;
assert_eq!(window.params.args, [lit(1_i64)], "COUNT({metadata:?}())");
}
let distinct = lower_define_window(BoundMatchExpr::Aggregate(MatchAggregateCall {
distinct: true,
..plain_aggregate(
"count",
vec![BoundMatchExpr::Metadata(MatchMetadataFunction::Classifier)],
)
}))?;
assert!(distinct.params.distinct);
assert_eq!(distinct.params.args, [col("__mr_classifier")]);
let wrapped = lower_define_window(aggregate_call(
"count",
vec![BoundMatchExpr::Alias {
expr: Box::new(BoundMatchExpr::Metadata(MatchMetadataFunction::Classifier)),
name: "classification".to_string(),
}],
vec![],
))?;
assert_eq!(
wrapped.params.args,
[col("__mr_classifier").alias("classification")]
);
let input_schema = test_input_schema();
let mut context = CustomCountContext {
options: datafusion_common::config::ConfigOptions::default(),
};
let mut normalizer = define_normalizer(&mut context, &input_schema);
let lowered = normalizer.lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
aggregate_call(
"count",
vec![BoundMatchExpr::Metadata(MatchMetadataFunction::Classifier)],
vec![],
),
)?;
let Expr::WindowFunction(window) = lowered.expr else {
panic!("expected DEFINE aggregate to lower to a window expression");
};
assert_eq!(window.params.args, [col("__mr_classifier")]);
Ok(())
}
#[test]
fn count_metadata_rewrite_preserves_ordinary_decorators_and_symbol_scope() -> Result<()> {
let mut context = datafusion_common::config::ConfigOptions::default();
let input_schema = test_input_schema();
let mut normalizer = define_normalizer(&mut context, &input_schema);
let symbol_price = BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".to_string(),
column: Column::from_name("price"),
});
let lowered = normalizer.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(bound_binary(
symbol_price,
Operator::Gt,
BoundMatchExpr::Literal(ScalarValue::Int64(Some(0))),
))),
order_by: vec![source_price_sort(false, true)],
null_treatment: Some(
datafusion::logical_expr::expr::NullTreatment::IgnoreNulls,
),
..plain_aggregate(
"count",
vec![BoundMatchExpr::Metadata(MatchMetadataFunction::MatchNumber)],
)
}),
)?;
let Expr::AggregateFunction(aggregate) = lowered.expr else {
panic!("expected a match-level aggregate");
};
assert!(matches!(
aggregate.params.args.as_slice(),
[Expr::Literal(ScalarValue::Int64(Some(1)), _)]
));
let filter = aggregate.params.filter.expect("preserved aggregate filter");
let filter = filter.to_string();
assert!(filter.contains("price > Int64(0)"), "{filter}");
assert!(filter.contains("__mr_classifier_a"), "{filter}");
assert_eq!(
aggregate.params.order_by,
vec![SortExpr::new(price_column(), false, true)]
);
assert_eq!(
aggregate.params.null_treatment,
Some(datafusion::logical_expr::expr::NullTreatment::IgnoreNulls)
);
Ok(())
}
#[test]
fn all_rows_literal_counts_use_non_null_sequence_without_a_window() -> Result<()> {
let input_schema = test_input_schema();
let schema = build_match_aware_schema(
&Arc::new(input_schema.clone()),
&BTreeSet::from(["A".to_string()]),
)?;
for clause in [SourceClause::Measures, SourceClause::ExplicitOutput] {
for argument in [
BoundMatchExpr::Literal(ScalarValue::Int64(Some(1))),
BoundMatchExpr::InputExpr(lit(1_i64)),
BoundMatchExpr::Literal(ScalarValue::Utf8(Some("row".to_string()))),
BoundMatchExpr::InputExpr(lit("row")),
] {
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &input_schema);
normalizer.rows_per_match =
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::Show);
let lowered = normalizer.lower_expr(
clause,
ExprRole::Scalar,
aggregate_call("count", vec![argument], vec![]),
)?;
assert!(find_window_exprs([&lowered.expr]).is_empty());
assert!(lowered.expr.column_refs().contains(&Column::from_name(
MatchMetadataColumn::MatchSequenceNumber.as_ref()
)));
let (_, field) = lowered.expr.to_field(schema.as_ref())?;
assert_eq!(field.data_type(), &DataType::Int64);
assert!(!field.is_nullable());
}
}
let expression = aggregate_call(
"count",
vec![BoundMatchExpr::Literal(ScalarValue::Int64(Some(1)))],
vec![],
);
lower_define_window(expression.clone())?;
let mut context = datafusion_common::config::ConfigOptions::default();
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
expression,
)?;
assert!(matches!(lowered.expr, Expr::AggregateFunction(_)));
Ok(())
}
#[test]
fn all_rows_counts_with_value_or_decorator_semantics_keep_their_window() -> Result<()> {
let input_schema = test_input_schema();
for kind in [
"distinct",
"filter",
"null treatment",
"symbol",
"null literal",
"column",
] {
let mut aggregate = plain_aggregate(
"count",
vec![BoundMatchExpr::Literal(ScalarValue::Int64(Some(1)))],
);
match kind {
"distinct" => aggregate.distinct = true,
"filter" => {
aggregate.filter = Some(Box::new(BoundMatchExpr::Literal(
ScalarValue::Boolean(Some(true)),
)));
}
"null treatment" => {
aggregate.null_treatment =
Some(datafusion::logical_expr::expr::NullTreatment::IgnoreNulls);
}
"symbol" => {
aggregate.args.clear();
aggregate.wildcard_symbol = Some("A".to_string());
}
"null literal" => {
aggregate.args = vec![BoundMatchExpr::Literal(ScalarValue::Int64(None))];
}
"column" => aggregate.args = vec![source_price_column()],
_ => unreachable!(),
}
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &input_schema);
normalizer.rows_per_match =
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::Show);
let lowered = normalizer.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Aggregate(aggregate),
)?;
assert!(matches!(lowered.expr, Expr::WindowFunction(_)), "{kind}");
}
Ok(())
}
#[test]
fn same_name_custom_count_does_not_inherit_builtin_count_rewrites() {
let input_schema = test_input_schema();
let mut context = CustomCountContext {
options: datafusion_common::config::ConfigOptions::default(),
};
let mut normalizer = define_normalizer(&mut context, &input_schema);
normalizer.rows_per_match =
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::Show);
let custom_count = normalizer
.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
aggregate_call(
"count",
vec![BoundMatchExpr::Literal(ScalarValue::Int64(Some(1)))],
vec![],
),
)
.expect("custom count lowers without built-in count substitutions");
assert!(matches!(custom_count.expr, Expr::WindowFunction(_)));
let error = normalizer
.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Aggregate(MatchAggregateCall {
wildcard_symbol: Some("A".to_string()),
..plain_aggregate("count", vec![])
}),
)
.expect_err("custom COUNT(A.*) must not inherit built-in COUNT semantics");
assert!(
error.to_string().contains("built-in COUNT implementation"),
"{error}"
);
}
#[test]
fn unqualified_first_in_all_rows_measures_filters_empty_rows() -> Result<()> {
let mut context = datafusion_common::config::ConfigOptions::default();
let input_schema = test_input_schema();
let mut normalizer = define_normalizer(&mut context, &input_schema);
normalizer.rows_per_match =
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::Show);
let lowered = normalizer.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(BoundMatchExpr::InputColumn(Column::from_name("price"))),
offset: None,
}),
)?;
let Expr::WindowFunction(window) = lowered.expr else {
panic!("expected FIRST window")
};
let sequence = col("__mr_match_sequence_number");
let expected_filter = sequence
.clone()
.gt_eq(lit(0_i64))
.and(sequence.lt_eq(lit((1_i64 << 62) - 1)))
.and(col("__mr_classifier").is_not_null());
assert_eq!(window.params.args, [col("price"), expected_filter]);
Ok(())
}
#[test]
fn one_row_match_edges_use_native_filtered_aggregates() -> Result<()> {
for (navigation, expected, symbol) in [
(
MatchNavigation::First {
expr: Box::new(source_price_column()),
offset: None,
},
datafusion_functions_aggregate::first_last::first_value_udaf(),
None,
),
(
MatchNavigation::Last {
expr: Box::new(BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".to_string(),
column: Column::from_name("price"),
})),
offset: None,
},
datafusion_functions_aggregate::first_last::last_value_udaf(),
Some("A"),
),
] {
let mut context = datafusion_common::config::ConfigOptions::default();
let input_schema = test_input_schema();
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Navigation(navigation),
)?;
let Expr::AggregateFunction(aggregate) = lowered.expr else {
panic!("ONE ROW FIRST/LAST must lower to an aggregate");
};
assert_eq!(aggregate.func.as_ref(), expected.as_ref());
assert_eq!(aggregate.params.args.len(), 1);
assert!(!aggregate.params.distinct);
assert_eq!(aggregate.params.order_by, vec![sequence_sort_expr()]);
assert_eq!(aggregate.params.null_treatment, None);
let mut expected_filter =
functions::first_last_unqualified_filter_expr(SourceClause::Measures);
if let Some(symbol) = symbol {
expected_filter = expected_filter.and(classifier_mask_expr(symbol));
}
assert_eq!(aggregate.params.filter.as_deref(), Some(&expected_filter),);
}
Ok(())
}
#[test]
fn one_row_edge_carriers_use_native_group_states() -> Result<()> {
let metadata = Metadata::new().with("logical", "value");
for (logical_type, carrier_type) in [
(DataType::Boolean, Some(DataType::Int8)),
(
DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
None,
),
] {
let input_schema = DFSchema::try_from_qualified_schema(
"t",
&Schema::new(vec![
Field::new("company", DataType::Utf8, true),
Field::new("ts", DataType::Int64, true),
Field::new("value", logical_type.clone(), true)
.with_metadata(metadata.clone()),
]),
)?;
let mut context = datafusion_common::config::ConfigOptions::default();
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(BoundMatchExpr::InputColumn(Column::from_name("value"))),
offset: None,
}),
)?;
let aggregate_expr = if carrier_type.is_some() {
let Expr::Cast(output_cast) = &lowered.expr else {
panic!("FIRST must restore its logical type after carrier aggregation");
};
assert_eq!(output_cast.field.data_type(), &logical_type);
assert_eq!(output_cast.field.metadata(), &metadata);
output_cast.expr.as_ref()
} else {
&lowered.expr
};
let Expr::AggregateFunction(aggregate) = aggregate_expr else {
panic!("FIRST must use a native aggregate without casting byte dictionaries");
};
assert_eq!(
aggregate.func,
datafusion_functions_aggregate::first_last::first_value_udaf()
);
assert_eq!(aggregate.params.order_by, vec![sequence_sort_expr()]);
assert_eq!(
aggregate.params.filter.as_deref(),
Some(&crate::planning::logical::selected_row_filter_expr())
);
if let Some(carrier_type) = carrier_type {
let [Expr::Cast(input_cast)] = aggregate.params.args.as_slice() else {
panic!("FIRST must cast its value to a native groups carrier");
};
assert_eq!(input_cast.field.data_type(), &carrier_type);
assert_eq!(input_cast.expr.as_ref(), &col("value"));
} else {
assert_eq!(aggregate.params.args, vec![col("value")]);
}
assert_eq!(
lowered.expr.to_field(&input_schema)?.1.metadata(),
&metadata
);
}
Ok(())
}
#[test]
fn one_row_edge_carriers_restore_non_null_values_as_nullable() -> Result<()> {
let metadata = Metadata::new().with("logical", "value");
for logical_type in [
DataType::Boolean,
DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
] {
for field_metadata in [Metadata::new(), metadata.clone()] {
let input_schema = DFSchema::try_from_qualified_schema(
"t",
&Schema::new(vec![
Field::new("company", DataType::Utf8, true),
Field::new("ts", DataType::Int64, true),
Field::new("value", logical_type.clone(), false)
.with_metadata(field_metadata.clone()),
]),
)?;
let mut context = datafusion_common::config::ConfigOptions::default();
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(BoundMatchExpr::InputColumn(Column::from_name(
"value",
))),
offset: None,
}),
)?;
if logical_type == DataType::Boolean {
let Expr::Cast(output_cast) = &lowered.expr else {
panic!("FIRST must restore Boolean after carrier aggregation");
};
assert!(output_cast.field.is_nullable(), "{logical_type}");
assert_eq!(output_cast.field.data_type(), &logical_type);
assert_eq!(output_cast.field.metadata(), &field_metadata);
if field_metadata.is_empty() {
assert_eq!(
output_cast.field,
Arc::new(Field::new("", logical_type.clone(), true)),
"metadata-free restores must stay type-only casts"
);
}
} else {
let Expr::AggregateFunction(aggregate) = &lowered.expr else {
panic!("FIRST must preserve the byte dictionary without casts");
};
assert_eq!(aggregate.params.args, vec![col("value")]);
}
let (_, field) = lowered.expr.to_field(&input_schema)?;
assert!(field.is_nullable(), "{logical_type}");
assert_eq!(field.data_type(), &logical_type);
assert_eq!(field.metadata(), &field_metadata);
}
}
Ok(())
}
#[test]
fn output_navigation_offsets_ignore_define_navigation() -> Result<()> {
let input = LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: Arc::new(test_input_schema()),
});
let define = bound_binary(
positive(source_navigation(Previous, 9)),
Operator::And,
positive(source_navigation(Next, 7)),
);
let spec = BoundMatchSpec {
partition_by: vec![],
order_by: vec![MatchRecognizeSortExpr {
expr: BoundMatchExpr::InputColumn(Column::new(Some("t"), "ts")),
direction: MatchRecognizeSortDirection::Asc,
null_ordering: MatchRecognizeNullOrdering::Last,
}],
source_rows_per_match: RowsPerMatch::OneRow,
after_match_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
symbols: vec!["A".to_string()],
definitions: vec![MatchRecognizeDefinition {
symbol: "A".to_string(),
predicate: define,
}],
measures: vec![
MatchRecognizeMeasure {
name: Some("previous".to_string()),
expression: source_navigation(Previous, 4),
},
MatchRecognizeMeasure {
name: Some("following".to_string()),
expression: source_navigation(Next, 5),
},
],
output: MatchRecognizeOutputContract::Derived,
};
let mut context = datafusion_common::config::ConfigOptions::default();
let source = crate::planning::logical::BoundMatchSource::try_new(
&mut context,
input,
spec,
MatchRecognizePlanningCapabilities::default(),
)?;
let lowered =
lower_bound_match_spec(&mut context, source.input(), source.canonical_spec())?;
assert_eq!(lowered.navigation_offsets.previous().as_usize(), 4);
assert_eq!(lowered.navigation_offsets.next().as_usize(), 5);
Ok(())
}
#[test]
fn omitted_and_null_navigation_offsets_normalize_to_uint64_one() -> Result<()> {
for is_next in [false, true] {
for offset in [
None,
Some(Box::new(BoundMatchExpr::Literal(ScalarValue::Null))),
Some(Box::new(BoundMatchExpr::Literal(ScalarValue::Int64(None)))),
Some(Box::new(BoundMatchExpr::Literal(ScalarValue::UInt64(None)))),
] {
let expr = Box::new(BoundMatchExpr::InputColumn(Column::from_name("price")));
let navigation = if is_next {
MatchNavigation::Next {
expr,
offset,
default: None,
}
} else {
MatchNavigation::Prev {
expr,
offset,
default: None,
}
};
let window = lower_define_window(BoundMatchExpr::Navigation(navigation))?;
assert_eq!(
window.params.args,
[
col("price"),
lit(ScalarValue::UInt64(Some(1))),
lit(ScalarValue::Null)
]
);
}
}
Ok(())
}
fn navigation_operand(qualifier: Option<&str>, metadata: bool) -> BoundMatchExpr {
let column = Column::from_name("price");
let value = match qualifier {
Some(symbol) => BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: symbol.into(),
column,
}),
None => BoundMatchExpr::InputColumn(column),
};
if metadata {
bound_binary(
value,
Operator::Plus,
BoundMatchExpr::Metadata(MatchMetadataFunction::MatchNumber),
)
} else {
value
}
}
#[test]
fn define_last_of_defining_symbol_is_the_current_row() -> Result<()> {
for (kind, qualifier, metadata, define_symbol, current) in [
("implicit", Some("A"), false, Some("A"), true),
("last", Some("A"), false, Some("A"), true),
("last", None, false, Some("A"), true),
("last", Some("A"), false, Some("a"), true),
("last", Some("B"), false, Some("A"), false),
("first", Some("A"), false, Some("A"), false),
("last", Some("A"), true, Some("A"), false),
("volatile", None, false, Some("A"), false),
("implicit", Some("A"), false, None, false),
] {
let value = if kind == "volatile" {
BoundMatchExpr::InputExpr(datafusion::functions::math::random().call(vec![]))
} else {
navigation_operand(qualifier, metadata)
};
let expr = match kind {
"last" | "volatile" => BoundMatchExpr::Navigation(MatchNavigation::Last {
expr: Box::new(value),
offset: None,
}),
"first" => BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(value),
offset: None,
}),
_ => value,
};
let mut context = datafusion_common::config::ConfigOptions::default();
let input_schema = test_input_schema();
let mut normalizer = define_normalizer_with_symbols(
&mut context,
&input_schema,
BTreeSet::from(["A".into(), "B".into()]),
);
normalizer.rows_per_match =
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::Omit);
let clause = define_symbol.map_or(SourceClause::Measures, |symbol| {
SourceClause::Define { symbol }
});
let lowered = normalizer.lower_expr(clause, ExprRole::Scalar, expr)?;
if current {
assert_eq!(
lowered.expr,
col("price"),
"{kind}({qualifier:?}) in {clause:?}"
);
assert!(lowered.symbols.is_empty());
} else {
assert!(
matches!(lowered.expr, Expr::WindowFunction(_)),
"{kind}({qualifier:?}) in {clause:?}"
);
if kind == "volatile" {
assert!(lowered.expr.is_volatile());
}
}
}
let mut context = datafusion_common::config::ConfigOptions::default();
let input_schema = test_input_schema();
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Metadata(MatchMetadataFunction::Classifier),
)?;
assert_eq!(
lowered.expr,
Expr::Literal(ScalarValue::Utf8(Some("A".to_string())), None)
);
Ok(())
}
fn field(name: &str) -> BoundMatchExpr {
BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".into(),
column: Column::from_name(name),
})
}
fn assert_current_row_stays_static(
schema: &DFSchema,
predicate: BoundMatchExpr,
) -> Result<()> {
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, schema);
let lowered = normalizer.lower_define("A", predicate.clone(), &predicate)?;
assert!(
is_static(
&lowered.expr,
StaticAnalysis::new(&normalizer.pattern_symbols, &BTreeSet::new()),
),
"{predicate:?} lowered to {}",
lowered.expr,
);
Ok(())
}
#[test]
fn current_row_lowering_separates_demanded_scalars_from_residual_predicates() -> Result<()>
{
let compare = |left, right| bound_binary(left, Operator::Eq, right);
let number = BoundMatchExpr::Literal(ScalarValue::Int64(Some(9)));
let cast = |data_type| BoundMatchExpr::Cast {
expr: Box::new(field("price")),
data_type,
};
let schema = test_input_schema();
for predicate in [
compare(field("price"), number.clone()),
compare(field("company"), number.clone()),
compare(cast(DataType::Float64), number.clone()),
compare(cast(DataType::Int8), number.clone()),
compare(
bound_binary(field("price"), Operator::Plus, number.clone()),
number,
),
BoundMatchExpr::InList {
expr: Box::new(BoundMatchExpr::Literal(ScalarValue::Null)),
list: vec![field("company"), source_price_column()],
negated: false,
},
compare(
field("company"),
BoundMatchExpr::Literal(ScalarValue::Utf8(Some("ok".into()))),
),
] {
assert_current_row_stays_static(&schema, predicate)?;
}
Ok(())
}
#[test]
fn current_row_lowering_shares_nested_arithmetic_safety() -> Result<()> {
for (data_type, one) in [
(DataType::Decimal128(15, 2), ScalarValue::Int64(Some(1))),
(DataType::Float32, ScalarValue::Float32(Some(1.0))),
(DataType::Float64, ScalarValue::Float64(Some(1.0))),
] {
let net = bound_binary(
field("price"),
Operator::Multiply,
bound_binary(
BoundMatchExpr::Literal(one),
Operator::Minus,
field("discount"),
),
);
let input_schema = DFSchema::try_from(Schema::new(vec![
Field::new("price", data_type.clone(), true),
Field::new("discount", data_type, true),
]))?;
for value in [
net.clone(),
bound_binary(net, Operator::Divide, field("price")),
] {
let predicate = bound_binary(
value,
Operator::Gt,
BoundMatchExpr::Literal(ScalarValue::Int64(Some(100))),
);
assert_current_row_stays_static(&input_schema, predicate)?;
}
}
Ok(())
}
#[test]
fn define_prev_keeps_the_value_type_for_both_evaluation_paths() -> Result<()> {
let schema = test_input_schema();
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &schema);
for (value, deferred) in [(col("price"), false), (col("price") / col("ts"), true)] {
let navigation = MatchNavigation::Prev {
expr: Box::new(BoundMatchExpr::InputExpr(value)),
offset: Some(Box::new(BoundMatchExpr::Literal(ScalarValue::Int64(Some(
1,
))))),
default: Some(Box::new(BoundMatchExpr::Literal(ScalarValue::Float64(
Some(7.5),
)))),
};
let lowered = normalizer.lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Navigation(navigation),
)?;
if deferred {
assert!(matches!(lowered.expr, Expr::Case(_)));
} else {
assert!(matches!(lowered.expr, Expr::WindowFunction(_)));
}
assert_eq!(lowered.expr.get_type(&schema)?, DataType::Int64);
}
Ok(())
}
#[test]
fn define_prev_next_fallible_null_value_keeps_default_type() -> Result<()> {
let schema = test_input_schema();
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &schema);
let safe_null = Expr::Case(Case::new(
None,
vec![(
Box::new(col("ts").gt(lit(0_i64))),
Box::new(lit(ScalarValue::Null)),
)],
None,
));
let fallible_null = Expr::Case(Case::new(
None,
vec![(
Box::new((lit(1_i64) / col("ts")).gt(lit(0_i64))),
Box::new(lit(ScalarValue::Null)),
)],
None,
));
for is_prev in [true, false] {
for (value, deferred) in [(&safe_null, false), (&fallible_null, true)] {
for (default, expected_type) in [
(ScalarValue::Int64(Some(42)), DataType::Int64),
(ScalarValue::Int64(None), DataType::Int64),
(ScalarValue::Boolean(None), DataType::Boolean),
(ScalarValue::Null, DataType::Null),
] {
let navigation = if is_prev {
MatchNavigation::Prev {
expr: Box::new(BoundMatchExpr::InputExpr(value.clone())),
offset: Some(Box::new(BoundMatchExpr::Literal(
ScalarValue::Int64(Some(1)),
))),
default: Some(Box::new(BoundMatchExpr::Literal(default))),
}
} else {
MatchNavigation::Next {
expr: Box::new(BoundMatchExpr::InputExpr(value.clone())),
offset: Some(Box::new(BoundMatchExpr::Literal(
ScalarValue::Int64(Some(1)),
))),
default: Some(Box::new(BoundMatchExpr::Literal(default))),
}
};
let lowered = normalizer.lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Navigation(navigation),
)?;
if deferred {
assert!(matches!(lowered.expr, Expr::Case(_)));
} else {
assert!(matches!(lowered.expr, Expr::WindowFunction(_)));
}
assert_eq!(lowered.expr.get_type(&schema)?, expected_type);
}
}
}
Ok(())
}
#[test]
fn define_prev_next_separates_input_and_match_dependent_navigation() -> Result<()> {
let pattern_symbols = BTreeSet::from(["A".to_string(), "B".to_string()]);
let generated_match_columns = BTreeSet::new();
let static_analysis = StaticAnalysis::new(&pattern_symbols, &generated_match_columns);
for (name, qualifier, metadata, expected_function, match_independent) in [
("prev", None, false, "lag", true),
("prev", Some("A"), false, "lag", true),
("prev", Some("B"), false, "__mr_prev_agg", false),
("next", None, false, "lead", true),
("next", Some("A"), false, "lead", true),
("next", Some("B"), false, "__mr_next_agg", false),
("prev", None, true, "__mr_prev_agg", false),
("prev", Some("A"), true, "__mr_prev_agg", false),
("prev", Some("B"), true, "__mr_prev_agg", false),
("next", None, true, "__mr_next_agg", false),
("next", Some("A"), true, "__mr_next_agg", false),
("next", Some("B"), true, "__mr_next_agg", false),
] {
let value = navigation_operand(qualifier, metadata);
let navigation = match name {
"prev" => MatchNavigation::Prev {
expr: Box::new(value),
offset: None,
default: None,
},
"next" => MatchNavigation::Next {
expr: Box::new(value),
offset: None,
default: None,
},
_ => unreachable!(),
};
let mut context = datafusion_common::config::ConfigOptions::default();
let input_schema = test_input_schema();
let mut normalizer = define_normalizer_with_symbols(
&mut context,
&input_schema,
pattern_symbols.clone(),
);
let lowered = normalizer.lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Navigation(navigation),
)?;
let Expr::WindowFunction(window) = &lowered.expr else {
panic!("expected DEFINE {name} to lower to a window expression");
};
assert_eq!(
is_static(&lowered.expr, static_analysis),
match_independent,
"{name}({qualifier:?}.price) static classification"
);
assert_eq!(window.fun.name(), expected_function);
if metadata && qualifier != Some("B") {
assert_eq!(window.params.args[4], valid_match_row_expr());
}
assert_eq!(
matches!(&window.fun, WindowFunctionDefinition::WindowUDF(_)),
match_independent
);
let expected_frame = match name {
"prev" => WindowFrame::new_bounds(
WindowFrameUnits::Rows,
WindowFrameBound::Preceding(ScalarValue::UInt64(None)),
WindowFrameBound::CurrentRow,
),
"next" => WindowFrame::new_bounds(
WindowFrameUnits::Rows,
WindowFrameBound::CurrentRow,
WindowFrameBound::Following(ScalarValue::UInt64(Some(1))),
),
_ => unreachable!(),
};
assert_eq!(
window.params.window_frame, expected_frame,
"{name}({qualifier:?}.price) frame"
);
let (expected_partition_by, expected_order_by) = if match_independent {
(
vec![col("company")],
vec![SortExpr::new(col("ts"), true, false)],
)
} else {
(
vec![
col("company"),
col(MatchMetadataColumn::MatchNumber.as_ref()),
],
vec![sequence_sort_expr()],
)
};
assert_eq!(window.params.partition_by, expected_partition_by);
assert_eq!(window.params.order_by, expected_order_by);
}
Ok(())
}
#[test]
fn navigation_offset_rejects_first_metadata_overlap_as_plan_error() {
let expr = Expr::Literal(ScalarValue::UInt64(Some(MAX_NAVIGATION_OFFSET + 1)), None);
let error = functions::navigation_offset(Some(&expr), "next")
.expect_err("buffer sequence numbers must not overlap matched rows");
assert!(matches!(error, datafusion_common::DataFusionError::Plan(_)));
assert!(
error
.to_string()
.contains(&MAX_NAVIGATION_OFFSET.to_string())
);
}
#[test]
fn navigation_offset_accepts_exact_metadata_boundary_when_representable() -> Result<()> {
if usize::try_from(MAX_NAVIGATION_OFFSET).is_err() {
return Ok(());
}
let expr = Expr::Literal(ScalarValue::UInt64(Some(MAX_NAVIGATION_OFFSET)), None);
assert_eq!(
functions::navigation_offset(Some(&expr), "prev")?.as_u64(),
MAX_NAVIGATION_OFFSET
);
Ok(())
}
#[test]
fn define_aggregate_filters_require_boolean_before_folding() -> Result<()> {
let schema = test_input_schema();
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &schema);
for (name, arg) in [
(
"sum",
BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".into(),
column: Column::from_name("price"),
}),
),
(
"count",
BoundMatchExpr::Literal(ScalarValue::Int64(Some(1))),
),
("array_agg", source_price_column()),
] {
for filter in [lit(1_i64), lit("true"), lit(true), lit(ScalarValue::Null)] {
let valid = matches!(
filter.get_type(&schema)?,
DataType::Boolean | DataType::Null
);
let result = normalizer.lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(BoundMatchExpr::InputExpr(filter.clone()))),
..plain_aggregate(name, vec![arg.clone()])
}),
);
if valid {
result?;
} else {
let error =
result.expect_err("non-Boolean FILTER must fail before folding");
assert!(
error.to_string().contains("FILTER must be Boolean"),
"{name} FILTER ({filter}): {error}"
);
}
}
}
Ok(())
}
#[test]
fn define_aggregate_filter_is_folded_into_nullable_args() -> Result<()> {
let mut context = datafusion_common::config::ConfigOptions::default();
let input_schema = test_input_schema();
let mut normalizer = define_normalizer(&mut context, &input_schema);
normalizer.partition_by.clear();
let lowered = normalizer.lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(bound_binary(
BoundMatchExpr::InputColumn(Column::from_name("price")),
Operator::Gt,
BoundMatchExpr::Literal(ScalarValue::Int64(Some(0))),
))),
..plain_aggregate(
"sum",
vec![BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".to_string(),
column: Column::from_name("price"),
})],
)
}),
)?;
let Expr::WindowFunction(window) = lowered.expr else {
panic!("expected DEFINE aggregate to lower to a window expression");
};
assert_eq!(
window.params,
WindowFunctionParams {
args: vec![Expr::Case(Case::new(
None,
vec![(
Box::new(col("price").gt(lit(0_i64))),
Box::new(col("price"))
)],
None
))],
partition_by: vec![col("__mr_match_number")],
order_by: vec![SortExpr::new(
col("__mr_match_sequence_number"),
true,
false
)],
window_frame: WindowFrame::new_bounds(
WindowFrameUnits::Rows,
WindowFrameBound::Preceding(ScalarValue::UInt64(None)),
WindowFrameBound::CurrentRow
),
filter: Some(Box::new(col("__mr_classifier_a"))),
distinct: false,
null_treatment: None,
}
);
Ok(())
}
#[test]
fn define_aggregate_order_by_is_allowed() -> Result<()> {
let window = lower_define_window(aggregate_call(
"count",
vec![source_price_column()],
vec![source_price_sort(false, true)],
))?;
assert_eq!(
window.params.order_by,
vec![SortExpr::new(price_column(), false, true)]
);
Ok(())
}
#[test]
fn define_aggregate_filter_guards_observable_order_by_keys_and_preserves_volatile_filters()
-> Result<()> {
let input_schema = test_input_schema();
let price_filter = bound_binary(
BoundMatchExpr::InputColumn(Column::from_name("price")),
Operator::Gt,
BoundMatchExpr::Literal(ScalarValue::Int64(Some(1))),
);
let expected_filter = col("price").gt(lit(1_i64));
let fallible_key = bound_binary(
BoundMatchExpr::Literal(ScalarValue::Int64(Some(12))),
Operator::Divide,
bound_binary(
BoundMatchExpr::InputColumn(Column::from_name("price")),
Operator::Minus,
BoundMatchExpr::Literal(ScalarValue::Int64(Some(1))),
),
);
let expected_fallible_key = lit(12_i64) / (col("price") - lit(1_i64));
let guarded = |filter: Expr, expr: Expr| {
Expr::Case(Case::new(
None,
vec![(Box::new(filter), Box::new(expr))],
None,
))
};
let mixed = lower_define_window(BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(price_filter.clone())),
order_by: vec![
BoundMatchExprSort {
expr: Box::new(BoundMatchExpr::InputColumn(Column::from_name("ts"))),
asc: true,
nulls_first: false,
},
BoundMatchExprSort {
expr: Box::new(fallible_key.clone()),
asc: false,
nulls_first: true,
},
],
..plain_aggregate(
"sum",
vec![BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".to_string(),
column: Column::from_name("price"),
})],
)
}))?;
assert_eq!(
mixed.params.args,
vec![guarded(expected_filter.clone(), col("price"))]
);
assert_eq!(
mixed.params.order_by,
vec![
SortExpr::new(col("ts"), true, false),
SortExpr::new(
guarded(expected_filter.clone(), expected_fallible_key.clone()),
false,
true,
),
]
);
assert_eq!(
mixed.params.filter.as_deref(),
Some(&col("__mr_classifier_a"))
);
let covar = lower_define_window(BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(price_filter.clone())),
order_by: vec![BoundMatchExprSort {
expr: Box::new(fallible_key.clone()),
asc: false,
nulls_first: false,
}],
..plain_aggregate(
"covar_pop",
vec![
BoundMatchExpr::InputColumn(Column::from_name("price")),
BoundMatchExpr::InputColumn(Column::from_name("ts")),
],
)
}))?;
assert_eq!(
covar.params.args,
vec![
guarded(expected_filter.clone(), col("price")),
guarded(expected_filter.clone(), col("ts")),
]
);
assert_eq!(
covar.params.order_by,
vec![SortExpr::new(
guarded(expected_filter.clone(), expected_fallible_key.clone()),
false,
false,
)]
);
assert_eq!(covar.params.filter, None);
let random_expr = datafusion::functions::math::random().call(vec![]);
let volatile_key =
lower_define_window(BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(price_filter.clone())),
order_by: vec![BoundMatchExprSort {
expr: Box::new(BoundMatchExpr::InputExpr(random_expr.clone())),
asc: true,
nulls_first: false,
}],
..plain_aggregate(
"sum",
vec![BoundMatchExpr::InputColumn(Column::from_name("price"))],
)
}))?;
assert_eq!(
volatile_key.params.order_by,
vec![SortExpr::new(
guarded(expected_filter.clone(), random_expr.clone()),
true,
false,
)]
);
assert_eq!(volatile_key.params.filter, None);
let volatile_filter = BoundMatchExpr::InputExpr(random_expr.clone().gt(lit(0.5_f64)));
let expected_volatile_filter = random_expr.gt(lit(0.5_f64));
let retained_volatile =
lower_define_window(BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(volatile_filter.clone())),
order_by: vec![BoundMatchExprSort {
expr: Box::new(fallible_key.clone()),
asc: true,
nulls_first: false,
}],
..plain_aggregate(
"sum",
vec![BoundMatchExpr::InputColumn(Column::from_name("price"))],
)
}))?;
assert_eq!(retained_volatile.params.args, vec![col("price")]);
assert_eq!(
retained_volatile.params.order_by,
vec![SortExpr::new(expected_fallible_key.clone(), true, false)]
);
assert_eq!(
retained_volatile.params.filter.as_deref(),
Some(&expected_volatile_filter)
);
let mut context = datafusion_common::config::ConfigOptions::default();
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(volatile_filter)),
order_by: vec![BoundMatchExprSort {
expr: Box::new(BoundMatchExpr::InputColumn(Column::from_name("ts"))),
asc: true,
nulls_first: false,
}],
..plain_aggregate(
"sum",
vec![BoundMatchExpr::InputColumn(Column::from_name("price"))],
)
}),
)?;
let Expr::WindowFunction(folded_volatile) = lowered.expr else {
panic!("expected DEFINE aggregate to lower to a window expression");
};
assert_eq!(
folded_volatile.params.args,
vec![guarded(expected_volatile_filter, col("price"))]
);
assert_eq!(
folded_volatile.params.order_by,
vec![SortExpr::new(col("ts"), true, false)]
);
assert_eq!(folded_volatile.params.filter, None);
let array_agg = lower_define_window(BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(price_filter)),
order_by: vec![BoundMatchExprSort {
expr: Box::new(fallible_key),
asc: true,
nulls_first: false,
}],
..plain_aggregate(
"array_agg",
vec![BoundMatchExpr::InputColumn(Column::from_name("price"))],
)
}))?;
assert_eq!(array_agg.params.args, vec![col("price")]);
assert_eq!(
array_agg.params.order_by,
vec![SortExpr::new(expected_fallible_key, true, false)]
);
assert_eq!(array_agg.params.filter.as_deref(), Some(&expected_filter));
Ok(())
}
#[test]
fn count_distinct_symbol_wildcard_is_rejected() {
let mut context = datafusion_common::config::ConfigOptions::default();
let input_schema = test_input_schema();
let mut normalizer = define_normalizer(&mut context, &input_schema);
normalizer.partition_by.clear();
let err = normalizer
.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Aggregate(MatchAggregateCall {
distinct: true,
wildcard_symbol: Some("A".to_string()),
..plain_aggregate("count", vec![])
}),
)
.expect_err("COUNT(DISTINCT symbol.*) should be rejected");
assert!(err.to_string().contains("COUNT(DISTINCT A.*)"), "{err}");
}
#[test]
fn all_rows_aggregate_order_by_is_rejected() {
let input_schema = test_input_schema();
for clause in [SourceClause::Measures, SourceClause::ExplicitOutput] {
for call in [
aggregate_call(
"count",
vec![BoundMatchExpr::Literal(ScalarValue::Int64(Some(1)))],
vec![source_price_sort(false, true)],
),
aggregate_call(
"sum",
vec![source_price_column()],
vec![source_price_sort(false, true)],
),
] {
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &input_schema);
normalizer.rows_per_match =
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::Show);
let err = normalizer
.lower_expr(clause, ExprRole::Scalar, call)
.expect_err("ALL ROWS PER MATCH aggregate ORDER BY should be rejected");
assert!(
matches!(err, datafusion_common::DataFusionError::Plan(_)),
"{err}"
);
assert!(err.to_string().contains("ALL ROWS PER MATCH"), "{err}");
}
}
}
#[test]
fn define_aggregate_conditions_retain_metadata_and_null_sum() -> Result<()> {
let input = LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: Arc::new(test_input_schema()),
});
let match_num_positive = bound_binary(
BoundMatchExpr::Metadata(MatchMetadataFunction::MatchNumber),
Operator::Gt,
BoundMatchExpr::Literal(ScalarValue::Int64(Some(0))),
);
let null_sum_is_not_null = BoundMatchExpr::Predicate {
kind: MatchPredicateKind::IsNotNull,
expr: Box::new(aggregate_call(
"sum",
vec![BoundMatchExpr::Literal(ScalarValue::Int64(None))],
vec![],
)),
};
let spec = BoundMatchSpec {
partition_by: vec![],
order_by: vec![MatchRecognizeSortExpr {
expr: BoundMatchExpr::InputColumn(Column::new(Some("t"), "ts")),
direction: MatchRecognizeSortDirection::Asc,
null_ordering: MatchRecognizeNullOrdering::Last,
}],
source_rows_per_match: RowsPerMatch::OneRow,
after_match_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
symbols: vec!["A".to_string()],
definitions: vec![MatchRecognizeDefinition {
symbol: "A".to_string(),
predicate: bound_binary(
match_num_positive,
Operator::And,
null_sum_is_not_null,
),
}],
measures: vec![MatchRecognizeMeasure {
name: Some("p".to_string()),
expression: source_price_column(),
}],
output: MatchRecognizeOutputContract::Derived,
};
let mut context = datafusion_common::config::ConfigOptions::default();
let source = crate::planning::logical::BoundMatchSource::try_new(
&mut context,
input,
spec,
MatchRecognizePlanningCapabilities::default(),
)?;
let lowered =
lower_bound_match_spec(&mut context, source.input(), source.canonical_spec())?;
let Expr::BinaryExpr(predicate) = &lowered.spec.definitions[0].predicate else {
panic!("metadata and aggregate conditions must remain explicit");
};
assert_eq!(predicate.op, Operator::And);
assert_eq!(*predicate.left, col("__mr_match_number").gt(lit(0_i64)));
assert!(matches!(predicate.right.as_ref(), Expr::IsNotNull(expr)
if matches!(expr.as_ref(), Expr::WindowFunction(_))));
Ok(())
}
#[test]
fn define_input_windows_bind_to_normalized_float_and_materialized_volatile_keys()
-> Result<()> {
let float_schema = DFSchema::try_from_qualified_schema(
"t",
&Schema::new(vec![
Field::new("f", DataType::Float64, true),
Field::new("ts", DataType::Int64, true),
Field::new("price", DataType::Int64, true),
]),
)?;
let input = LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: Arc::new(float_schema),
});
let default_frame = WindowFrame::new_bounds(
WindowFrameUnits::Rows,
WindowFrameBound::Preceding(ScalarValue::UInt64(None)),
WindowFrameBound::CurrentRow,
);
let inherited_float_window = Expr::WindowFunction(Box::new(WindowFunction {
fun: WindowFunctionDefinition::AggregateUDF(
datafusion_functions_aggregate::sum::sum_udaf(),
),
params: WindowFunctionParams {
args: vec![Expr::Column(Column::new(Some("t"), "price"))],
partition_by: vec![Expr::Column(Column::new(Some("t"), "f"))],
order_by: vec![SortExpr::new(
Expr::Column(Column::new(Some("t"), "ts")),
true,
false,
)],
window_frame: default_frame.clone(),
filter: None,
distinct: false,
null_treatment: None,
},
}));
let explicit_other_window = Expr::WindowFunction(Box::new(WindowFunction {
fun: WindowFunctionDefinition::AggregateUDF(
datafusion_functions_aggregate::sum::sum_udaf(),
),
params: WindowFunctionParams {
args: vec![Expr::Column(Column::new(Some("t"), "price"))],
partition_by: vec![Expr::Column(Column::new(Some("t"), "ts"))],
order_by: vec![SortExpr::new(
Expr::Column(Column::new(Some("t"), "ts")),
true,
false,
)],
window_frame: default_frame.clone(),
filter: None,
distinct: false,
null_treatment: None,
},
}));
let float_spec = BoundMatchSpec {
partition_by: vec![BoundMatchExpr::InputColumn(Column::new(Some("t"), "f"))],
order_by: vec![MatchRecognizeSortExpr {
expr: BoundMatchExpr::InputColumn(Column::new(Some("t"), "ts")),
direction: MatchRecognizeSortDirection::Asc,
null_ordering: MatchRecognizeNullOrdering::Last,
}],
source_rows_per_match: RowsPerMatch::OneRow,
after_match_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
symbols: vec!["A".to_string()],
definitions: vec![MatchRecognizeDefinition {
symbol: "A".to_string(),
predicate: BoundMatchExpr::InputExpr(
inherited_float_window
.gt(lit(0_i64))
.and(explicit_other_window.gt(lit(0_i64))),
),
}],
measures: vec![MatchRecognizeMeasure {
name: Some("p".to_string()),
expression: source_price_column(),
}],
output: MatchRecognizeOutputContract::Derived,
};
let mut context = datafusion_common::config::ConfigOptions::default();
let float_source = crate::planning::logical::BoundMatchSource::try_new(
&mut context,
input.clone(),
float_spec,
MatchRecognizePlanningCapabilities::default(),
)?;
let float_lowered = lower_bound_match_spec(
&mut context,
float_source.input(),
float_source.canonical_spec(),
)?;
let windows = find_window_exprs([&float_lowered.spec.definitions[0].predicate]);
assert_eq!(windows.len(), 2);
let Expr::WindowFunction(first_wf) = &windows[0] else {
unreachable!()
};
let Expr::WindowFunction(second_wf) = &windows[1] else {
unreachable!()
};
assert_eq!(
first_wf.params.partition_by,
float_lowered.spec.partition_by
);
assert_ne!(
first_wf.params.partition_by,
float_lowered.source_partition_by
);
assert_eq!(
second_wf.params.partition_by,
vec![Expr::Column(Column::new(Some("t"), "ts"))]
);
let random = datafusion::functions::math::random().call(vec![]);
let volatile_window = Expr::WindowFunction(Box::new(WindowFunction {
fun: WindowFunctionDefinition::WindowUDF(
datafusion_functions_window::lead_lag::lag_udwf(),
),
params: WindowFunctionParams {
args: vec![Expr::Column(Column::new(Some("t"), "price"))],
partition_by: vec![random.clone()],
order_by: vec![SortExpr::new(random.clone(), true, false)],
window_frame: default_frame,
filter: None,
distinct: false,
null_treatment: None,
},
}));
let volatile_spec = BoundMatchSpec {
partition_by: vec![BoundMatchExpr::InputExpr(random.clone())],
order_by: vec![MatchRecognizeSortExpr {
expr: BoundMatchExpr::InputExpr(random),
direction: MatchRecognizeSortDirection::Asc,
null_ordering: MatchRecognizeNullOrdering::Last,
}],
source_rows_per_match: RowsPerMatch::OneRow,
after_match_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
symbols: vec!["A".to_string()],
definitions: vec![MatchRecognizeDefinition {
symbol: "A".to_string(),
predicate: BoundMatchExpr::InputExpr(volatile_window.gt(lit(0_i64))),
}],
measures: vec![MatchRecognizeMeasure {
name: Some("p".to_string()),
expression: source_price_column(),
}],
output: MatchRecognizeOutputContract::Derived,
};
let volatile_source = crate::planning::logical::BoundMatchSource::try_new(
&mut context,
input,
volatile_spec,
MatchRecognizePlanningCapabilities::default(),
)?;
let volatile_lowered = lower_bound_match_spec(
&mut context,
volatile_source.input(),
volatile_source.canonical_spec(),
)?;
let windows = find_window_exprs([&volatile_lowered.spec.definitions[0].predicate]);
assert_eq!(windows.len(), 1);
let Expr::WindowFunction(wf) = &windows[0] else {
unreachable!()
};
assert!(!windows[0].is_volatile());
assert_eq!(wf.params.partition_by, volatile_lowered.spec.partition_by);
assert_eq!(
wf.params.order_by,
vec![SortExpr::new(
volatile_lowered.spec.order_by[0].expr.clone(),
true,
false
)]
);
Ok(())
}
#[test]
fn noncanonical_and_navigation_aggregate_names_require_exact_context_registration()
-> Result<()> {
struct ExactCustomFirstContext {
options: datafusion_common::config::ConfigOptions,
custom_first: Arc<AggregateUDF>,
}
impl MatchRecognizePlanningContext for ExactCustomFirstContext {
fn options(&self) -> &datafusion_common::config::ConfigOptions {
&self.options
}
fn aggregate_udf(&self, name: &str) -> Option<Arc<AggregateUDF>> {
(name == "FIRST")
.then(|| Arc::clone(&self.custom_first))
.or_else(|| self.options.aggregate_udf(name))
}
}
let input = LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: Arc::new(test_input_schema()),
});
let measure_spec = |name: &str| BoundMatchSpec {
partition_by: vec![],
order_by: vec![MatchRecognizeSortExpr {
expr: BoundMatchExpr::InputColumn(Column::new(Some("t"), "ts")),
direction: MatchRecognizeSortDirection::Asc,
null_ordering: MatchRecognizeNullOrdering::Last,
}],
source_rows_per_match: RowsPerMatch::OneRow,
after_match_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
symbols: vec!["A".to_string()],
definitions: vec![],
measures: vec![MatchRecognizeMeasure {
name: Some("m".to_string()),
expression: aggregate_call(name, vec![source_price_column()], vec![]),
}],
output: MatchRecognizeOutputContract::Derived,
};
let mut default_context =
crate::planning::DefaultMatchRecognizePlanningContext::new();
for (name, expected_fragment) in [
("FIRST", "not available in the planning context"),
("LAST", "not available in the planning context"),
("First", "not available in the planning context"),
("Last", "not available in the planning context"),
("SUM", "not available in the planning context"),
("first", "structured source expression"),
("last", "structured source expression"),
("prev", "structured source expression"),
("next", "structured source expression"),
("__mr_first_agg", "reserved internal prefix"),
("__mr_last_agg", "reserved internal prefix"),
("__mr_prev_agg", "reserved internal prefix"),
("__mr_next_agg", "reserved internal prefix"),
] {
let error = crate::planning::logical::BoundMatchSource::try_new(
&mut default_context,
input.clone(),
measure_spec(name),
MatchRecognizePlanningCapabilities::default(),
)
.expect_err("unregistered navigation or noncanonical aggregate name must fail");
assert!(
error.to_string().contains(expected_fragment),
"{name}: {error}"
);
}
let input_schema = test_input_schema();
for name in [
"FIRST",
"LAST",
"first",
"last",
"prev",
"next",
"__mr_first_agg",
"__mr_last_agg",
"__mr_prev_agg",
"__mr_next_agg",
] {
let error = define_normalizer(&mut default_context, &input_schema)
.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
aggregate_call(name, vec![source_price_column()], vec![]),
)
.expect_err("direct lowering must not resolve navigation alias as aggregate");
assert!(
error
.to_string()
.contains("not available in the planning context"),
"{name}: {error}"
);
}
let custom_first = Arc::new(AggregateUDF::new_from_impl(SameNameCustomAggregate {
name: "FIRST",
}));
let mut custom_context = ExactCustomFirstContext {
options: datafusion_common::config::ConfigOptions::default(),
custom_first: Arc::clone(&custom_first),
};
let (source, lowered) =
crate::planning::logical::BoundMatchSource::try_new_and_lower(
&mut custom_context,
input.clone(),
measure_spec("FIRST"),
MatchRecognizePlanningCapabilities::default(),
)?;
assert_eq!(source.canonical_spec().as_spec().measures.len(), 1);
let Expr::AggregateFunction(aggregate) = &lowered.spec.measures[0].expression else {
panic!("expected custom FIRST aggregate");
};
assert_eq!(aggregate.func.as_ref(), custom_first.as_ref());
assert_ne!(
aggregate.func.as_ref(),
datafusion_functions_aggregate::first_last::first_value_udaf().as_ref()
);
let unregistered_last = crate::planning::logical::BoundMatchSource::try_new(
&mut custom_context,
input.clone(),
measure_spec("LAST"),
MatchRecognizePlanningCapabilities::default(),
)
.expect_err("unregistered uppercase LAST must still fail");
assert!(
unregistered_last
.to_string()
.contains("not available in the planning context"),
"{unregistered_last}"
);
let canonical_first = crate::planning::logical::BoundMatchSource::try_new(
&mut custom_context,
input,
measure_spec("first"),
MatchRecognizePlanningCapabilities::default(),
)
.expect_err("canonical lowercase first remains reserved for structured navigation");
assert!(
canonical_first
.to_string()
.contains("structured source expression"),
"{canonical_first}"
);
Ok(())
}
#[test]
fn first_last_logical_offset_lowering_preserves_zero_fast_paths_and_routes_positive_offsets()
-> Result<()> {
let input_schema = test_input_schema();
let a_price = || {
BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".to_string(),
column: Column::from_name("price"),
})
};
let lit_u64 = |v: u64| {
Some(Box::new(BoundMatchExpr::Literal(ScalarValue::UInt64(
Some(v),
))))
};
{
let mut context = datafusion_common::config::ConfigOptions::default();
let lowered_zero = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::Last {
expr: Box::new(a_price()),
offset: lit_u64(0),
}),
)?;
assert_eq!(lowered_zero.expr, col("price"));
let lowered_one = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::Last {
expr: Box::new(a_price()),
offset: lit_u64(1),
}),
)?;
let Expr::WindowFunction(window) = lowered_one.expr else {
panic!(
"LAST(A.price, 1) in DEFINE A must remain a window, not collapse to current row"
);
};
assert_eq!(
window.fun,
WindowFunctionDefinition::WindowUDF(crate::functions::udwf::mr_last_udwf())
);
assert_eq!(
window.params.args,
vec![col("price"), lit(1_u64), classifier_mask_expr("A")]
);
}
for (is_first, offset, expected_udaf, expected_arg_count) in [
(
true,
0_u64,
datafusion_functions_aggregate::first_last::first_value_udaf(),
1,
),
(
false,
0_u64,
datafusion_functions_aggregate::first_last::last_value_udaf(),
1,
),
(
true,
2_u64,
crate::functions::udaf::mr_first_offset_udaf(),
2,
),
(
false,
2_u64,
crate::functions::udaf::mr_last_offset_udaf(),
2,
),
] {
let mut context = datafusion_common::config::ConfigOptions::default();
let nav = if is_first {
MatchNavigation::First {
expr: Box::new(a_price()),
offset: lit_u64(offset),
}
} else {
MatchNavigation::Last {
expr: Box::new(a_price()),
offset: lit_u64(offset),
}
};
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Navigation(nav),
)?;
let Expr::AggregateFunction(agg) = lowered.expr else {
panic!("ONE ROW FIRST/LAST must lower to an aggregate");
};
assert_eq!(agg.func.as_ref(), expected_udaf.as_ref());
assert_eq!(agg.params.args.len(), expected_arg_count);
if expected_arg_count == 2 {
assert_eq!(agg.params.args[1], lit(offset));
}
assert!(agg.params.filter.is_some());
}
{
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &input_schema);
normalizer.rows_per_match =
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::Show);
let lowered = normalizer.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(source_price_column()),
offset: lit_u64(3),
}),
)?;
let Expr::WindowFunction(window) = lowered.expr else {
panic!("ALL ROWS FIRST(price, 3) must lower to a window");
};
assert_eq!(
window.fun,
WindowFunctionDefinition::WindowUDF(crate::functions::udwf::mr_first_udwf())
);
assert_eq!(
window.params.args,
vec![
price_column(),
lit(3_u64),
crate::planning::logical::selected_row_filter_expr(),
]
);
}
Ok(())
}
#[test]
fn zero_offset_compound_navigation_preserves_typed_null_default() -> Result<()> {
let schema = test_input_schema();
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &schema);
for clause in [SourceClause::Define { symbol: "A" }, SourceClause::Measures] {
let zero = || {
Some(Box::new(BoundMatchExpr::Literal(ScalarValue::Int64(Some(
0,
)))))
};
let lowered = normalizer.lower_expr(
clause,
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::Prev {
expr: Box::new(BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(BoundMatchExpr::Literal(ScalarValue::Null)),
offset: zero(),
})),
offset: zero(),
default: Some(Box::new(BoundMatchExpr::Cast {
expr: Box::new(BoundMatchExpr::Literal(ScalarValue::Null)),
data_type: DataType::Int64,
})),
}),
)?;
assert_eq!(
lowered.expr.get_type(&normalizer.expression_schema)?,
DataType::Int64
);
assert_eq!(lowered.max_prev_offset.as_u64(), 0);
}
Ok(())
}
#[test]
fn compound_navigation_lowering_canonicalizes_and_enforces_single_rpv() -> Result<()> {
let input_schema = test_input_schema();
let a_price = || {
BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".to_string(),
column: Column::from_name("price"),
})
};
let lit_i64 = |v: i64| {
Some(Box::new(BoundMatchExpr::Literal(ScalarValue::Int64(Some(
v,
)))))
};
{
let mut context = datafusion_common::config::ConfigOptions::default();
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::Prev {
expr: Box::new(BoundMatchExpr::Navigation(MatchNavigation::Last {
expr: Box::new(a_price()),
offset: lit_i64(0),
})),
offset: lit_i64(2),
default: None,
}),
)?;
let Expr::WindowFunction(window) = lowered.expr else {
panic!("PREV(LAST(A.price, 0), 2) in DEFINE A should lower to LAG window");
};
assert_eq!(
window.fun,
WindowFunctionDefinition::WindowUDF(
datafusion_functions_window::lead_lag::lag_udwf()
)
);
}
{
let mut context = datafusion_common::config::ConfigOptions::default();
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::Prev {
expr: Box::new(BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(a_price()),
offset: lit_i64(1),
})),
offset: lit_i64(0),
default: None,
}),
)?;
assert_eq!(lowered.max_prev_offset.as_u64(), 0);
let Expr::AggregateFunction(agg) = lowered.expr else {
panic!(
"PREV(FIRST(A.price, 1), 0) in ONE ROW should lower to __mr_first_agg"
);
};
assert_eq!(
agg.func.as_ref(),
crate::functions::udaf::mr_first_offset_udaf().as_ref()
);
}
{
let mut context = datafusion_common::config::ConfigOptions::default();
let lowered = define_normalizer(&mut context, &input_schema).lower_expr(
SourceClause::Define { symbol: "B" },
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::Next {
expr: Box::new(BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(a_price()),
offset: lit_i64(1),
})),
offset: lit_i64(0),
default: lit_i64(-1),
}),
)?;
let Expr::WindowFunction(window) = lowered.expr else {
panic!("NEXT(FIRST(A.price, 1), 0, -1) in DEFINE must lower to a window");
};
assert_eq!(
window.fun,
WindowFunctionDefinition::AggregateUDF(crate::functions::udaf::mr_prev_udaf())
);
assert_eq!(window.params.args.len(), 7);
assert_eq!(window.params.args[1], lit(0_u64));
assert_eq!(window.params.args[5], lit(true));
assert_eq!(window.params.args[6], lit(1_u64));
}
{
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &input_schema);
normalizer.rows_per_match =
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::Show);
let lowered = normalizer.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::Prev {
expr: Box::new(BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(a_price()),
offset: lit_i64(1),
})),
offset: lit_i64(2),
default: lit_i64(-1),
}),
)?;
assert_eq!(lowered.max_prev_offset.as_u64(), 2);
let windows = find_window_exprs([&lowered.expr]);
assert_eq!(windows.len(), 1);
let Expr::WindowFunction(window) = &windows[0] else {
unreachable!()
};
assert_eq!(
window.fun,
WindowFunctionDefinition::WindowUDF(crate::functions::udwf::mr_prev_udwf())
);
assert_eq!(
window.params.args,
vec![
col("price"),
lit(2_u64),
lit(-1_i64),
lit(true),
lit(1_u64),
classifier_mask_expr("A"),
]
);
}
let mixed_input_and_symbol =
bound_binary(source_price_column(), Operator::Plus, a_price());
let mixed_classifier_and_symbol = bound_binary(
BoundMatchExpr::Metadata(MatchMetadataFunction::Classifier),
Operator::Eq,
BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".to_string(),
column: Column::from_name("company"),
}),
);
for bad_nav in [
MatchNavigation::First {
expr: Box::new(mixed_input_and_symbol.clone()),
offset: None,
},
MatchNavigation::Last {
expr: Box::new(mixed_classifier_and_symbol),
offset: lit_i64(1),
},
MatchNavigation::Prev {
expr: Box::new(mixed_input_and_symbol.clone()),
offset: lit_i64(1),
default: None,
},
MatchNavigation::Next {
expr: Box::new(BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(mixed_input_and_symbol),
offset: lit_i64(1),
})),
offset: lit_i64(1),
default: None,
},
] {
let mut context = datafusion_common::config::ConfigOptions::default();
let error = define_normalizer(&mut context, &input_schema)
.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Navigation(bad_nav),
)
.expect_err("mixing unqualified and symbol-qualified refs inside navigation must fail");
assert!(
error
.to_string()
.contains("cannot mix unqualified and symbol-qualified references"),
"{error}"
);
}
Ok(())
}
#[test]
fn deferred_static_navigation_probes_coercions_for_the_default_type() -> Result<()> {
use datafusion_functions::core::expr_fn::coalesce;
use datafusion_optimizer::analyzer::type_coercion::TypeCoercionRewriter;
let schema = DFSchema::try_from(Schema::new(vec![
Field::new("x", DataType::Int32, true),
Field::new("y", DataType::Int32, true),
]))?;
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &schema);
normalizer.partition_by.clear();
normalizer.order_by = vec![SortExpr::new(col("x"), true, false)];
for (fallback, default, expected_type) in [
(
lit(1.5_f64),
ScalarValue::Float64(Some(2.5)),
DataType::Float64,
),
(
lit(0_i64),
ScalarValue::Int64(Some(3_000_000_000)),
DataType::Int64,
),
] {
let value = coalesce(vec![col("x") / col("y"), fallback]);
for prev in [true, false] {
let expr = Box::new(BoundMatchExpr::InputExpr(value.clone()));
let default_expr = Some(Box::new(BoundMatchExpr::Literal(default.clone())));
let navigation = if prev {
MatchNavigation::Prev {
expr,
offset: None,
default: default_expr,
}
} else {
MatchNavigation::Next {
expr,
offset: None,
default: default_expr,
}
};
let lowered = normalizer.lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Navigation(navigation),
)?;
let Expr::Case(case) = &lowered.expr else {
panic!("fallible navigation must remain demand evaluated");
};
assert_eq!(case.else_expr.as_deref(), Some(&lit(default.clone())));
let coerced = lowered
.expr
.clone()
.rewrite(&mut TypeCoercionRewriter::new(&schema))?
.data;
assert_eq!(coerced.get_type(&schema)?, expected_type);
let shifts = find_window_exprs([&lowered.expr]);
assert_eq!(shifts.len(), 3, "shift x, y, and the presence marker");
assert!(shifts.iter().all(|expr| matches!(expr, Expr::WindowFunction(window)
if matches!(&window.params.args[0], Expr::Column(_) | Expr::Literal(_, _)))));
}
}
Ok(())
}
#[test]
fn deferred_prev_keeps_timestamp_coercions_for_the_session_analyzer() -> Result<()> {
use datafusion::arrow::datatypes::TimeUnit;
use datafusion::common::tree_node::Transformed;
let schema = DFSchema::try_from(Schema::new(vec![
Field::new(
"naive",
DataType::Timestamp(TimeUnit::Nanosecond, None),
true,
),
Field::new(
"aware",
DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
true,
),
Field::new("denom", DataType::Int64, true),
]))?;
let mut context = datafusion_common::config::ConfigOptions::default();
context.execution.time_zone = Some("+02:00".parse()?);
let mut normalizer = define_normalizer(&mut context, &schema);
normalizer.partition_by.clear();
normalizer.order_by = vec![SortExpr::new(col("denom"), true, false)];
let value = col("naive")
.eq(col("aware"))
.and((lit(1_i64) / col("denom")).gt(lit(0_i64)));
let lowered = normalizer.lower_expr(
SourceClause::Define { symbol: "A" },
ExprRole::Scalar,
BoundMatchExpr::Navigation(MatchNavigation::Prev {
expr: Box::new(BoundMatchExpr::InputExpr(value.clone())),
offset: None,
default: None,
}),
)?;
let Expr::Case(case) = &lowered.expr else {
panic!("fallible PREV must remain demand evaluated");
};
assert!(
!lowered
.expr
.exists(|node| Ok(matches!(node, Expr::Cast(_))))?
);
let unshifted = case.when_then_expr[0]
.1
.as_ref()
.clone()
.transform_up(|node| {
if let Expr::WindowFunction(window) = node {
assert_eq!(
window.fun,
WindowFunctionDefinition::WindowUDF(
datafusion_functions_window::lead_lag::lag_udwf(),
)
);
Ok(Transformed::yes(window.params.args[0].clone()))
} else {
Ok(Transformed::no(node))
}
})?
.data;
assert_eq!(unshifted, value);
Ok(())
}
#[test]
fn measure_filters_guard_user_work_with_searched_case() -> Result<()> {
use super::functions::nullable_filtered_arg;
use datafusion_optimizer::analyzer::type_coercion::TypeCoercionRewriter;
let schema = test_input_schema();
let mut context = datafusion_common::config::ConfigOptions::default();
for all_rows in [false, true] {
for symbol_scoped in [false, true] {
let mut normalizer = define_normalizer(&mut context, &schema);
if all_rows {
normalizer.rows_per_match =
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::Show);
}
let arg = if symbol_scoped {
BoundMatchExpr::PatternField(MatchPatternFieldRef {
symbol: "A".into(),
column: Column::new(Some("t"), "price"),
})
} else {
source_price_column()
};
for filter in [
(lit(1_i64) / col("ts")).gt(lit(0_i64)),
datafusion_functions::math::random()
.call(vec![])
.gt(lit(0.5_f64)),
lit(ScalarValue::Null),
] {
let lowered = normalizer.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(BoundMatchExpr::InputExpr(filter.clone()))),
..plain_aggregate("sum", vec![arg.clone()])
}),
)?;
let actual = match &lowered.expr {
Expr::AggregateFunction(aggregate) => {
aggregate.params.filter.as_deref()
}
Expr::WindowFunction(window) => window.params.filter.as_deref(),
other => panic!("expected aggregate: {other:?}"),
};
let mask = if symbol_scoped {
classifier_mask_expr("A")
} else {
crate::planning::logical::is_matched_expr()
};
assert_eq!(actual, Some(&nullable_filtered_arg(mask, filter)));
let coerced = lowered
.expr
.rewrite(&mut TypeCoercionRewriter::new(
normalizer.expression_schema.as_ref(),
))?
.data;
let filter = match &coerced {
Expr::AggregateFunction(aggregate) => &aggregate.params.filter,
Expr::WindowFunction(window) => &window.params.filter,
_ => unreachable!(),
};
assert_eq!(
filter
.as_ref()
.unwrap()
.get_type(normalizer.expression_schema.as_ref())?,
DataType::Boolean
);
}
}
}
Ok(())
}
#[test]
fn all_rows_measure_windows_guard_args_when_materialized() -> Result<()> {
use crate::planning::logical::utils::materialize_windows;
use datafusion::logical_expr::LogicalPlanBuilder;
let schema = test_input_schema();
let mut context = datafusion_common::config::ConfigOptions::default();
let mut normalizer = define_normalizer(&mut context, &schema);
normalizer.rows_per_match =
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::Show);
for arg in [
source_price_column(),
bound_binary(
BoundMatchExpr::Literal(ScalarValue::Int64(Some(1))),
Operator::Divide,
source_price_column(),
),
BoundMatchExpr::InputExpr(datafusion_functions::math::random().call(vec![])),
] {
let lowered = normalizer.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
BoundMatchExpr::Aggregate(MatchAggregateCall {
filter: Some(Box::new(BoundMatchExpr::InputExpr(
datafusion_functions::math::random()
.call(vec![])
.gt(lit(0.5_f64)),
))),
..plain_aggregate("sum", vec![arg])
}),
)?;
let Expr::WindowFunction(original) = &lowered.expr else {
panic!("window")
};
let safe = crate::planning::expr_safety::can_discard_scalar(
&original.params.args[0],
Some(normalizer.expression_schema.as_ref()),
);
let input = LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: Arc::clone(&normalizer.expression_schema),
});
let expected_field = lowered.expr.to_field(input.schema().as_ref())?.1;
let (plan, bindings) =
materialize_windows(input.clone(), std::slice::from_ref(&lowered.expr), [])?;
let actual_field = plan
.schema()
.field_with_unqualified_name(&bindings.column(&lowered.expr)?.name)?;
assert_eq!(actual_field.data_type(), expected_field.data_type());
assert_eq!(actual_field.is_nullable(), expected_field.is_nullable());
let LogicalPlan::Window(window) = &plan else {
panic!("window plan")
};
if safe {
let expected = LogicalPlanBuilder::window_plan(
input,
bindings.aliased_expressions_from(0),
)?;
assert_eq!(plan, expected, "safe arguments must keep the original plan");
} else {
let Expr::Alias(alias) = &window.window_expr[0] else {
panic!("window alias")
};
let Expr::WindowFunction(function) = alias.expr.as_ref() else {
panic!("window expression")
};
assert!(matches!(&function.params.args[0], Expr::Column(_)));
assert!(matches!(
function.params.filter.as_deref(),
Some(Expr::Column(_))
));
let LogicalPlan::Projection(values) = window.input.as_ref() else {
panic!("guarded values")
};
let LogicalPlan::Projection(filters) = values.input.as_ref() else {
panic!("shared filter")
};
assert_eq!(
filters
.expr
.iter()
.filter(|expr| expr.is_volatile())
.count(),
1
);
}
}
Ok(())
}