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 crate::core::classifier_bits_col_name;
use datafusion::arrow::datatypes::{DataType, FieldRef};
use datafusion::common::Result;
use datafusion::logical_expr::expr::{
    WindowFunction, WindowFunctionDefinition, WindowFunctionParams,
};
use datafusion::logical_expr::{
    Accumulator, AggregateUDF, AggregateUDFImpl, Expr, Signature, Volatility, col,
};
use std::sync::LazyLock;

use crate::planning::logical::{sequence_sort_expr, utils::causal_window_frame};

/// Test-only UDAF with a built-in aggregate's name but a distinct identity.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct SameNameCustomAggregate {
    pub(crate) name: &'static str,
}

impl AggregateUDFImpl for SameNameCustomAggregate {
    fn name(&self) -> &str {
        self.name
    }

    fn signature(&self) -> &Signature {
        static SIGNATURE: LazyLock<Signature> =
            LazyLock::new(|| Signature::any(1, Volatility::Immutable));
        &SIGNATURE
    }

    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
        Ok(DataType::Int64)
    }

    fn return_field(&self, args: &[FieldRef]) -> Result<FieldRef> {
        if self.name == "count" {
            datafusion::functions_aggregate::count::count_udaf().return_field(args)
        } else {
            datafusion::logical_expr::udaf_default_return_field(self, args)
        }
    }

    fn accumulator(
        &self,
        acc_args: datafusion::logical_expr::function::AccumulatorArgs,
    ) -> Result<Box<dyn Accumulator>> {
        datafusion::functions_aggregate::count::count_udaf().accumulator(acc_args)
    }

    fn state_fields(
        &self,
        args: datafusion::logical_expr::function::StateFieldsArgs,
    ) -> Result<Vec<FieldRef>> {
        datafusion::functions_aggregate::count::count_udaf().state_fields(args)
    }
}

pub(crate) fn classifier_window(aggregate: Expr, symbol: &str) -> Expr {
    let Expr::AggregateFunction(aggregate) = aggregate else {
        panic!("expected aggregate expression");
    };

    Expr::WindowFunction(Box::new(WindowFunction {
        fun: WindowFunctionDefinition::AggregateUDF(aggregate.func),
        params: WindowFunctionParams {
            args: aggregate.params.args,
            partition_by: vec![col("__mr_match_number")],
            order_by: vec![sequence_sort_expr()],
            window_frame: causal_window_frame(),
            filter: Some(Box::new(col(classifier_bits_col_name(symbol)))),
            null_treatment: None,
            distinct: false,
        },
    }))
}

pub(crate) fn with_same_name_custom_aggregate(
    mut expr: Expr,
    name: &'static str,
) -> Expr {
    let custom =
        std::sync::Arc::new(AggregateUDF::new_from_impl(SameNameCustomAggregate {
            name,
        }));
    match &mut expr {
        Expr::AggregateFunction(aggregate) => aggregate.func = custom,
        Expr::WindowFunction(window) => {
            window.fun = WindowFunctionDefinition::AggregateUDF(custom)
        }
        _ => panic!("expected aggregate or aggregate window"),
    }
    expr
}

/// Materialize explicit Boolean fields for low-level logical-node test_cases.
pub(crate) fn prepare_symbol_fields(
    input: datafusion::logical_expr::LogicalPlan,
    names: impl IntoIterator<Item = String>,
) -> Result<datafusion::logical_expr::LogicalPlan> {
    use crate::core::symbol_col_name;
    use datafusion::common::Column;
    use datafusion::logical_expr::{LogicalPlanBuilder, lit};
    let mut exprs = input
        .schema()
        .fields()
        .iter()
        .enumerate()
        .map(|(index, field)| {
            Expr::Column(Column::new(
                input.schema().qualified_field(index).0.cloned(),
                field.name(),
            ))
        })
        .collect::<Vec<_>>();
    let mut changed = false;
    for name in names {
        let name = symbol_col_name(&name);
        if !input
            .schema()
            .fields()
            .iter()
            .any(|field| field.name() == &name)
        {
            exprs.push(lit(true).alias(name));
            changed = true;
        }
    }
    if changed {
        LogicalPlanBuilder::from(input).project(exprs)?.build()
    } else {
        Ok(input)
    }
}

/// Construct a bound binary AST without changing operand roles or evaluation order.
pub(crate) fn bound_binary(
    left: crate::planning::source::BoundMatchExpr,
    op: datafusion::logical_expr::Operator,
    right: crate::planning::source::BoundMatchExpr,
) -> crate::planning::source::BoundMatchExpr {
    crate::planning::source::BoundMatchExpr::Binary {
        left: Box::new(left),
        op,
        right: Box::new(right),
    }
}