use std::collections::HashMap;
use std::sync::Arc;
use crate::execution::matching::ExecutableMatchProgram;
use crate::nfa::{CompiledAutomaton, PatternCompileLimits, SymbolStatus};
use datafusion::arrow::compute::SortOptions;
use datafusion::catalog::Session;
use datafusion::common::{DataFusionError, Result, internal_err};
use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
use datafusion::physical_expr::PhysicalExpr;
use datafusion::physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
use datafusion::physical_plan::ExecutionPlan;
use datafusion::physical_planner::PhysicalPlanner;
use crate::execution::physical::properties::{
PhysicalPropertiesInput, PropertiesBuilder, ordered_partition_by_indices,
};
use crate::core::{NormalizedPattern, Pattern, SymbolId};
use crate::nfa::display_pattern_or_clone;
use crate::planning::logical::{LogicalMatchProgram, MatchRecognize};
#[derive(Clone)]
pub(crate) struct PreparedPattern {
pub(crate) display_pattern: Pattern,
pub(crate) normalized_pattern: NormalizedPattern,
pub(crate) compiled_automaton: Arc<CompiledAutomaton>,
}
#[derive(Debug, Clone)]
pub(crate) struct MatchPlanLayout {
pub(super) input: Arc<dyn ExecutionPlan>,
pub(super) grouped_input: bool,
pub(super) bypass_never_ordering: bool,
pub(super) partition_by: Vec<Arc<dyn PhysicalExpr>>,
pub(super) order_by: Option<LexOrdering>,
pub(super) cache: Arc<datafusion::physical_plan::execution_plan::PlanProperties>,
pub(super) maintains_input_order: bool,
pub(super) ordered_partition_by_indices: Vec<usize>,
}
pub(crate) struct PatternPreparationInput<'a> {
pub(crate) pattern: &'a Pattern,
pub(crate) symbols: &'a [String],
pub(crate) disjoint_symbols: &'a [(String, String)],
pub(crate) implies_symbols: &'a [(String, String)],
pub(crate) symbol_status: &'a HashMap<String, SymbolStatus>,
pub(crate) pattern_compile_limits: PatternCompileLimits,
}
pub(crate) fn runtime_symbol_ids(logical_len: usize) -> Result<Vec<SymbolId>> {
let Some(runtime_len) = logical_len.checked_add(1) else {
return internal_err!("MATCH_RECOGNIZE symbol count overflow");
};
(1..runtime_len)
.map(|index| SymbolId::try_new(index, runtime_len))
.collect::<Option<_>>()
.ok_or_else(|| DataFusionError::Internal("invalid runtime symbol table".into()))
}
pub(crate) fn validate_compiled_symbol_alignment(
program: &LogicalMatchProgram,
runtime_symbols: &[SymbolId],
automaton: &CompiledAutomaton,
) -> Result<()> {
let aligned =
automaton.num_symbols() == runtime_symbols.len() + 1
&& automaton.id_to_symbol().first() == Some(&None)
&& program.symbols().iter().zip(runtime_symbols).all(
|(symbol, runtime_id)| {
automaton.id_to_symbol()[runtime_id.index()].as_deref()
== Some(symbol.name())
},
);
if !aligned {
return internal_err!(
"MATCH_RECOGNIZE compiled symbol table disagrees with the logical program"
);
}
Ok(())
}
fn normalize_pattern_for_compilation(
input: &PatternPreparationInput<'_>,
) -> NormalizedPattern {
use crate::nfa::PatternOptimizer;
let pattern = input.pattern;
let static_optimizer = PatternOptimizer::new(input.symbol_status)
.with_disjoint_symbols(input.disjoint_symbols)
.with_implies_symbols(input.implies_symbols)
.with_allow_pruning(!input.symbol_status.is_empty());
let normalized = static_optimizer.optimize(pattern);
match &normalized {
NormalizedPattern::Ast(optimized) if optimized != pattern => {
log::debug!(
"Construction-time pattern normalization applied: {pattern:?} -> {optimized:?}"
);
}
NormalizedPattern::Never => {
log::debug!(
"Construction-time pattern normalization detected Never for pattern: {pattern:?}"
);
}
NormalizedPattern::Epsilon => {
log::debug!(
"Construction-time pattern normalization detected Epsilon for pattern: {pattern:?}"
);
}
NormalizedPattern::Ast(_) => {}
}
normalized
}
pub(crate) fn prepare_pattern(
pattern_input: PatternPreparationInput<'_>,
) -> Result<PreparedPattern> {
let normalized_pattern = normalize_pattern_for_compilation(&pattern_input);
let display_pattern =
display_pattern_or_clone(&normalized_pattern, pattern_input.pattern);
let compiled_automaton = Arc::new(CompiledAutomaton::compile_with_limits(
&normalized_pattern,
pattern_input.symbols,
pattern_input.pattern_compile_limits,
)?);
Ok(PreparedPattern {
display_pattern,
normalized_pattern,
compiled_automaton,
})
}
impl MatchPlanLayout {
pub(crate) fn bind_partition_by(
planner: &dyn PhysicalPlanner,
mr: &MatchRecognize,
session: &dyn Session,
ctx: &PhysicalPlanningContext,
) -> Result<Vec<Arc<dyn PhysicalExpr>>> {
mr.program()
.partition_by()
.iter()
.map(|expr| {
planner.create_physical_expr(expr, mr.input().schema(), session, ctx)
})
.collect()
}
pub(crate) fn bind_order_by(
planner: &dyn PhysicalPlanner,
mr: &MatchRecognize,
session: &dyn Session,
ctx: &PhysicalPlanningContext,
) -> Result<Vec<PhysicalSortExpr>> {
mr.program()
.order_by()
.iter()
.map(|sort| {
Ok(PhysicalSortExpr {
expr: planner.create_physical_expr(
&sort.expr,
mr.input().schema(),
session,
ctx,
)?,
options: SortOptions {
descending: !sort.asc,
nulls_first: sort.nulls_first,
},
})
})
.collect()
}
pub(crate) fn try_new(
input: Arc<dyn ExecutionPlan>,
partition_by: Vec<Arc<dyn PhysicalExpr>>,
order_by: Option<LexOrdering>,
program: &ExecutableMatchProgram,
) -> Result<Self> {
Self::try_new_with_bypass(input, partition_by, order_by, program, true)
}
pub(super) fn try_new_with_bypass(
input: Arc<dyn ExecutionPlan>,
partition_by: Vec<Arc<dyn PhysicalExpr>>,
order_by: Option<LexOrdering>,
program: &ExecutableMatchProgram,
bypass_never_ordering: bool,
) -> Result<Self> {
let bypass_never_ordering = bypass_never_ordering
&& program_bypasses_ordering_for_never(
program,
&partition_by,
order_by.as_ref(),
);
let grouped = input
.downcast_ref::<datafusion_hash_grouped_order::HashGroupedOrderExec>()
.filter(|group| {
super::compatible_group(group, &partition_by, order_by.as_ref())
});
let grouped_input = grouped.is_some();
let unordered_groups = grouped.is_some_and(|group| {
group.config().emit_order
== datafusion_hash_grouped_order::GroupEmitOrder::Unordered
});
let ordered_partition_by_indices =
ordered_partition_by_indices(&partition_by, &input)?;
let skips_past_last_row = matches!(
program.after_match_skip(),
crate::execution::matching::ResolvedAfterMatchSkip::PastLastRow
);
let has_zero_navigation_offsets = !program
.output_plan()
.stream()
.emits_navigation_buffer_rows();
let preserves_input_uniqueness =
skips_past_last_row && has_zero_navigation_offsets;
let properties = PropertiesBuilder::try_new(PhysicalPropertiesInput {
input: &input,
schema: program.output_schema(),
partition_by: &partition_by,
ordered_partition_by_indices: &ordered_partition_by_indices,
order_by: &order_by,
output_spec: program.output_spec(),
zero_output_navigation: has_zero_navigation_offsets,
maintains_input_order: !unordered_groups
&& !bypass_never_ordering
&& skips_past_last_row
&& has_zero_navigation_offsets,
preserves_input_uniqueness,
interleaves_logical_partitions: program
.stream_requirements()
.interleaves_logical_partitions,
ordered_unmatched: program.emits_ordered_unmatched(),
rows_per_match: program.rows_per_match(),
retention: super::PartitionRetention::for_program(program),
bounded_match: program.compiled_automaton().max_match_rows().is_some(),
bypass_never_ordering,
})?;
let maintains_input_order = properties.maintains_input_order();
let cache = Arc::new(properties.compute()?);
Ok(Self {
input,
grouped_input,
bypass_never_ordering,
partition_by,
order_by,
cache,
maintains_input_order,
ordered_partition_by_indices,
})
}
pub(super) fn rebuild_with_input(
&self,
input: Arc<dyn ExecutionPlan>,
program: &ExecutableMatchProgram,
) -> Result<Self> {
Self::try_new_with_bypass(
input,
self.partition_by.clone(),
self.order_by.clone(),
program,
self.bypass_never_ordering,
)
}
pub(super) fn rebuild_with_bypass(
&self,
bypass_never_ordering: bool,
program: &ExecutableMatchProgram,
) -> Result<Self> {
Self::try_new_with_bypass(
Arc::clone(&self.input),
self.partition_by.clone(),
self.order_by.clone(),
program,
bypass_never_ordering,
)
}
}
pub(super) fn program_bypasses_ordering_for_never(
program: &ExecutableMatchProgram,
partition_by: &[Arc<dyn PhysicalExpr>],
order_by: Option<&LexOrdering>,
) -> bool {
use crate::core::{EmptyMatchesMode, RowsPerMatch};
use datafusion::physical_expr::expressions::Column;
!matches!(
program.rows_per_match(),
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
) && program.is_infallible_never()
&& partition_by
.iter()
.all(|expr| expr.downcast_ref::<Column>().is_some())
&& order_by.is_none_or(|ordering| {
ordering
.iter()
.all(|sort| sort.expr.downcast_ref::<Column>().is_some())
})
}