use std::ops::Not;
use std::sync::Arc;
use crate::core::{
EmptyMatchesMode, MAX_VALID_MATCH_SEQUENCE_NUMBER, MIN_VALID_MATCH_SEQUENCE_NUMBER,
MatchMetadataColumn, NavigationOffsets, RowsPerMatch,
};
use datafusion::common::{DFSchema, Result};
use datafusion::logical_expr::{
Expr, Extension, LogicalPlan, LogicalPlanBuilder, SortExpr, col, lit,
};
use crate::planning::logical::utils::rows_projection_expr;
use crate::planning::logical::valid_match_row_expr;
use crate::planning::measures;
use super::AssembledNode;
pub(crate) fn finalize_output_with_navigation_offsets(
assembled: AssembledNode,
rows_per_match: &RowsPerMatch,
table_schema: &Arc<DFSchema>,
navigation_offsets: NavigationOffsets,
source_partition_by: &[Expr],
source_order_by: &[SortExpr],
) -> Result<LogicalPlan> {
let AssembledNode {
matcher,
mut measures_exprs,
mut logical_partition_by,
has_exclusions,
} = assembled;
if rows_per_match == &RowsPerMatch::AllRows(EmptyMatchesMode::Omit)
&& navigation_offsets.is_zero()
&& !has_exclusions
{
measures::omit_classified_row_filter(&mut measures_exprs)?;
}
let matcher_finalizes_summaries =
matcher.program().output().finalizes_selected_summaries();
let plan = LogicalPlan::Extension(Extension {
node: Arc::new(matcher),
});
let (plan, measures_exprs) =
measures::apply_windows_and_rebase_measures(plan, measures_exprs, true)?;
let plan = if let Some(filter_expr) =
buffer_row_filter_expr(navigation_offsets, rows_per_match)
{
LogicalPlanBuilder::from(plan)
.filter(filter_expr)?
.build()?
} else {
plan
};
let (plan, measures_exprs) =
measures::apply_windows_and_rebase_measures(plan, measures_exprs, false)?;
let (plan, measures_exprs) = match rows_per_match {
RowsPerMatch::OneRow => {
if matcher_finalizes_summaries {
(plan, measures_exprs)
} else {
let (plan, measures, partition_outputs) =
measures::apply_aggregate_and_rebase_measures(
plan,
measures_exprs,
&logical_partition_by,
)?;
logical_partition_by = partition_outputs;
(plan, measures)
}
}
_ => {
let plan = if has_exclusions {
let excluded_col = col(MatchMetadataColumn::Excluded.as_ref());
let pred = excluded_col.not();
LogicalPlanBuilder::from(plan).filter(pred)?.build()?
} else {
plan
};
(plan, measures_exprs)
}
};
let partition_outputs = if matches!(rows_per_match, RowsPerMatch::OneRow) {
logical_partition_by
.into_iter()
.zip(source_partition_by)
.map(|(output, source)| {
let (relation, name) = source.qualified_name();
if output.qualified_name() == (relation.clone(), name.clone()) {
output
} else {
output.alias_qualified(relation, name)
}
})
.collect::<Vec<_>>()
} else {
source_partition_by.to_vec()
};
let projection_exprs = rows_projection_expr(
rows_per_match,
table_schema,
&partition_outputs,
source_order_by,
&measures_exprs,
);
LogicalPlanBuilder::from(plan)
.project(projection_exprs)?
.build()
}
fn buffer_row_filter_expr(
navigation_offsets: NavigationOffsets,
rows_per_match: &RowsPerMatch,
) -> Option<Expr> {
if matches!(rows_per_match, RowsPerMatch::OneRow) {
return None;
}
let seq_col = || col(MatchMetadataColumn::MatchSequenceNumber.as_ref());
let matched_row_expr = match (
!navigation_offsets.previous().is_zero(),
!navigation_offsets.next().is_zero(),
) {
(false, false) => return None,
(true, true) => valid_match_row_expr(),
(true, false) => seq_col().gt_eq(lit(MIN_VALID_MATCH_SEQUENCE_NUMBER)),
(false, true) => seq_col().lt_eq(lit(MAX_VALID_MATCH_SEQUENCE_NUMBER)),
};
Some(
if matches!(
rows_per_match,
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
) {
seq_col().is_null().or(matched_row_expr)
} else {
matched_row_expr
},
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::NavigationOffset;
#[test]
fn output_filter_keeps_the_exact_inclusive_sequence_maximum() {
let next_only =
NavigationOffsets::new(NavigationOffset::ZERO, NavigationOffset::ONE);
assert_eq!(
buffer_row_filter_expr(
next_only,
&RowsPerMatch::AllRows(EmptyMatchesMode::Show),
),
Some(col("__mr_match_sequence_number").lt_eq(lit((1_i64 << 62) - 1)))
);
}
#[test]
fn all_rows_first_and_last_run_after_buffer_row_filter() -> Result<()> {
use crate::core::{
AfterMatchSkip, MatchRecognizeDefinition, MatchRecognizeMeasure,
MatchRecognizeNullOrdering, MatchRecognizeOutputContract,
MatchRecognizeSortDirection, MatchRecognizeSortExpr, Pattern, Symbol,
};
use crate::functions::udwf::{mr_first_udwf, mr_last_udwf, mr_prev_udwf};
use crate::planning::{
BoundMatchExpr, BoundMatchSpec, DefaultMatchRecognizePlanningContext,
MatchNavigation, plan_match_recognize_from_source,
};
use datafusion::common::{Column, ScalarValue};
use datafusion::logical_expr::{Operator, WindowFunctionDefinition};
let input = LogicalPlanBuilder::values(vec![
vec![lit(1_i64), lit(0_i64)],
vec![lit(2_i64), lit(5_i64)],
])?
.project(vec![col("column1").alias("ord"), col("column2").alias("x")])?
.build()?;
let ratio = || BoundMatchExpr::Binary {
left: Box::new(BoundMatchExpr::Literal(ScalarValue::Int64(Some(100)))),
op: Operator::Divide,
right: Box::new(BoundMatchExpr::InputColumn(Column::from_name("x"))),
};
let spec = BoundMatchSpec {
partition_by: vec![],
order_by: vec![MatchRecognizeSortExpr {
expr: BoundMatchExpr::InputColumn(Column::from_name("ord")),
direction: MatchRecognizeSortDirection::Asc,
null_ordering: MatchRecognizeNullOrdering::Last,
}],
source_rows_per_match: RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
after_match_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Symbol(Symbol::Named("A".into())),
symbols: vec!["A".into()],
definitions: vec![MatchRecognizeDefinition {
symbol: "A".into(),
predicate: BoundMatchExpr::InputExpr(col("x").gt(lit(0_i64))),
}],
measures: vec![
MatchRecognizeMeasure {
name: Some("prev_x".into()),
expression: BoundMatchExpr::Navigation(MatchNavigation::Prev {
expr: Box::new(BoundMatchExpr::InputColumn(Column::from_name(
"x",
))),
offset: Some(Box::new(BoundMatchExpr::Literal(
ScalarValue::Int64(Some(1)),
))),
default: Some(Box::new(BoundMatchExpr::Literal(
ScalarValue::Int64(Some(-1)),
))),
}),
},
MatchRecognizeMeasure {
name: Some("first_ratio".into()),
expression: BoundMatchExpr::Navigation(MatchNavigation::First {
expr: Box::new(ratio()),
offset: None,
}),
},
MatchRecognizeMeasure {
name: Some("last_ratio".into()),
expression: BoundMatchExpr::Navigation(MatchNavigation::Last {
expr: Box::new(ratio()),
offset: None,
}),
},
],
output: MatchRecognizeOutputContract::Derived,
};
let plan = plan_match_recognize_from_source(
&mut DefaultMatchRecognizePlanningContext::new(),
input,
spec,
)?;
let window_udwfs = |exprs: &[Expr]| {
exprs
.iter()
.map(|expr| match expr {
Expr::Alias(alias) => alias.expr.as_ref(),
other => other,
})
.filter_map(|expr| match expr {
Expr::WindowFunction(wf) => match &wf.fun {
WindowFunctionDefinition::WindowUDF(udf) => Some(Arc::clone(udf)),
_ => None,
},
_ => None,
})
.collect::<Vec<_>>()
};
let LogicalPlan::Projection(projection) = &plan else {
panic!("expected final projection, got {plan:?}");
};
let LogicalPlan::Window(post_filter) = projection.input.as_ref() else {
panic!("expected post-filter Window for FIRST/LAST, got {plan:?}");
};
let LogicalPlan::Filter(buffer_filter) = post_filter.input.as_ref() else {
panic!("expected buffer-row Filter below post-filter Window, got {plan:?}");
};
let LogicalPlan::Window(pre_filter) = buffer_filter.input.as_ref() else {
panic!("expected pre-filter Window for PREV, got {plan:?}");
};
assert_eq!(
buffer_filter.predicate,
col(MatchMetadataColumn::MatchSequenceNumber.as_ref())
.gt_eq(lit(MIN_VALID_MATCH_SEQUENCE_NUMBER))
);
let post_udwfs = window_udwfs(&post_filter.window_expr);
assert_eq!(post_udwfs.len(), 2);
assert!(post_udwfs.contains(&mr_first_udwf()));
assert!(post_udwfs.contains(&mr_last_udwf()));
assert_eq!(window_udwfs(&pre_filter.window_expr), vec![mr_prev_udwf()]);
Ok(())
}
}