datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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 MATCH_RECOGNIZE syntax classification and terminal conversions.

#[cfg(any(test, feature = "test-support"))]
use std::fmt::Write;

use super::*;

pub(super) fn strip_outer_parentheses(mut expr: SQLExpr) -> SQLExpr {
    while let SQLExpr::Nested(inner) = expr {
        expr = *inner;
    }
    expr
}

pub(super) fn sort_ascending(sort: &OrderByExpr) -> Result<bool> {
    if let Some(with_fill) = &sort.with_fill {
        return datafusion::common::not_impl_err!(
            "ORDER BY WITH FILL is not supported: {with_fill}"
        );
    }
    match &sort.options.sort {
        None | Some(OrderBySort::Asc) => Ok(true),
        Some(OrderBySort::Desc) => Ok(false),
        Some(OrderBySort::Using(operator)) => {
            datafusion::common::not_impl_err!(
                "ORDER BY USING is not supported: {operator}"
            )
        }
    }
}

#[cfg(any(test, feature = "test-support"))]
pub(super) fn push_list<T: Display>(out: &mut String, title: &str, items: &[T]) {
    if items.is_empty() {
        return;
    }
    out.push_str(title);
    out.push('\n');
    for item in items {
        let _ = writeln!(out, "  {item}");
    }
}

pub(super) fn reject_reserved_pattern_symbols(symbols: &BTreeSet<String>) -> Result<()> {
    for symbol in symbols {
        if is_reserved_internal_column_name(symbol) {
            return plan_err!(
                "MATCH_RECOGNIZE pattern symbol '{}' uses a reserved internal prefix",
                symbol
            );
        }
    }
    Ok(())
}

pub(super) fn reject_reserved_sql_expr(clause: &str, expr: &SQLExpr) -> Result<()> {
    match expr {
        SQLExpr::Identifier(ident) if is_reserved_internal_column_name(&ident.value) => {
            plan_err!(
                "MATCH_RECOGNIZE {clause} cannot reference reserved internal column '{}'",
                ident.value
            )
        }
        SQLExpr::CompoundIdentifier(parts) => {
            if let Some(ident) = parts.last()
                && is_reserved_internal_column_name(&ident.value)
            {
                return plan_err!(
                    "MATCH_RECOGNIZE {clause} cannot reference reserved internal column '{}'",
                    ident.value
                );
            }
            Ok(())
        }
        SQLExpr::Function(func) => {
            let name = function_name(func);
            if is_reserved_internal_column_name(&name) {
                return plan_err!(
                    "MATCH_RECOGNIZE {clause} cannot call reserved internal function '{}'",
                    name
                );
            }
            Ok(())
        }
        _ => Ok(()),
    }
}

pub(super) fn sql_literal_source_expr(expr: &SQLExpr) -> Result<Option<ParsedMatchExpr>> {
    let SQLExpr::Value(value) = expr else {
        return Ok(None);
    };
    let literal = match &value.value {
        Value::Null => ScalarValue::Null,
        Value::Boolean(value) => ScalarValue::Boolean(Some(*value)),
        Value::Number(value, _) => {
            let value = value.to_string();
            let parsed = value.parse::<i64>().map_err(|_| {
                datafusion::common::DataFusionError::Plan(format!(
                    "MATCH_RECOGNIZE navigation numeric literal '{value}' is not an integer"
                ))
            })?;
            ScalarValue::Int64(Some(parsed))
        }
        other => {
            if let Some(value) = other.clone().into_string() {
                ScalarValue::Utf8(Some(value))
            } else {
                return Ok(None);
            }
        }
    };
    Ok(Some(ParsedMatchExpr::Literal(literal)))
}

pub(super) fn function_name(func: &Function) -> String {
    // Match DataFusion's registry keys: preserve qualification and quoted case.
    if is_unqualified_function(func)
        && let Some(ident) = func.name.0[0].as_ident()
    {
        return IdentNormalizer::default().normalize(ident.clone());
    }
    func.name.to_string()
}

pub(super) fn is_unqualified_function(func: &Function) -> bool {
    func.name.0.len() == 1
}

pub(super) fn function_arguments_are_empty(args: &FunctionArguments) -> bool {
    match args {
        FunctionArguments::None => true,
        FunctionArguments::List(list) => {
            list.duplicate_treatment.is_none()
                && list.args.is_empty()
                && list.clauses.is_empty()
        }
        FunctionArguments::Subquery(_) => false,
    }
}

pub(super) fn ensure_mr_function_syntax(func: &Function, name: &str) -> Result<()> {
    if !function_arguments_are_empty(&func.parameters) {
        return plan_err!(
            "MATCH_RECOGNIZE function '{}' does not support function parameters",
            name
        );
    }
    if func.filter.is_some() {
        return plan_err!(
            "MATCH_RECOGNIZE function '{}' does not support FILTER",
            name
        );
    }
    if func.null_treatment.is_some() {
        return plan_err!(
            "MATCH_RECOGNIZE function '{}' does not support null treatment",
            name
        );
    }
    if func.over.is_some() {
        return plan_err!("MATCH_RECOGNIZE function '{}' does not support OVER", name);
    }
    if !func.within_group.is_empty() {
        return plan_err!(
            "MATCH_RECOGNIZE function '{}' does not support WITHIN GROUP",
            name
        );
    }
    if func.uses_odbc_syntax {
        return plan_err!(
            "MATCH_RECOGNIZE function '{}' does not support ODBC function syntax",
            name
        );
    }
    Ok(())
}

pub(super) fn metadata_function(name: &str) -> Option<MatchMetadataFunction> {
    Some(match name {
        "classifier" => MatchMetadataFunction::Classifier,
        "match_number" => MatchMetadataFunction::MatchNumber,
        "match_sequence_number" => MatchMetadataFunction::MatchSequenceNumber,
        "excluded" => MatchMetadataFunction::Excluded,
        _ => return None,
    })
}

pub(super) fn is_aggregate_function(context: &dyn ContextProvider, name: &str) -> bool {
    // Generic calls follow DataFusion's exact-key scalar precedence. Explicit
    // MATCH_RECOGNIZE metadata/navigation is dispatched before this helper.
    if context.get_function_meta(name).is_some() {
        return false;
    }
    context.get_aggregate_meta(name).is_some()
        || matches!(
            name,
            "sum"
                | "avg"
                | "average"
                | "count"
                | "min"
                | "max"
                | "bit_and"
                | "bit_or"
                | "bit_xor"
                | "bool_and"
                | "bool_or"
                | "stddev"
                | "stddev_samp"
                | "stddev_pop"
                | "var_samp"
                | "variance"
                | "var_pop"
                | "corr"
                | "covar_samp"
                | "covar_pop"
                | "median"
                | "approx_distinct"
        )
}

pub(super) fn is_window_function(context: &dyn ContextProvider, name: &str) -> bool {
    // Generic calls follow DataFusion's exact-key scalar precedence. Explicit
    // MATCH_RECOGNIZE metadata/navigation is dispatched before this helper.
    if context.get_function_meta(name).is_some() {
        return false;
    }
    context.get_window_meta(name).is_some()
        || matches!(
            name,
            "row_number"
                | "rank"
                | "dense_rank"
                | "percent_rank"
                | "cume_dist"
                | "ntile"
                | "lag"
                | "lead"
                | "first_value"
                | "last_value"
        )
}

pub(super) fn ensure_nullary_function(func: &Function, name: &str) -> Result<()> {
    if positional_expr_args(func)?.is_empty() {
        Ok(())
    } else {
        plan_err!(
            "MATCH_RECOGNIZE metadata function '{}' takes no arguments",
            name
        )
    }
}

pub(super) fn positional_expr_args(func: &Function) -> Result<Vec<SQLExpr>> {
    match &func.args {
        FunctionArguments::None => Ok(Vec::new()),
        FunctionArguments::List(list) => {
            if !list.clauses.is_empty() {
                return plan_err!(
                    "MATCH_RECOGNIZE function '{}' does not support function argument clauses",
                    func.name
                );
            }
            list.args
                .iter()
                .map(|arg| match arg {
                    FunctionArg::Unnamed(FunctionArgExpr::Expr(expr)) => Ok(expr.clone()),
                    _ => plan_err!(
                        "MATCH_RECOGNIZE function '{}' only supports positional expression arguments",
                        func.name
                    ),
                })
                .collect()
        }
        FunctionArguments::Subquery(_) => plan_err!(
            "MATCH_RECOGNIZE function '{}' does not support subquery arguments",
            func.name
        ),
    }
}

pub(super) fn mr_positional_expr_args(
    func: &Function,
    name: &str,
) -> Result<Vec<SQLExpr>> {
    if let FunctionArguments::List(list) = &func.args
        && list.duplicate_treatment.is_some()
    {
        return plan_err!(
            "MATCH_RECOGNIZE function '{}' does not support duplicate treatment",
            name
        );
    }
    positional_expr_args(func)
}

pub(super) fn single_part_object_name(name: &ObjectName) -> Result<String> {
    if name.0.len() != 1 {
        return plan_err!(
            "MATCH_RECOGNIZE qualified wildcard '{}' must use a single pattern symbol",
            name
        );
    }
    Ok(name
        .0
        .last()
        .and_then(|part| part.as_ident())
        .map(|ident| ident.value.clone())
        .unwrap_or_else(|| name.to_string()))
}

pub(super) fn default_define_window_frame() -> WindowFrame {
    WindowFrame {
        units: WindowFrameUnits::Rows,
        start_bound: WindowFrameBound::Preceding(None),
        end_bound: Some(WindowFrameBound::Following(None)),
    }
}

pub(super) fn clause_name(clause: SqlClause) -> &'static str {
    match clause {
        SqlClause::PartitionBy => "PARTITION BY",
        SqlClause::OrderBy => "ORDER BY",
        SqlClause::Define => "DEFINE",
        SqlClause::Measures => "MEASURES",
    }
}

pub(super) fn sql_unary_operator_to_match(
    op: &UnaryOperator,
) -> Result<MatchUnaryOperator> {
    match op {
        UnaryOperator::Not => Ok(MatchUnaryOperator::Not),
        UnaryOperator::Minus => Ok(MatchUnaryOperator::Minus),
        UnaryOperator::Plus => Ok(MatchUnaryOperator::Plus),
        _ => plan_err!(
            "MATCH_RECOGNIZE source expression does not support unary operator '{}'",
            op
        ),
    }
}

pub(super) fn sql_binary_operator_to_df(op: &BinaryOperator) -> Result<Operator> {
    Ok(match op {
        BinaryOperator::Plus => Operator::Plus,
        BinaryOperator::Minus => Operator::Minus,
        BinaryOperator::Multiply => Operator::Multiply,
        BinaryOperator::Divide => Operator::Divide,
        BinaryOperator::Modulo => Operator::Modulo,
        BinaryOperator::Gt => Operator::Gt,
        BinaryOperator::Lt => Operator::Lt,
        BinaryOperator::GtEq => Operator::GtEq,
        BinaryOperator::LtEq => Operator::LtEq,
        BinaryOperator::Eq => Operator::Eq,
        BinaryOperator::NotEq => Operator::NotEq,
        BinaryOperator::And => Operator::And,
        BinaryOperator::Or => Operator::Or,
        BinaryOperator::StringConcat => Operator::StringConcat,
        BinaryOperator::BitwiseAnd => Operator::BitwiseAnd,
        BinaryOperator::BitwiseOr => Operator::BitwiseOr,
        BinaryOperator::BitwiseXor | BinaryOperator::PGBitwiseXor => Operator::BitwiseXor,
        _ => {
            return plan_err!(
                "MATCH_RECOGNIZE source expression does not support binary operator '{}'",
                op
            );
        }
    })
}