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.

//! Bind physical offsets only when the matcher and the SQL windows see the same ordered partitions.

mod binding;
mod projection;
#[cfg(test)]
mod tests;
mod windows;

pub(super) use binding::bind_rule_excluding;
#[cfg(test)]
use binding::{bind_atom, bind_coalesce_comparison, bind_rule, coalesce_column_literal};
pub(super) use projection::flatten_projections;
#[cfg(test)]
use windows::literal_default_shift;
pub(super) use windows::{ShiftMap, checked_windows_on};

use crate::execution::classification::{OffsetExpression, StaticRule};
use binding::bind_neighbor;
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::common::DFSchema;
use datafusion::common::plan_err;
use datafusion::common::tree_node::{Transformed, TreeNode};
use datafusion::logical_expr::{Expr, Operator, binary_expr, col, lit};
use datafusion::physical_expr::expressions::{
    BinaryExpr, CastExpr, Column, IsNotNullExpr, IsNullExpr, Literal, NotExpr,
};
use datafusion::physical_expr::projection::ProjectionExpr;
use datafusion::physical_expr_common::physical_expr::is_volatile;
use datafusion::physical_plan::PhysicalExpr;
use std::sync::Arc;

pub(super) fn expression_rule(
    expr: &Arc<dyn PhysicalExpr>,
    shifts: &ShiftMap,
    width: usize,
    raw: &mut Vec<ProjectionExpr>,
    original: &Schema,
    allow_fallible: bool,
) -> Option<StaticRule> {
    if is_volatile(expr) {
        return None;
    }

    // Rebind the actual physical projection, including its coercions. Programmatic
    // callers can supply arbitrary private fields, so a symbol's diagnostic
    // expression alone cannot prove this projection safe to move past the sort.
    fn logical(expr: &Arc<dyn PhysicalExpr>) -> Option<Expr> {
        if let Some(c) = expr.downcast_ref::<Column>() {
            return Some(col(c.name()));
        }
        if let Some(l) = expr.downcast_ref::<Literal>() {
            return Some(lit(l.value().clone()));
        }
        if let Some(b) = expr.downcast_ref::<BinaryExpr>() {
            // Other binary kernels (for example regex) can allocate scratch
            // proportional to a variable-width operand. Keep them on demand.
            if !matches!(
                b.op(),
                Operator::And
                    | Operator::Or
                    | Operator::Eq
                    | Operator::NotEq
                    | Operator::Lt
                    | Operator::LtEq
                    | Operator::Gt
                    | Operator::GtEq
                    | Operator::IsDistinctFrom
                    | Operator::IsNotDistinctFrom
                    | Operator::Plus
                    | Operator::Minus
                    | Operator::Multiply
                    | Operator::Divide
                    | Operator::Modulo
            ) {
                return None;
            }
            return Some(binary_expr(
                logical(b.left())?,
                *b.op(),
                logical(b.right())?,
            ));
        }
        if let Some(c) = expr.downcast_ref::<CastExpr>() {
            return Some(datafusion::logical_expr::expr_fn::cast(
                logical(c.expr())?,
                c.cast_type().clone(),
            ));
        }
        if let Some(n) = expr.downcast_ref::<NotExpr>() {
            return Some(Expr::Not(Box::new(logical(n.arg())?)));
        }
        if let Some(n) = expr.downcast_ref::<IsNullExpr>() {
            return Some(logical(n.arg())?.is_null());
        }
        if let Some(n) = expr.downcast_ref::<IsNotNullExpr>() {
            return Some(logical(n.arg())?.is_not_null());
        }
        None
    }

    let mut expr_raw = raw.clone();
    let mut leaves = Vec::new();
    let mut fields = Vec::new();
    let predicate = Arc::clone(expr)
        .transform_up(|node| {
            let Some(column) = node.downcast_ref::<Column>() else {
                return Ok(Transformed::no(node));
            };
            let source = shifts.get(&column.index()).map_or(column, |(src, ..)| src);
            let field = original.fields().get(column.index()).ok_or_else(|| {
                datafusion::common::plan_datafusion_err!("offset column unavailable")
            })?;
            let source_field =
                original.fields().get(source.index()).ok_or_else(|| {
                    datafusion::common::plan_datafusion_err!("offset source unavailable")
                })?;
            if source_field.data_type() != field.data_type() {
                return plan_err!("offset source type mismatch");
            }
            let leaf =
                bind_neighbor(column, shifts, width, &mut expr_raw).ok_or_else(|| {
                    datafusion::common::plan_datafusion_err!("offset source unavailable")
                })?;
            let i = leaves.iter().position(|n| *n == leaf).unwrap_or_else(|| {
                let i = leaves.len();
                fields.push(Field::new(
                    format!("v{i}"),
                    source_field.data_type().clone(),
                    leaf.shift != 0 || source_field.is_nullable(),
                ));
                leaves.push(leaf);
                i
            });
            Ok(Transformed::yes(
                Arc::new(Column::new(fields[i].name(), i)) as Arc<dyn PhysicalExpr>
            ))
        })
        .ok()?
        .data;
    let schema = Arc::new(Schema::new(fields));
    let rule = {
        if leaves.is_empty()
            || predicate.data_type(&schema).ok() != Some(DataType::Boolean)
        {
            return None;
        }
        let logical_schema = DFSchema::try_from(Arc::clone(&schema)).ok()?;
        let logical = logical(&predicate)?;
        if !allow_fallible
            && !crate::planning::can_reorder_input_scalar(&logical, &logical_schema)
        {
            return None;
        }
        StaticRule::Expr(OffsetExpression::try_new(predicate, leaves, schema)?)
    };
    *raw = expr_raw;
    Some(rule)
}