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.

//! DataFusion optimizer rules installed by the public crate.

use std::sync::Arc;

use crate::config::MatchRecognizeConfig;
use crate::execution::physical::try_absorb_synthetic_row_filter;
use datafusion::common::Result;
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
use datafusion::physical_optimizer::optimizer::ConfigOnlyContext;
use datafusion::physical_optimizer::sanity_checker::input_requirements_hold;
use datafusion::physical_optimizer::{PhysicalOptimizerContext, PhysicalOptimizerRule};
use datafusion::physical_plan::execution_plan::InvariantLevel;
use datafusion::physical_plan::{
    ExecutionPlan, ExecutionPlanProperties, filter::FilterExec,
};

mod grouped_order;
mod input_constants;
mod merge_buffer;
mod projection_pushdown;
mod repair_requirements;

pub(super) use projection_pushdown::MatchRecognizeProjectionPushdown;

#[derive(Debug, Default)]
pub(super) struct MatchRecognizePhysicalOptimizer;

impl PhysicalOptimizerRule for MatchRecognizePhysicalOptimizer {
    fn optimize(
        &self,
        plan: Arc<dyn ExecutionPlan>,
        config: &ConfigOptions,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        self.optimize_with_context(plan, &ConfigOnlyContext::new(config))
    }

    fn optimize_with_context(
        &self,
        plan: Arc<dyn ExecutionPlan>,
        context: &dyn PhysicalOptimizerContext,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        let config = context.config_options();
        // Work around upstream DataFusion 56.0.0 (#27318) before our passes
        // run, so any regression from our own rewrites is still caught by
        // SanityCheckPlan.
        let plan = repair_requirements::optimize(plan, context)?;
        let plan = grouped_order::collapse_roundrobin_window_roundtrip(plan)?;
        // Tightening WITH UNMATCHED can make whole-partition pruning legal.
        let plan = if config
            .extensions
            .get::<MatchRecognizeConfig>()
            .is_some_and(|mr| mr.diagnostics.disable_pattern_optimizer)
        {
            plan
        } else {
            plan.transform_up(|plan| {
                if let Some(filter) = plan.downcast_ref::<FilterExec>()
                    && let Some(rewritten) = try_absorb_synthetic_row_filter(filter)?
                {
                    return Ok(Transformed::yes(rewritten));
                }
                Ok(Transformed::no(plan))
            })?
            .data
        };
        let plan = grouped_order::optimize(plan, config)?;
        let plan = input_constants::optimize(plan, config)?;
        merge_buffer::optimize(plan)
    }

    fn name(&self) -> &str {
        "match_recognize_physical"
    }

    fn schema_check(&self) -> bool {
        true
    }
}

// Preserve root ordering, descendant requirements, and cross-child executable
// invariants (for example, compatible sibling partition counts in joins).
fn rewrite_is_valid(
    original: &Arc<dyn ExecutionPlan>,
    rewritten: &Arc<dyn ExecutionPlan>,
) -> bool {
    let root_order_preserved = original.output_ordering().is_none_or(|ordering| {
        rewritten
            .equivalence_properties()
            .ordering_satisfy(ordering.clone())
            .unwrap_or(false)
    });
    root_order_preserved
        && input_requirements_hold(rewritten)
        && rewritten
            .apply(|node| {
                node.check_invariants(InvariantLevel::Executable)?;
                Ok(TreeNodeRecursion::Continue)
            })
            .is_ok()
}