use std::sync::Arc;
use crate::core::{
MatchMetadataColumn, MatchRecognizeOutputContract, MatchRecognizeOutputSpec,
MatchRecognizeSortDirection, NavigationOffsets, RowsPerMatch,
};
use crate::planning::NamedExpr;
use crate::planning::bound_expr_lowering::LoweredSourceMatch;
use crate::planning::logical::{BoundMatchSource, LoweredMatchSpec};
use datafusion::common::{DFSchema, Result};
use datafusion::logical_expr::{Expr, Extension, LogicalPlan, SortExpr};
use crate::planning::MatchRecognizePlanningContext;
use crate::planning::measures;
use crate::planning::phases::{
AssembledNode, MatcherNodeSpec, MatcherOutputMode, NodeOutputSpec,
assemble_node_from_logical_parts, finalize_output_with_navigation_offsets,
materialize_partition_keys, prepare_input_from_logical_spec, process_defines,
};
use crate::planning::source::{BoundMatchSpec, MatchRecognizePlanningCapabilities};
struct AssembledSourceMatch {
node: AssembledNode,
rows_per_match: RowsPerMatch,
table_schema: Arc<DFSchema>,
source_partition_by: Vec<Expr>,
source_order_by: Vec<SortExpr>,
navigation_offsets: NavigationOffsets,
}
pub fn plan_match_recognize_from_source(
context: &mut dyn MatchRecognizePlanningContext,
input: LogicalPlan,
spec: BoundMatchSpec,
) -> Result<LogicalPlan> {
plan_match_recognize_from_source_with_capabilities(
context,
input,
spec,
MatchRecognizePlanningCapabilities::default(),
)
}
pub fn plan_match_recognize_from_source_with_capabilities(
context: &mut dyn MatchRecognizePlanningContext,
input: LogicalPlan,
spec: BoundMatchSpec,
capabilities: MatchRecognizePlanningCapabilities,
) -> Result<LogicalPlan> {
let assembled = assemble_match_recognize_from_source(
context,
input,
spec,
capabilities,
NativeOneRowPlanningPolicy::Opportunistic,
)?;
finalize_output_with_navigation_offsets(
assembled.node,
&assembled.rows_per_match,
&assembled.table_schema,
assembled.navigation_offsets,
&assembled.source_partition_by,
&assembled.source_order_by,
)
}
pub fn plan_match_recognize_node_from_source_with_capabilities(
context: &mut dyn MatchRecognizePlanningContext,
input: LogicalPlan,
spec: BoundMatchSpec,
capabilities: MatchRecognizePlanningCapabilities,
) -> Result<LogicalPlan> {
let assembled = assemble_match_recognize_from_source(
context,
input,
spec,
capabilities,
NativeOneRowPlanningPolicy::Disabled,
)?;
Ok(LogicalPlan::Extension(Extension {
node: Arc::new(assembled.node.matcher),
}))
}
#[cfg(feature = "substrait")]
pub(crate) fn plan_match_recognize_native_one_row_node_from_source_with_capabilities(
context: &mut dyn MatchRecognizePlanningContext,
input: LogicalPlan,
spec: BoundMatchSpec,
capabilities: MatchRecognizePlanningCapabilities,
) -> Result<LogicalPlan> {
let assembled = assemble_match_recognize_from_source(
context,
input,
spec,
capabilities,
NativeOneRowPlanningPolicy::Required,
)?;
Ok(LogicalPlan::Extension(Extension {
node: Arc::new(assembled.node.matcher),
}))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NativeOneRowPlanningPolicy {
Disabled,
Opportunistic,
Required,
}
impl NativeOneRowPlanningPolicy {
const fn allows_native(self) -> bool {
!matches!(self, Self::Disabled)
}
}
fn assemble_match_recognize_from_source(
context: &mut dyn MatchRecognizePlanningContext,
input: LogicalPlan,
spec: BoundMatchSpec,
capabilities: MatchRecognizePlanningCapabilities,
native_one_row_policy: NativeOneRowPlanningPolicy,
) -> Result<AssembledSourceMatch> {
let (bound_source, lowered) =
BoundMatchSource::try_new_and_lower(context, input, spec, capabilities)?;
let bound_source = Arc::new(bound_source);
let LoweredSourceMatch {
input,
mut spec,
navigation_offsets,
source_partition_by,
source_order_by,
mut volatile_key_exprs,
} = lowered;
let requirements = bound_source.requirements();
if matches!(
spec.output,
MatchRecognizeOutputContract::ExplicitNamedExpressions(_)
) {
return datafusion::common::plan_err!(
"MATCH_RECOGNIZE source lowering does not support explicit output contracts yet"
);
}
let table_schema = Arc::clone(bound_source.input().schema());
let (input, key_exprs) = materialize_partition_keys(input, &mut spec)?;
let pattern_info = spec.pattern.structural_info();
let table_rows_per_match = spec.source_rows_per_match.clone();
let partition_by = spec.partition_by.clone();
let order_by = spec_order_by_to_sort_exprs(&spec);
let after_match_skip = spec.after_match_skip.clone();
let mut measures_exprs = std::mem::take(&mut spec.measures)
.into_iter()
.map(|measure| NamedExpr {
name: measure.name.expect("validated source measure has a name"),
expr: measure.expression,
})
.collect::<Vec<_>>();
let native_summaries = if native_one_row_policy.allows_native()
&& matches!(table_rows_per_match, RowsPerMatch::OneRow)
{
let summary_input_spec =
MatchRecognizeOutputSpec::with_validated_navigation_offsets(
(0..input.schema().fields().len()).collect(),
MatchMetadataColumn::public_output().to_vec(),
spec.symbols.clone(),
navigation_offsets,
);
let summary_input_schema = summary_input_spec.build_df_schema(input.schema())?;
let define_windows = datafusion::logical_expr::utils::find_window_exprs(
spec.definitions
.iter()
.map(|definition| &definition.predicate),
);
measures::simplify_one_row_measures(
&mut measures_exprs,
&partition_by,
&define_windows,
&input,
summary_input_schema.as_ref(),
pattern_info.min_match_rows() > 0,
)?;
measures::plan_selected_match_summaries(
&measures_exprs,
summary_input_schema.as_ref(),
&measures::one_row_group_exprs(&partition_by),
native_one_row_policy != NativeOneRowPlanningPolicy::Required,
)
} else {
None
};
if matches!(native_one_row_policy, NativeOneRowPlanningPolicy::Required)
&& native_summaries.is_none()
{
return datafusion::common::plan_err!(
"MATCH_RECOGNIZE semantic node requires native ONE ROW finalization, but its complete measure program is not eligible"
);
}
let mut prepared = prepare_input_from_logical_spec(
context,
input,
&spec,
&order_by,
requirements,
!volatile_key_exprs.is_empty(),
)?;
prepared.prepared_exprs.append(&mut volatile_key_exprs);
prepared.prepared_exprs.extend(key_exprs);
let matcher_output = match native_summaries {
Some(plan) => {
measures_exprs = plan.measures_exprs;
MatcherOutputMode::SelectedSummaries(plan.summaries)
}
None => MatcherOutputMode::Rows(prepared.matcher_rows_per_match.clone()),
};
let processed = process_defines(context, prepared)?;
let assembled = assemble_node_from_logical_parts(
processed,
MatcherNodeSpec {
partition_by,
order_by,
after_match_skip,
pattern: spec.pattern,
output: matcher_output,
navigation_offsets,
bound_source,
},
NodeOutputSpec {
measures_exprs,
has_exclusions: pattern_info.has_exclusions(),
},
)?;
Ok(AssembledSourceMatch {
node: assembled,
rows_per_match: table_rows_per_match,
table_schema,
source_partition_by,
source_order_by,
navigation_offsets,
})
}
fn spec_order_by_to_sort_exprs(spec: &LoweredMatchSpec) -> Vec<SortExpr> {
spec.order_by
.iter()
.map(|sort| {
let asc = matches!(sort.direction, MatchRecognizeSortDirection::Asc);
let nulls_first = matches!(
sort.null_ordering,
crate::core::MatchRecognizeNullOrdering::First
);
SortExpr::new(sort.expr.clone(), asc, nulls_first)
})
.collect()
}