datafusion-match-recognize 0.56.1

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// 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(
            _,
            SqlQuantifier::Exactly(0)
            | SqlQuantifier::AtMost(0)
            | SqlQuantifier::Range(_, 0),
        ) => {
            return datafusion::common::plan_err!(
                "MATCH_RECOGNIZE pattern quantifier upper bound must be greater than zero"
            );
        }
        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{1}?", Q::ExactlyReluctant(1)),
                ("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 bad in ["A{0}", "A{0,0}", "A{,0}", "A{0}?", "A{0,0}?", "A{,0}?"] {
                let parsed = parse_pattern(dialect, bad);
                let err = validate_sql_pattern(&parsed)
                    .expect_err(&format!("zero upper bound must fail: {bad}"));
                assert!(
                    err.to_string()
                        .contains("quantifier upper bound must be greater than zero"),
                    "{bad}: {err}"
                );
            }

            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();
    }
}