datafusion-match-recognize 0.56.1

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
// Licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

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,
}

/// Turn a bound `MATCH_RECOGNIZE` request into a complete logical plan.
///
/// This uses the default source capabilities. It canonicalizes and validates
/// the request against `input`, lowers its expressions, builds the semantic
/// [`crate::planning::MatchRecognize`] node, and adds the final projection or
/// aggregation required by the requested output mode.
///
/// # Example
///
/// This one-symbol request accepts each input row because an omitted `DEFINE`
/// condition defaults to true.
///
/// ```rust
/// use datafusion::logical_expr::{LogicalPlan, LogicalPlanBuilder, lit};
/// use datafusion_match_recognize::planning::{
///     AfterMatchSkip, BoundMatchSpec, DefaultMatchRecognizePlanningContext,
///     EmptyMatchesMode, MatchRecognizeOutputContract, Pattern, RowsPerMatch, Symbol,
///     plan_match_recognize_from_source,
/// };
///
/// # fn build() -> datafusion::error::Result<LogicalPlan> {
/// let input = LogicalPlanBuilder::values(vec![vec![lit(1_i64)]])?.build()?;
/// let spec = BoundMatchSpec {
///     partition_by: vec![],
///     order_by: vec![],
///     source_rows_per_match: RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
///     after_match_skip: AfterMatchSkip::PastLastRow,
///     pattern: Pattern::Symbol(Symbol::Named("A".to_string())),
///     symbols: vec!["A".to_string()],
///     definitions: vec![],
///     measures: vec![],
///     output: MatchRecognizeOutputContract::Derived,
/// };
/// let mut context = DefaultMatchRecognizePlanningContext::new();
/// plan_match_recognize_from_source(&mut context, input, spec)
/// # }
/// # build()?;
/// # Ok::<(), datafusion::error::DataFusionError>(())
/// ```
///
/// # Errors
///
/// Returns an error when the request is inconsistent with `input`, contains an
/// invalid or unsupported clause, cannot be lowered with `context`, or cannot
/// produce a valid output plan.
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(),
    )
}

/// Turn a bound request into a complete logical plan while enforcing source
/// capabilities.
///
/// In addition to the semantic node and its prepared input, the returned plan
/// contains the projection or aggregation that produces the requested table
/// output.
///
/// # Errors
///
/// Returns an error when the request is inconsistent with `input`, uses a
/// feature disabled by `capabilities`, contains an invalid or unsupported
/// clause, cannot be lowered with `context`, or cannot produce a valid output
/// plan.
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,
    )
}

/// Build the `MatchRecognize` node and its prepared input without final output
/// projection or aggregation.
///
/// A Substrait consumer uses this form when surrounding standard relations
/// already perform those final output steps. The returned plan is therefore not
/// a replacement for the complete-plan helpers when the caller expects the
/// source request's final table schema.
///
/// # Errors
///
/// Returns an error when the request is inconsistent with `input`, uses a
/// feature disabled by `capabilities`, contains an invalid or unsupported
/// clause, or cannot be lowered with `context`.
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),
    }))
}

/// Build a semantic node that must perform native ONE ROW finalization.
///
/// This is used when an interchange payload records that surrounding standard
/// relations were planned against the native one-row node boundary. Planning
/// fails instead of silently rebuilding the row-stream boundary when the
/// complete measure program is no longer eligible.
///
/// # Errors
///
/// Returns the same planning errors as
/// [`plan_match_recognize_node_from_source_with_capabilities`], and returns an
/// error when the complete measure program cannot be finalized inside the
/// semantic node.
#[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"
        );
    }
    // The public projection uses the source schema and expressions.
    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"
        );
    }
    // Materializing validated row-level partition keys preserves DEFINE dependencies.
    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()
}