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.

//! Converts sqlparser row-pattern nodes to the shared `Pattern` type.
#![doc(hidden)]

use crate::core::{Pattern, RepetitionQuantifier, Symbol};
use datafusion::common::Result;
use datafusion::sql::sqlparser::ast::{
    MatchRecognizePattern as SqlPattern, MatchRecognizeSymbol as SqlSymbol,
    RepetitionQuantifier as SqlQuantifier,
};

/// Drop the children iteratively: sqlparser can nest one node per suffix.
pub(crate) fn dismantle_sql_pattern(pattern: &mut SqlPattern) {
    let mut stack = vec![std::mem::replace(
        pattern,
        SqlPattern::Symbol(SqlSymbol::Start),
    )];
    while let Some(node) = stack.pop() {
        match node {
            SqlPattern::Concat(parts) | SqlPattern::Alternation(parts) => {
                stack.extend(parts)
            }
            SqlPattern::Group(inner) | SqlPattern::Repetition(inner, _) => {
                stack.push(*inner)
            }
            SqlPattern::Symbol(_) | SqlPattern::Exclude(_) | SqlPattern::Permute(_) => {}
        }
    }
}

/// Reject invalid ranges and SQL spellings whose parsed pattern would change
/// the requested semantics, including invalid stacked suffixes and unquoted `$`
/// names. A single `?` suffix on a quantifier selects reluctant repetition.
pub fn validate_sql_pattern(p: &SqlPattern) -> Result<()> {
    match p {
        SqlPattern::Concat(parts) | SqlPattern::Alternation(parts) => {
            for part in parts {
                validate_sql_pattern(part)?;
            }
        }
        SqlPattern::Repetition(_, SqlQuantifier::Range(min, max)) if min > max => {
            return datafusion::common::plan_err!(
                "MATCH_RECOGNIZE pattern quantifier lower bound {} exceeds upper bound {}",
                min,
                max
            );
        }
        SqlPattern::Repetition(inner, outer)
            if matches!(inner.as_ref(), SqlPattern::Repetition(..)) =>
        {
            // The Group node distinguishes `(A+)?` from the reluctant `A+?`.
            if let SqlPattern::Repetition(base, _) = inner.as_ref()
                && matches!(outer, SqlQuantifier::AtMostOne)
                && !matches!(base.as_ref(), SqlPattern::Repetition(..))
            {
                return validate_sql_pattern(inner);
            }
            let (reason, qualification) = match outer {
                SqlQuantifier::OneOrMore => (
                    "MATCH_RECOGNIZE possessive quantifiers are not supported",
                    " only if nested greedy repetition is intended",
                ),
                _ => (
                    "MATCH_RECOGNIZE pattern cannot apply two quantifiers to one element",
                    "",
                ),
            };
            return datafusion::common::plan_err!(
                "{reason}; group nested quantifiers explicitly, for example '(A+){outer}'{qualification}"
            );
        }
        SqlPattern::Group(inner) | SqlPattern::Repetition(inner, _) => {
            validate_sql_pattern(inner)?;
        }
        SqlPattern::Exclude(SqlSymbol::Start | SqlSymbol::End) => {
            return datafusion::common::plan_err!(
                "MATCH_RECOGNIZE pattern exclusion can only wrap a pattern symbol"
            );
        }
        SqlPattern::Permute(symbols)
            if symbols
                .iter()
                .any(|symbol| matches!(symbol, SqlSymbol::Start | SqlSymbol::End)) =>
        {
            return datafusion::common::plan_err!(
                "MATCH_RECOGNIZE PERMUTE can only contain pattern symbols"
            );
        }
        SqlPattern::Symbol(symbol) | SqlPattern::Exclude(symbol) => {
            validate_sql_symbol(symbol)?;
        }
        SqlPattern::Permute(symbols) => {
            for symbol in symbols {
                validate_sql_symbol(symbol)?;
            }
        }
    }
    Ok(())
}

fn validate_sql_symbol(symbol: &SqlSymbol) -> Result<()> {
    // All three MATCH_RECOGNIZE dialects accept `$` inside identifiers.
    // Check before symbol collection discards the identifier's quote style.
    if let SqlSymbol::Named(ident) = symbol
        && ident.quote_style.is_none()
        && ident.value.contains('$')
    {
        return datafusion::common::plan_err!(
            "MATCH_RECOGNIZE pattern symbol '{}' contains '$'; separate the end anchor with a space (for example 'B $') or quote the symbol name",
            ident.value
        );
    }
    Ok(())
}

/// Convert an sqlparser `MatchRecognizePattern` node into the shared [`Pattern`]
/// representation.
pub fn sql_pattern_to_df(p: &SqlPattern) -> Pattern {
    match p {
        SqlPattern::Symbol(s) => Pattern::Symbol(conv_sym(s)),
        SqlPattern::Exclude(s) => Pattern::Exclude(conv_sym(s)),
        SqlPattern::Permute(list) => {
            Pattern::Permute(list.iter().map(conv_sym).collect())
        }
        SqlPattern::Concat(parts) => {
            Pattern::Concat(parts.iter().map(sql_pattern_to_df).collect())
        }
        SqlPattern::Group(inner) => Pattern::Group(Box::new(sql_pattern_to_df(inner))),
        SqlPattern::Alternation(parts) => {
            Pattern::Alternation(parts.iter().map(sql_pattern_to_df).collect())
        }
        SqlPattern::Repetition(inner, q) => {
            // sqlparser represents `A+?` as two repetitions rather than a
            // quantifier flag. Explicit parentheses have a separate Group node.
            let (inner, quantifier) = match (inner.as_ref(), q) {
                (SqlPattern::Repetition(base, quantifier), SqlQuantifier::AtMostOne) => (
                    base.as_ref(),
                    conv_quant(quantifier)
                        .reluctant_variant()
                        .expect("sqlparser quantifiers are greedy"),
                ),
                _ => (inner.as_ref(), conv_quant(q)),
            };
            Pattern::Repetition(Box::new(sql_pattern_to_df(inner)), quantifier)
        }
    }
}

fn conv_sym(s: &SqlSymbol) -> Symbol {
    match s {
        SqlSymbol::Named(ident) => Symbol::Named(ident.value.clone()),
        SqlSymbol::Start => Symbol::Start,
        SqlSymbol::End => Symbol::End,
    }
}

fn conv_quant(q: &SqlQuantifier) -> RepetitionQuantifier {
    match q {
        SqlQuantifier::ZeroOrMore => RepetitionQuantifier::ZeroOrMore,
        SqlQuantifier::OneOrMore => RepetitionQuantifier::OneOrMore,
        SqlQuantifier::AtMostOne => RepetitionQuantifier::AtMostOne,
        SqlQuantifier::Exactly(n) => RepetitionQuantifier::Exactly(*n),
        SqlQuantifier::AtLeast(n) => RepetitionQuantifier::AtLeast(*n),
        SqlQuantifier::AtMost(n) => RepetitionQuantifier::AtMost(*n),
        SqlQuantifier::Range(n, m) => RepetitionQuantifier::Range(*n, *m),
    }
}

#[cfg(test)]
mod tests {
    use datafusion::sql::sqlparser::ast::{
        Ident, MatchRecognizePattern as SqlPattern, MatchRecognizeSymbol as SqlSymbol,
        RepetitionQuantifier as SqlQuantifier, SetExpr, Statement, TableFactor,
    };
    use datafusion::sql::sqlparser::dialect::{
        Dialect, GenericDialect, OracleDialect, SnowflakeDialect,
    };
    use datafusion::sql::sqlparser::parser::Parser;

    use super::{dismantle_sql_pattern, sql_pattern_to_df, validate_sql_pattern};
    use crate::core::{Pattern, RepetitionQuantifier, Symbol};

    fn symbol(name: &str) -> SqlPattern {
        SqlPattern::Symbol(SqlSymbol::Named(Ident::new(name)))
    }

    fn parse_pattern(dialect: &dyn Dialect, pattern: &str) -> SqlPattern {
        let sql = format!(
            "SELECT * FROM t MATCH_RECOGNIZE (PATTERN ({pattern}) DEFINE A AS true)"
        );
        let Statement::Query(query) = Parser::parse_sql(dialect, &sql)
            .expect("MATCH_RECOGNIZE query")
            .pop()
            .unwrap()
        else {
            panic!("expected query")
        };
        let SetExpr::Select(select) = *query.body else {
            panic!("expected SELECT")
        };
        let TableFactor::MatchRecognize { pattern, .. } =
            select.from.into_iter().next().unwrap().relation
        else {
            panic!("expected MATCH_RECOGNIZE")
        };
        pattern
    }

    #[test]
    fn deeply_stacked_quantifiers_return_a_plan_error() {
        use datafusion::common::DataFusionError;

        let mut pattern =
            parse_pattern(&GenericDialect, &format!("A{}", "+".repeat(10_000)));
        let result = validate_sql_pattern(&pattern);
        dismantle_sql_pattern(&mut pattern);
        assert!(
            matches!(result, Err(DataFusionError::Plan(reason)) if reason.contains("possessive quantifiers"))
        );
    }

    #[test]
    fn parsed_patterns_preserve_supported_spellings() {
        // Each supported dialect is public: sqlparser represents reluctant
        // quantifiers as stacked nodes and admits '$' in unquoted symbols.
        for dialect in [
            &GenericDialect as &dyn Dialect,
            &OracleDialect,
            &SnowflakeDialect,
        ] {
            for (sql, error) in [
                ("A++", "possessive quantifiers"),
                ("A*+", "possessive quantifiers"),
                ("A{2}{2}", "cannot apply two quantifiers"),
                ("A+??", "cannot apply two quantifiers"),
                ("A{1,2}??", "cannot apply two quantifiers"),
                ("A???", "cannot apply two quantifiers"),
                ("A+?+", "possessive quantifiers"),
                ("A*?{2}", "cannot apply two quantifiers"),
                ("A{3,2}?", "lower bound 3 exceeds upper bound 2"),
                ("B$", "symbol 'B$' contains '$'"),
                ("A$B", "symbol 'A$B' contains '$'"),
                ("{- B$ -}", "symbol 'B$' contains '$'"),
                ("PERMUTE(A, B$)", "symbol 'B$' contains '$'"),
            ] {
                let rejected =
                    validate_sql_pattern(&parse_pattern(dialect, sql)).expect_err(sql);
                assert!(rejected.to_string().contains(error), "{sql}: {rejected}");
            }
            for sql in ["A B $", "A \"B$\"", "{- \"B$\" -}", "PERMUTE(A, \"B$\")"] {
                validate_sql_pattern(&parse_pattern(dialect, sql)).expect(sql);
            }

            let SqlPattern::Repetition(inner, SqlQuantifier::AtMostOne) =
                parse_pattern(dialect, "A+?")
            else {
                panic!("sqlparser changed the stacked-quantifier representation")
            };
            assert!(matches!(inner.as_ref(), SqlPattern::Repetition(..)));
            assert_eq!(parse_pattern(dialect, "B$"), symbol("B$"));
        }
    }

    #[test]
    fn formatted_pattern_preserves_quoted_symbol_tokens() {
        for dialect in [
            &GenericDialect as &dyn Dialect,
            &OracleDialect,
            &SnowflakeDialect,
        ] {
            for (sql, expected) in [
                ("A B", "A B"),
                (r#"A "LOW HIGH""#, r#"A "LOW HIGH""#),
                (r#"A ({- "a""b" -})"#, r#"A ({- "a""b" -})"#),
                (r#""$" $"#, r#""$" $"#),
                (r#"PERMUTE(A, "B$")"#, r#"PERMUTE(A,"B$")"#),
                (r#""PERMUTE""#, r#""PERMUTE""#),
            ] {
                let pattern = sql_pattern_to_df(&parse_pattern(dialect, sql));
                let displayed = pattern.to_string();
                assert_eq!(displayed, expected);
                let reparsed = parse_pattern(dialect, &displayed);
                validate_sql_pattern(&reparsed).expect(sql);
                assert_eq!(sql_pattern_to_df(&reparsed), pattern, "{sql}");
            }
        }
        assert_eq!(Symbol::Named("LOW HIGH".into()).to_string(), "LOW HIGH");
    }

    #[test]
    fn reluctant_quantifiers_preserve_bounds_and_grouping() {
        use RepetitionQuantifier as Q;

        for dialect in [
            &GenericDialect as &dyn Dialect,
            &OracleDialect,
            &SnowflakeDialect,
        ] {
            for (sql, quantifier) in [
                ("A*?", Q::ZeroOrMoreReluctant),
                ("A+?", Q::OneOrMoreReluctant),
                ("A??", Q::AtMostOneReluctant),
                ("A{0}?", Q::ExactlyReluctant(0)),
                ("A{2}?", Q::ExactlyReluctant(2)),
                ("A{2,}?", Q::AtLeastReluctant(2)),
                ("A{,3}?", Q::AtMostReluctant(3)),
                ("A{1,3}?", Q::RangeReluctant(1, 3)),
            ] {
                let parsed = parse_pattern(dialect, sql);
                validate_sql_pattern(&parsed).expect(sql);
                let converted = sql_pattern_to_df(&parsed);
                assert_eq!(
                    converted,
                    Pattern::Repetition(
                        Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
                        quantifier,
                    ),
                    "{sql}"
                );
            }

            for (sql, inner, outer) in [
                ("(A+)?", Q::OneOrMore, Q::AtMostOne),
                ("(A+?)?", Q::OneOrMoreReluctant, Q::AtMostOne),
                ("(A+?)??", Q::OneOrMoreReluctant, Q::AtMostOneReluctant),
                ("(A{2}){2}", Q::Exactly(2), Q::Exactly(2)),
                ("(A+?)+", Q::OneOrMoreReluctant, Q::OneOrMore),
            ] {
                let parsed = parse_pattern(dialect, sql);
                validate_sql_pattern(&parsed).expect(sql);
                assert_eq!(
                    sql_pattern_to_df(&parsed),
                    Pattern::Repetition(
                        Box::new(Pattern::Group(Box::new(Pattern::Repetition(
                            Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
                            inner,
                        )))),
                        outer,
                    ),
                    "{sql}"
                );
            }
        }
    }

    #[test]
    fn raw_pattern_validation_checks_anchor_context_and_ordered_ranges() {
        for (pattern, context) in [
            (
                SqlPattern::Exclude(SqlSymbol::End),
                "pattern exclusion can only wrap a pattern symbol",
            ),
            (
                SqlPattern::Permute(vec![
                    SqlSymbol::Start,
                    SqlSymbol::Named(Ident::new("A")),
                ]),
                "PERMUTE can only contain pattern symbols",
            ),
            (
                SqlPattern::Repetition(Box::new(symbol("A")), SqlQuantifier::Range(3, 2)),
                "lower bound 3 exceeds upper bound 2",
            ),
        ] {
            let error = validate_sql_pattern(&pattern).unwrap_err().to_string();
            assert!(error.contains(context), "{error}");
        }
        validate_sql_pattern(&SqlPattern::Repetition(
            Box::new(symbol("A")),
            SqlQuantifier::Range(2, 3),
        ))
        .unwrap();
    }
}