datafusion-match-recognize 0.55.0

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.

//! Imports and exports `MATCH_RECOGNIZE` through this package's Substrait
//! extension.
//!
//! The wire form is an `ExtensionSingleRel` whose detail contains this crate's
//! versioned Protobuf message. It is not a portable standard Substrait relation:
//! another producer or consumer must explicitly support [`MATCH_RECOGNIZE_TYPE_URL`],
//! [`MATCH_RECOGNIZE_SCHEMA_VERSION`], and every declared required feature.
//!
//! # Complete plans
//!
//! Most callers use [`to_substrait_plan_with_match_recognize`] and
//! [`from_substrait_plan_with_match_recognize`]. These helpers handle complete
//! DataFusion logical plans, delegate ordinary relations to DataFusion's
//! Substrait traversal, and add this package's matcher relation handling.
//!
//! # Custom traversal
//!
//! Advanced integrations can compose [`MatchRecognizeSubstraitProducer`] or
//! [`MatchRecognizeSubstraitConsumer`] with DataFusion's traversal APIs. The
//! lower-level [`encode_match_recognize_detail`] and
//! [`decode_match_recognize_detail`] functions handle one extension detail
//! message when the surrounding relation is already managed by the caller.
//! Export the relation returned by [`export_input`] alongside encoded detail;
//! it preserves supported changes to the node's current input.
//!
//! Import rejects unknown schema versions and required features instead of
//! silently dropping or changing match semantics.

mod consumer;
mod decode;
mod export;
mod payload;
mod producer;
mod quantifier;
mod schema;
mod window;
mod wire;

use std::collections::BTreeSet;
use std::sync::{Arc, RwLock};

use crate::core::{
    AfterMatchSkip, EmptyMatchesMode, MatchRecognizeDefinition, MatchRecognizeMeasure,
    MatchRecognizeNamedExpression, MatchRecognizeNullOrdering,
    MatchRecognizeOutputContract, MatchRecognizeSortDirection, MatchRecognizeSortExpr,
    MatchRecognizeSpec, Pattern, RowsPerMatch, Symbol,
};
use crate::planning::logical::MatchRecognize;
use crate::planning::{
    BUILTIN_SUBSTRING_NAME, BoundMatchAggregateCall, BoundMatchExpr, BoundMatchExprSort,
    BoundMatchNavigation, BoundMatchSpec, MatchAggregateCall, MatchExprSort,
    MatchMetadataFunction, MatchNavigation, MatchPatternFieldRef, MatchPredicateKind,
    MatchRecognizePlanningCapabilities, MatchRecognizePlanningContext,
    MatchUnaryOperator, analyze_match_recognize_requirements,
    plan_match_recognize_from_source_with_capabilities,
    plan_match_recognize_native_one_row_node_from_source_with_capabilities,
    plan_match_recognize_node_from_source_with_capabilities,
};
use async_trait::async_trait;
use datafusion::arrow::datatypes::{DataType, Field, IntervalUnit, TimeUnit};
use datafusion::catalog::TableProvider;
use datafusion::common::{
    Column, DFSchema, DFSchemaRef, Result, TableReference, not_impl_err, plan_err,
    substrait_err,
};
use datafusion::execution::registry::SerializerRegistry;
use datafusion::execution::{FunctionRegistry, SessionState};
use datafusion::logical_expr::expr;
use datafusion::logical_expr::{
    AggregateUDF, Expr, Extension, LogicalPlan, Operator, ScalarUDF,
};
use datafusion_substrait::extensions::Extensions;
use datafusion_substrait::logical_plan::consumer::{
    SubstraitConsumer, from_substrait_named_struct, from_substrait_plan_with_consumer,
    from_substrait_type,
};
use datafusion_substrait::logical_plan::producer::{SubstraitProducer, to_substrait_rel};
use datafusion_substrait::substrait::proto;
use datafusion_substrait::substrait::proto::rel::RelType;
use datafusion_substrait::substrait::proto::rel_common::EmitKind;
use datafusion_substrait::substrait::proto::{
    ExtensionLeafRel, ExtensionMultiRel, plan_rel,
};
use datafusion_substrait::substrait::proto::{
    ExtensionSingleRel, NamedStruct, Plan, PlanRel, Rel, RelRoot,
};
use datafusion_substrait::substrait::version;
use datafusion_substrait::variation_const::{
    DATE_32_TYPE_VARIATION_REF, DATE_64_TYPE_VARIATION_REF,
    DECIMAL_128_TYPE_VARIATION_REF, DECIMAL_256_TYPE_VARIATION_REF,
    DEFAULT_CONTAINER_TYPE_VARIATION_REF, DEFAULT_INTERVAL_DAY_TYPE_VARIATION_REF,
    DEFAULT_MAP_TYPE_VARIATION_REF, DEFAULT_TYPE_VARIATION_REF,
    DICTIONARY_MAP_TYPE_VARIATION_REF, DURATION_INTERVAL_DAY_TYPE_VARIATION_REF,
    FLOAT_16_TYPE_NAME, LARGE_CONTAINER_TYPE_VARIATION_REF, NULL_TYPE_NAME,
    TIME_32_TYPE_VARIATION_REF, TIME_64_TYPE_VARIATION_REF,
    UNSIGNED_INTEGER_TYPE_VARIATION_REF, VIEW_CONTAINER_TYPE_VARIATION_REF,
};
use pbjson_types::Any;
use prost::Message;

/// Protobuf `Any` type URL for this package's extension relation.
///
/// The namespace is a stable wire compatibility label, not a statement of
/// project affiliation.
pub const MATCH_RECOGNIZE_TYPE_URL: &str = "type.googleapis.com/io.github.datafusion_contrib.match_recognize.v0.MatchRecognizeRel";
/// Required-feature marker for the version-zero extension relation.
pub const MATCH_RECOGNIZE_EXTENSION_FEATURE: &str = "match_recognize.extension_v0";
/// Required-feature marker for source ordinals and checked positional output
/// identity at both row-stream and selected-summary semantic boundaries.
pub const MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE: &str =
    "match_recognize.positional_field_refs_v2";
/// Required-feature marker for residual match-aware DEFINE semantics.
///
/// Executable import checks the normalized DEFINE requirements independently
/// of the wire declaration.
pub const MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE: &str =
    "match_recognize.match_aware_defines_v1";
/// Required-feature marker for reluctant row-pattern quantifiers.
pub const MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE: &str =
    "match_recognize.reluctant_quantifiers_v1";
/// Required-feature marker for logical navigation offsets in `FIRST`/`LAST`.
pub const MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE: &str =
    "match_recognize.logical_navigation_offset_v1";
/// Required-feature marker for compound navigation (`PREV`/`NEXT` wrapping `FIRST`/`LAST`).
pub const MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE: &str =
    "match_recognize.compound_navigation_v1";
/// Required-feature marker for `IS [NOT] DISTINCT FROM` in source expressions.
pub const MATCH_RECOGNIZE_DISTINCT_FROM_FEATURE: &str =
    "match_recognize.distinct_from_v1";
/// Required-feature marker for `MATCH_SEQUENCE_NUMBER` source expressions.
pub const DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE: &str =
    "match_recognize.datafusion_match_sequence_number";
/// Required-feature marker for `EXCLUDED` source expressions.
pub const DATAFUSION_EXCLUDED_FEATURE: &str = "match_recognize.datafusion_excluded";
/// Required-feature marker for exact window `FILTER` and null treatment.
pub const DATAFUSION_WINDOW_MODIFIERS_FEATURE: &str =
    "match_recognize.datafusion_window_modifiers_v1";
/// Typed selected-match summary finalization contract emitted by this package.
pub const DATAFUSION_SEMANTIC_ONE_ROW_FEATURE: &str =
    "match_recognize.datafusion_semantic_one_row_v2";

/// Schema version encoded in the version-zero extension payload.
pub const MATCH_RECOGNIZE_SCHEMA_VERSION: u32 = 0;

fn has_reluctant_quantifier(pattern: &Pattern) -> bool {
    match pattern {
        Pattern::Repetition(inner, quantifier) => {
            quantifier.is_reluctant() || has_reluctant_quantifier(inner)
        }
        Pattern::Group(inner) => has_reluctant_quantifier(inner),
        Pattern::Concat(patterns) | Pattern::Alternation(patterns) => {
            patterns.iter().any(has_reluctant_quantifier)
        }
        Pattern::Symbol(_) | Pattern::Exclude(_) | Pattern::Permute(_) => false,
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct SpecExprFeatures {
    has_logical_offset: bool,
    has_compound_navigation: bool,
    has_distinct_from: bool,
}

fn spec_expr_features(spec: &BoundMatchSpec) -> Result<SpecExprFeatures> {
    let mut features = SpecExprFeatures::default();
    let mut stack: Vec<&BoundMatchExpr> = Vec::new();
    stack.extend(spec.partition_by.iter());
    stack.extend(spec.order_by.iter().map(|sort| &sort.expr));
    stack.extend(spec.definitions.iter().map(|def| &def.predicate));
    stack.extend(spec.measures.iter().map(|measure| &measure.expression));
    if let MatchRecognizeOutputContract::ExplicitNamedExpressions(outputs) = &spec.output
    {
        stack.extend(outputs.iter().map(|output| &output.expression));
    }
    while let Some(expr) = stack.pop() {
        match expr {
            BoundMatchExpr::Navigation(nav) => match nav {
                MatchNavigation::First { offset, .. }
                | MatchNavigation::Last { offset, .. } => {
                    if offset.is_some() {
                        features.has_logical_offset = true;
                    }
                }
                MatchNavigation::Prev { expr: inner, .. }
                | MatchNavigation::Next { expr: inner, .. } => {
                    if matches!(
                        inner.as_ref(),
                        BoundMatchExpr::Navigation(
                            MatchNavigation::First { .. } | MatchNavigation::Last { .. }
                        )
                    ) {
                        features.has_compound_navigation = true;
                    }
                }
            },
            BoundMatchExpr::Binary {
                op: Operator::IsDistinctFrom | Operator::IsNotDistinctFrom,
                ..
            } => {
                features.has_distinct_from = true;
            }
            _ => {}
        }
        if features.has_logical_offset
            && features.has_compound_navigation
            && features.has_distinct_from
        {
            break;
        }
        expr.try_for_each_child(|child| {
            stack.push(child);
            Ok(())
        })?;
    }
    Ok(features)
}

pub use consumer::{
    DecodedMatchRecognizeDetail, DecodedSummaryAggregate, MatchRecognizeBoundary,
    MatchRecognizeSubstraitConsumer, decode_match_recognize_detail,
    from_substrait_plan_with_match_recognize,
};
pub use export::export_input;
pub use producer::{
    MatchRecognizeSubstraitProducer, encode_match_recognize_detail,
    to_substrait_plan_with_match_recognize,
};

#[cfg(all(test, feature = "sql"))]
use schema::{
    decode_data_type, substrait_type_is_nullable, to_substrait_named_struct,
    to_substrait_type,
};

#[cfg(all(test, feature = "sql"))]
mod plan_case_tests;
#[cfg(test)]
mod schema_conformance;
#[cfg(all(test, feature = "sql"))]
mod tests;