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.

//! SQL-independent semantic planning for `MATCH_RECOGNIZE`.
//!
//! Source adapters supply a [`BoundMatchSpec`] with bound input expressions,
//! column references, and Arrow types. Structured scalar and aggregate calls
//! retain their identities; lowering resolves registry calls through
//! [`MatchRecognizePlanningContext`]. Planning validates and canonicalizes the
//! request, then builds the semantic logical node and final output. It retains
//! the canonical source so exporters can reproduce the request. Static DEFINEs
//! can become checked Boolean input columns. Planning also prepares candidate
//! predicates, aggregate state, and Deferred history inputs from the bound source.

pub use crate::core::{
    AfterMatchSkip, EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeDefinition,
    MatchRecognizeMeasure, MatchRecognizeNamedExpression, MatchRecognizeNullOrdering,
    MatchRecognizeOutputContract, MatchRecognizeSortDirection, MatchRecognizeSortExpr,
    MatchRecognizeSpec, MatchRecognizeSpecError, MatchRecognizeSpecResult,
    NormalizedPattern, Pattern, PatternStructuralInfo, RepetitionPreference,
    RepetitionQuantifier, RowsPerMatch, Symbol,
};
use datafusion::common::config::ConfigOptions;
use datafusion::logical_expr::{AggregateUDF, ScalarUDF};
pub(crate) use deferred_program::{
    DeferredHistorySlotOwner, DeferredOperationSpec, DeferredProgramSpec,
};
#[cfg(feature = "substrait")]
pub(crate) use define::preparation::static_define_predicate_expr;
pub use define::{
    DefineRequirement, MatchRecognizeRequirements, analyze_match_recognize_requirements,
};
pub(crate) use expressions::NamedExpr;
pub(crate) use extract::{
    ManagedAggregate, ManagedAggregateBackend, ManagedAggregateBackendSet,
};
pub(crate) use hybrid_guard::LogicalHybridGuardExpr;
#[cfg(test)]
pub(crate) use logical::ExecutableMatchProgramInput;
pub use logical::MatchRecognize;
pub(crate) use physical_derivation::compile_match_program;
pub(crate) use routed_program::{
    AccumulatorInputMode, MatchCompilerOptions, RoutedAggregate, RoutedEvaluator,
    RoutedHistoryGuard, RoutedMatchProgram, RoutedPredicate, RoutedSymbol,
};
#[allow(deprecated)]
pub use source::validate_pattern_qualifiers;
pub use source::{
    BoundMatchAggregateCall, BoundMatchExpr, BoundMatchExprSort, BoundMatchNavigation,
    BoundMatchSpec, CanonicalBoundMatchSpec, MatchAggregateCall, MatchExpr,
    MatchExprSort, MatchMetadataFunction, MatchNavigation, MatchPatternFieldRef,
    MatchPredicateKind, MatchRecognizePlanningCapabilities, MatchUnaryOperator,
};
#[cfg(feature = "substrait")]
pub(crate) use source_lowering::plan_match_recognize_native_one_row_node_from_source_with_capabilities;
pub use source_lowering::{
    plan_match_recognize_from_source, plan_match_recognize_from_source_with_capabilities,
    plan_match_recognize_node_from_source_with_capabilities,
};
use std::sync::Arc;
pub(crate) use symbol_relationships::SymbolRelationships;
pub(crate) use type_validation::can_have_nulls_outside_bitmap;
pub(crate) use vm_assembly::VmAssemblyDowngrade;

/// Semantic logical-plan nodes and programs shared with physical planning and
/// source exporters.
pub(crate) mod logical;
pub(crate) mod predicate;

mod bound_expr_lowering;
mod deferred_program;
mod define;
mod expr_safety;
mod expressions;
pub(crate) mod extract;
mod hybrid_guard;
mod measures;
mod navigation_names;
mod phases;
pub(crate) mod physical_derivation;
pub(crate) mod routed_program;
mod semantic_metadata;
mod source;
mod source_lowering;
mod static_extraction;
pub(crate) mod symbol_relationships;
mod type_validation;
mod vm_assembly;

/// Whether a row-local input expression can move across an ordered matcher boundary
/// without changing errors or the number of volatile calls.
pub(crate) fn can_reorder_input_scalar(
    expr: &datafusion::logical_expr::Expr,
    schema: &datafusion::common::DFSchema,
) -> bool {
    expr_safety::can_discard_scalar(expr, Some(schema))
}

/// Internal source and wire identity for the SQL SUBSTRING operator.
pub(crate) const BUILTIN_SUBSTRING_NAME: &str = "__mr_builtin_substr";

/// Planning-only switches read from the registered session extension.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MatchRecognizePlanningOptions {
    /// Route match-aware aggregates away from local managed state.
    pub disable_managed_aggregates: bool,
    /// Keep complete `DEFINE` expressions instead of extracting static columns.
    pub disable_static_extraction: bool,
}

impl MatchRecognizePlanningOptions {
    pub(crate) fn from_config_options(options: &ConfigOptions) -> Self {
        let Some(config) = options
            .extensions
            .get::<crate::config::MatchRecognizeConfig>()
        else {
            return Self::default();
        };
        Self {
            disable_managed_aggregates: config.diagnostics.disable_managed_aggregates,
            disable_static_extraction: config.diagnostics.disable_static_extraction,
        }
    }
}

/// Planning context used by SQL-free source lowering.
///
/// Source lowering needs DataFusion configuration and function resolution, but
/// not SQL parser or planner state. Keeping this local trait avoids depending on
/// DataFusion's SQL-only `RelationPlannerContext`.
pub trait MatchRecognizePlanningContext {
    /// Return the DataFusion options used while binding and lowering the source.
    fn options(&self) -> &ConfigOptions;

    /// Read this package's planning switches from [`Self::options`].
    fn match_recognize_options(&self) -> MatchRecognizePlanningOptions {
        MatchRecognizePlanningOptions::from_config_options(self.options())
    }

    /// Resolve a scalar function by name.
    ///
    /// The default context exposes no named scalar functions. Importers may
    /// still supply already-resolved DataFusion expressions through
    /// [`crate::planning::MatchExpr::InputExpr`].
    fn scalar_udf(&self, _name: &str) -> Option<Arc<ScalarUDF>> {
        None
    }

    /// Resolve an aggregate function by name.
    ///
    /// The default implementation recognizes DataFusion built-in aggregates.
    fn aggregate_udf(&self, name: &str) -> Option<Arc<AggregateUDF>> {
        bound_expr_lowering::builtin_aggregate_udf(name)
    }
}

/// Planning context backed by owned DataFusion configuration and the package's
/// built-in aggregate resolver.
#[derive(Debug, Clone, Default)]
pub struct DefaultMatchRecognizePlanningContext {
    options: ConfigOptions,
}

impl DefaultMatchRecognizePlanningContext {
    /// Create a context with default DataFusion options.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a context with the supplied DataFusion options.
    pub fn with_options(options: ConfigOptions) -> Self {
        Self { options }
    }
}

impl MatchRecognizePlanningContext for DefaultMatchRecognizePlanningContext {
    fn options(&self) -> &ConfigOptions {
        &self.options
    }
}

impl MatchRecognizePlanningContext for ConfigOptions {
    fn options(&self) -> &ConfigOptions {
        self
    }
}

#[cfg(test)]
mod options_tests {
    use super::*;
    #[test]
    fn reads_planning_overrides_from_registered_options() {
        let mut options = ConfigOptions::default();
        assert_eq!(
            MatchRecognizePlanningOptions::from_config_options(&options),
            MatchRecognizePlanningOptions::default()
        );
        options
            .extensions
            .insert(crate::config::MatchRecognizeConfig::default());

        assert_eq!(
            MatchRecognizePlanningOptions::from_config_options(&options),
            MatchRecognizePlanningOptions::default()
        );
        options
            .set(
                "match_recognize.diagnostics.disable_managed_aggregates",
                "true",
            )
            .unwrap();
        options
            .set(
                "match_recognize.diagnostics.disable_static_extraction",
                "true",
            )
            .unwrap();

        assert_eq!(
            MatchRecognizePlanningOptions::from_config_options(&options),
            MatchRecognizePlanningOptions {
                disable_managed_aggregates: true,
                disable_static_extraction: true,
            }
        );
    }
}