use crate::core::{
MAX_NAVIGATION_OFFSET, MatchMetadataColumn, MatchRecognizeDefinition,
MatchRecognizeMeasure, MatchRecognizeOutputContract, MatchRecognizeSortDirection,
NavigationOffset, NavigationOffsets, RowsPerMatch, classifier_bits_col_name,
is_reserved_internal_column_name,
};
use crate::planning::define::{StaticAnalysis, is_static};
use crate::planning::expr_safety::can_precompute;
use crate::planning::logical::LoweredMatchSpec;
use crate::planning::logical::utils::build_match_aware_schema;
use crate::planning::phases::materialize_volatile_keys;
use crate::planning::source::{
BoundMatchAggregateCall, BoundMatchExpr, BoundMatchExprSort, BoundMatchNavigation,
BoundMatchSpec, CanonicalBoundMatchSpec, MatchMetadataFunction, MatchNavigation,
MatchPatternFieldRef, MatchPredicateKind, MatchUnaryOperator,
};
use crate::planning::{MatchRecognizePlanningContext, NamedExpr};
use datafusion::arrow::datatypes::DataType;
use datafusion::common::tree_node::TreeNode;
use datafusion::common::{Column, DFSchema, DFSchemaRef, Result, ScalarValue, plan_err};
use datafusion::logical_expr::expr::{
AggregateFunction, BinaryExpr, Case, ScalarFunction, WindowFunction,
WindowFunctionParams,
};
use datafusion::logical_expr::utils::{find_aggregate_exprs, find_window_exprs};
use datafusion::logical_expr::{
AggregateUDF, Expr, ExprSchemable, LogicalPlan, SortExpr, WindowFrame,
WindowFrameBound, WindowFrameUnits, WindowFunctionDefinition, WindowUDF, col, lit,
};
#[cfg(test)]
pub(crate) use functions::canonical_navigation_aggregate_params;
pub(crate) use functions::{
builtin_aggregate_udf, canonical_define_navigation_window_params,
classifier_mask_expr, literal_nonnegative_u64, simplified_literal,
};
use std::collections::BTreeSet;
use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SourceClause<'a> {
PartitionBy,
OrderBy,
Define { symbol: &'a str },
Measures,
ExplicitOutput,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ExprRole {
RowLevel,
Scalar,
AggregateArg,
NavigationValue,
NavigationDefault,
FirstLastArg,
}
#[derive(Debug)]
struct LoweredExpr {
expr: Expr,
symbols: BTreeSet<String>,
has_universal_rpv: bool,
max_prev_offset: NavigationOffset,
max_next_offset: NavigationOffset,
}
impl LoweredExpr {
fn new(expr: Expr) -> Self {
Self {
expr,
symbols: BTreeSet::new(),
has_universal_rpv: false,
max_prev_offset: NavigationOffset::ZERO,
max_next_offset: NavigationOffset::ZERO,
}
}
fn with_symbol(expr: Expr, symbol: String) -> Self {
Self {
symbols: BTreeSet::from([symbol]),
..Self::new(expr)
}
}
fn merge_offsets(&mut self, other: &Self) {
self.max_prev_offset = self.max_prev_offset.max(other.max_prev_offset);
self.max_next_offset = self.max_next_offset.max(other.max_next_offset);
}
fn take_child(&mut self, child: Self) -> Expr {
self.merge_offsets(&child);
self.symbols.extend(child.symbols);
self.has_universal_rpv |= child.has_universal_rpv;
child.expr
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum CurrentRow {
Enabled,
Applied,
Disabled,
}
struct BoundExprLowerer<'a> {
context: &'a mut dyn MatchRecognizePlanningContext,
input_schema: &'a DFSchema,
expression_schema: DFSchemaRef,
rows_per_match: RowsPerMatch,
pattern_symbols: BTreeSet<String>,
source_partition_by: Vec<Expr>,
source_order_by: Vec<SortExpr>,
partition_by: Vec<Expr>,
order_by: Vec<SortExpr>,
current_row: CurrentRow,
}
pub(crate) struct LoweredSourceMatch {
pub(crate) input: LogicalPlan,
pub(crate) spec: LoweredMatchSpec,
pub(crate) navigation_offsets: NavigationOffsets,
pub(crate) source_partition_by: Vec<Expr>,
pub(crate) source_order_by: Vec<SortExpr>,
pub(crate) volatile_key_exprs: Vec<NamedExpr>,
}
pub(crate) fn lower_bound_match_spec(
context: &mut dyn MatchRecognizePlanningContext,
input: &LogicalPlan,
spec: &CanonicalBoundMatchSpec,
) -> Result<LoweredSourceMatch> {
let input_schema = input.schema().as_ref();
let source = spec.as_spec();
let pattern_symbols = source.symbols.iter().cloned().collect();
let expression_schema = build_match_aware_schema(input.schema(), &pattern_symbols)?;
let spec = source.clone();
let BoundMatchSpec {
partition_by,
order_by,
source_rows_per_match,
after_match_skip,
pattern,
symbols,
definitions,
measures,
output,
} = spec;
let mut key_lowerer = BoundExprLowerer {
context,
input_schema,
expression_schema: Arc::clone(&expression_schema),
rows_per_match: source_rows_per_match.clone(),
pattern_symbols,
source_partition_by: vec![],
source_order_by: vec![],
partition_by: vec![],
order_by: vec![],
current_row: CurrentRow::Enabled,
};
let mut partition_by = partition_by
.into_iter()
.map(|expr| {
let lowered = key_lowerer.lower_expr(
SourceClause::PartitionBy,
ExprRole::RowLevel,
expr,
)?;
crate::planning::type_validation::validate_expr(
&lowered.expr,
&expression_schema,
)?;
Ok(lowered.expr)
})
.collect::<Result<Vec<_>>>()?;
let mut order_by = order_by
.into_iter()
.map(|sort| {
let lowered = key_lowerer.lower_expr(
SourceClause::OrderBy,
ExprRole::RowLevel,
sort.expr,
)?;
crate::planning::type_validation::validate_expr(
&lowered.expr,
&expression_schema,
)?;
Ok(SortExpr::new(
lowered.expr,
matches!(sort.direction, MatchRecognizeSortDirection::Asc),
matches!(
sort.null_ordering,
crate::core::MatchRecognizeNullOrdering::First
),
))
})
.collect::<Result<Vec<_>>>()?;
let pattern_symbols = key_lowerer.pattern_symbols;
for expr in partition_by
.iter()
.chain(order_by.iter().map(|sort| &sort.expr))
{
expr.get_type(input_schema)?;
}
let source_partition_by = partition_by.clone();
let source_order_by = order_by.clone();
crate::planning::phases::normalize_partition_keys(&mut partition_by, input_schema)?;
let (input, volatile_key_exprs) = materialize_volatile_keys(
input,
&mut partition_by,
&mut order_by,
measures
.iter()
.filter_map(|measure| measure.name.as_deref()),
)?;
let input_schema = input.schema().as_ref();
let expression_schema = if volatile_key_exprs.is_empty() {
expression_schema
} else {
build_match_aware_schema(input.schema(), &pattern_symbols)?
};
let mut normalizer = BoundExprLowerer {
context,
input_schema,
expression_schema: Arc::clone(&expression_schema),
rows_per_match: source_rows_per_match.clone(),
pattern_symbols,
source_partition_by: source_partition_by.clone(),
source_order_by: source_order_by.clone(),
partition_by: partition_by.clone(),
order_by: order_by.clone(),
current_row: CurrentRow::Enabled,
};
let mut max_prev_offset = NavigationOffset::ZERO;
let mut max_next_offset = NavigationOffset::ZERO;
let definitions = definitions
.into_iter()
.zip(&source.definitions)
.map(|(definition, original)| {
let lowered = normalizer.lower_define(
&definition.symbol,
definition.predicate,
&original.predicate,
)?;
crate::planning::type_validation::validate_expr(
&lowered.expr,
&expression_schema,
)?;
Ok(MatchRecognizeDefinition {
symbol: definition.symbol,
predicate: lowered.expr,
})
})
.collect::<Result<Vec<_>>>()?;
let measures = measures
.into_iter()
.map(|measure| {
let lowered = normalizer.lower_expr(
SourceClause::Measures,
ExprRole::Scalar,
measure.expression,
)?;
crate::planning::type_validation::validate_expr(
&lowered.expr,
&expression_schema,
)?;
max_prev_offset = max_prev_offset.max(lowered.max_prev_offset);
max_next_offset = max_next_offset.max(lowered.max_next_offset);
Ok(MatchRecognizeMeasure {
name: measure.name,
expression: lowered.expr,
})
})
.collect::<Result<Vec<_>>>()?;
let output = match output {
MatchRecognizeOutputContract::Derived => MatchRecognizeOutputContract::Derived,
MatchRecognizeOutputContract::ExplicitNamedExpressions(expressions) => {
let mut normalized = Vec::with_capacity(expressions.len());
for output in expressions {
let lowered = normalizer.lower_expr(
SourceClause::ExplicitOutput,
ExprRole::Scalar,
output.expression,
)?;
crate::planning::type_validation::validate_expr(
&lowered.expr,
&expression_schema,
)?;
max_prev_offset = max_prev_offset.max(lowered.max_prev_offset);
max_next_offset = max_next_offset.max(lowered.max_next_offset);
normalized.push(crate::core::MatchRecognizeNamedExpression {
name: output.name,
expression: lowered.expr,
});
}
MatchRecognizeOutputContract::ExplicitNamedExpressions(normalized)
}
};
Ok(LoweredSourceMatch {
input,
spec: LoweredMatchSpec {
partition_by,
order_by: order_by
.into_iter()
.map(|sort| crate::core::MatchRecognizeSortExpr {
expr: sort.expr,
direction: if sort.asc {
MatchRecognizeSortDirection::Asc
} else {
MatchRecognizeSortDirection::Desc
},
null_ordering: if sort.nulls_first {
crate::core::MatchRecognizeNullOrdering::First
} else {
crate::core::MatchRecognizeNullOrdering::Last
},
})
.collect(),
source_rows_per_match,
after_match_skip,
pattern,
symbols,
definitions,
measures,
output,
},
navigation_offsets: NavigationOffsets::new(max_prev_offset, max_next_offset),
source_partition_by,
source_order_by,
volatile_key_exprs,
})
}
mod functions;
mod normalization;
#[cfg(test)]
mod tests;
impl BoundExprLowerer<'_> {
pub(super) fn lower_define(
&mut self,
symbol: &str,
predicate: BoundMatchExpr,
original: &BoundMatchExpr,
) -> Result<LoweredExpr> {
self.current_row = CurrentRow::Enabled;
let clause = SourceClause::Define { symbol };
let lowered = self.lower_expr(clause, ExprRole::Scalar, predicate)?;
if self.current_row == CurrentRow::Applied {
if !can_precompute(&lowered.expr, &self.expression_schema)
&& !is_static(
&lowered.expr,
StaticAnalysis::new(&self.pattern_symbols, &BTreeSet::new()),
)
{
self.current_row = CurrentRow::Disabled;
return self.lower_expr(clause, ExprRole::Scalar, original.clone());
}
}
Ok(lowered)
}
}