datafusion-match-recognize 0.55.0

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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// 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.

//! Parser-independent row-pattern syntax, output policy, and derived
//! structural facts shared by planning and NFA compilation.

use std::fmt::{self, Display, Formatter};

mod analysis;
mod bounds;
mod output;
mod properties;

#[cfg(test)]
pub use analysis::FixedPrefixSuffixInfo;
pub use analysis::{PatternAnalysisSummary, PatternStructuralInfo};
pub use output::{AfterMatchSkip, EmptyMatchesMode, RowsPerMatch};

/// A pattern for matching in MATCH_RECOGNIZE.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
pub enum Pattern {
    /// A single symbol
    Symbol(Symbol),
    /// An excluded symbol
    Exclude(Symbol),
    /// A permutation of symbols
    Permute(Vec<Symbol>),
    /// A concatenation of patterns
    Concat(Vec<Pattern>),
    /// A grouped pattern
    Group(Box<Pattern>),
    /// An alternation of patterns
    Alternation(Vec<Pattern>),
    /// A pattern with repetition
    Repetition(Box<Pattern>, RepetitionQuantifier),
}

/// Result of simplifying a pattern before NFA compilation.
///
/// Separate variants represent impossible and empty matches, so callers do not
/// need to encode either case as a synthetic pattern node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NormalizedPattern {
    /// Pattern can never match.
    Never,
    /// Pattern matches the empty string.
    Epsilon,
    /// Pattern still needs standard matching/compilation.
    Ast(Pattern),
}

/// A symbol in a MATCH_RECOGNIZE pattern.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
pub enum Symbol {
    /// A named symbol
    Named(String),
    /// Start of partition symbol
    Start,
    /// End of partition symbol
    End,
}

/// Quantifier for pattern repetition.
///
/// Source planning and public logical-node construction accept greedy and
/// reluctant forms. Possessive variants are internal optimizer markers whose
/// row-local exit suppression requires a proof that it preserves match results.
/// They do not define general atomic repetition for arbitrary pattern bodies,
/// and programmatic or Substrait source requests cannot supply them.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd)]
pub enum RepetitionQuantifier {
    /// Zero or more (*)
    ZeroOrMore,
    /// One or more (+)
    OneOrMore,
    /// At most one (?)
    AtMostOne,
    /// Exactly n occurrences
    Exactly(u32),
    /// At least n occurrences
    AtLeast(u32),
    /// At most n occurrences
    AtMost(u32),
    /// Between n and m occurrences
    Range(u32, u32),
    /// Zero or more, preferring fewer occurrences (*?).
    ZeroOrMoreReluctant,
    /// One or more, preferring fewer occurrences (+?).
    OneOrMoreReluctant,
    /// At most one, preferring zero occurrences (??).
    AtMostOneReluctant,
    /// Exactly n occurrences ({n}?). There is no repetition choice.
    ExactlyReluctant(u32),
    /// At least n occurrences, preferring fewer occurrences ({n,}?).
    AtLeastReluctant(u32),
    /// At most n occurrences, preferring fewer occurrences ({,n}?).
    AtMostReluctant(u32),
    /// Between n and m occurrences, preferring fewer occurrences ({n,m}?).
    RangeReluctant(u32, u32),
    /// Internal possessive marker for zero or more (*+).
    ZeroOrMorePossessive,
    /// Internal possessive marker for one or more (++).
    OneOrMorePossessive,
    /// Internal possessive marker for at most one (?+).
    AtMostOnePossessive,
    /// Internal possessive marker for exactly n occurrences ({n}+).
    ///
    /// Semantically equivalent to `Exactly(n)` because a fixed-count repetition
    /// offers no backtracking choice (it either matches n times or fails).
    /// Included to preserve the optimizer's intent and for consistency in AST transformations.
    ExactlyPossessive(u32),
    /// Internal possessive marker for at least n occurrences ({n,}+).
    AtLeastPossessive(u32),
    /// Internal possessive marker for at most n occurrences ({,m}+).
    AtMostPossessive(u32),
    /// Internal possessive marker for between n and m occurrences ({n,m}+).
    RangePossessive(u32, u32),
}

/// Preference at a repetition's continuation/exit choice.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RepetitionPreference {
    /// Prefer another occurrence before trying the following pattern.
    Greedy,
    /// Prefer the following pattern before trying another occurrence.
    Reluctant,
    /// Optimizer-proven row-local continuation/exit suppression.
    Possessive,
}

/// Shared repetition bounds and preference used by planning and compilation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct QuantifierBounds {
    /// Minimum number of repetitions required.
    pub min: u32,
    /// Maximum number of repetitions allowed. `None` means unbounded.
    pub max: Option<u32>,
    /// How to choose between continuing and exiting the repetition.
    pub preference: RepetitionPreference,
}

impl QuantifierBounds {
    /// Returns `true` when the quantifier suppresses backtracking.
    pub const fn is_possessive(self) -> bool {
        matches!(self.preference, RepetitionPreference::Possessive)
    }

    /// Returns `true` when the quantifier prefers fewer repetitions.
    pub const fn is_reluctant(self) -> bool {
        matches!(self.preference, RepetitionPreference::Reluctant)
    }

    /// Returns the exact repetition count when the quantifier is fixed.
    pub const fn fixed_count(self) -> Option<u32> {
        match self.max {
            Some(max) if max == self.min => Some(self.min),
            _ => None,
        }
    }
}

impl RepetitionQuantifier {
    /// Return this quantifier's bounds and repetition preference.
    pub(crate) const fn bounds(&self) -> QuantifierBounds {
        let (min, max) = match self {
            Self::ZeroOrMore | Self::ZeroOrMoreReluctant | Self::ZeroOrMorePossessive => {
                (0, None)
            }
            Self::OneOrMore | Self::OneOrMoreReluctant | Self::OneOrMorePossessive => {
                (1, None)
            }
            Self::AtMostOne | Self::AtMostOneReluctant | Self::AtMostOnePossessive => {
                (0, Some(1))
            }
            Self::Exactly(n) | Self::ExactlyReluctant(n) | Self::ExactlyPossessive(n) => {
                (*n, Some(*n))
            }
            Self::AtLeast(n) | Self::AtLeastReluctant(n) | Self::AtLeastPossessive(n) => {
                (*n, None)
            }
            Self::AtMost(n) | Self::AtMostReluctant(n) | Self::AtMostPossessive(n) => {
                (0, Some(*n))
            }
            Self::Range(min, max)
            | Self::RangeReluctant(min, max)
            | Self::RangePossessive(min, max) => (*min, Some(*max)),
        };
        let preference = match self {
            Self::ZeroOrMoreReluctant
            | Self::OneOrMoreReluctant
            | Self::AtMostOneReluctant
            | Self::ExactlyReluctant(_)
            | Self::AtLeastReluctant(_)
            | Self::AtMostReluctant(_)
            | Self::RangeReluctant(_, _) => RepetitionPreference::Reluctant,
            Self::ZeroOrMorePossessive
            | Self::OneOrMorePossessive
            | Self::AtMostOnePossessive
            | Self::ExactlyPossessive(_)
            | Self::AtLeastPossessive(_)
            | Self::AtMostPossessive(_)
            | Self::RangePossessive(_, _) => RepetitionPreference::Possessive,
            _ => RepetitionPreference::Greedy,
        };
        QuantifierBounds {
            min,
            max,
            preference,
        }
    }

    /// Returns `true` when the quantifier is possessive.
    pub const fn is_possessive(&self) -> bool {
        self.bounds().is_possessive()
    }

    /// Returns `true` when the quantifier prefers fewer repetitions.
    pub const fn is_reluctant(&self) -> bool {
        self.bounds().is_reluctant()
    }

    /// Returns the exact repetition count when the quantifier is fixed.
    pub const fn fixed_count(&self) -> Option<u32> {
        self.bounds().fixed_count()
    }

    /// Returns the minimum number of repetitions required.
    pub const fn min_repetitions(&self) -> u32 {
        self.bounds().min
    }

    /// Returns the maximum number of repetitions allowed, if bounded.
    pub const fn max_repetitions(&self) -> Option<u32> {
        self.bounds().max
    }

    /// Return an equivalent standard spelling, such as `?` for `{0,1}`, while
    /// preserving repetition preference.
    pub fn normalized(&self) -> Self {
        let greedy = match self {
            Self::Range(min, max)
            | Self::RangeReluctant(min, max)
            | Self::RangePossessive(min, max)
                if min == max =>
            {
                Self::Exactly(*min)
            }
            Self::AtLeast(0) | Self::AtLeastReluctant(0) | Self::AtLeastPossessive(0) => {
                Self::ZeroOrMore
            }
            Self::AtLeast(1) | Self::AtLeastReluctant(1) | Self::AtLeastPossessive(1) => {
                Self::OneOrMore
            }
            Self::AtMost(1)
            | Self::Range(0, 1)
            | Self::AtMostReluctant(1)
            | Self::RangeReluctant(0, 1)
            | Self::AtMostPossessive(1)
            | Self::RangePossessive(0, 1) => Self::AtMostOne,
            _ => return self.clone(),
        };
        match self.bounds().preference {
            RepetitionPreference::Greedy => greedy,
            RepetitionPreference::Reluctant => greedy
                .reluctant_variant()
                .expect("normalized spelling is greedy"),
            RepetitionPreference::Possessive => greedy
                .possessive_variant()
                .expect("normalized spelling is greedy"),
        }
    }

    /// Returns the reluctant counterpart when this quantifier is greedy.
    pub fn reluctant_variant(&self) -> Option<Self> {
        match self {
            Self::ZeroOrMore => Some(Self::ZeroOrMoreReluctant),
            Self::OneOrMore => Some(Self::OneOrMoreReluctant),
            Self::AtMostOne => Some(Self::AtMostOneReluctant),
            Self::Exactly(n) => Some(Self::ExactlyReluctant(*n)),
            Self::AtLeast(n) => Some(Self::AtLeastReluctant(*n)),
            Self::AtMost(n) => Some(Self::AtMostReluctant(*n)),
            Self::Range(min, max) => Some(Self::RangeReluctant(*min, *max)),
            _ => None,
        }
    }

    /// Return the internal possessive marker when this quantifier is greedy.
    /// The optimizer must establish that its exit suppression preserves results.
    pub fn possessive_variant(&self) -> Option<Self> {
        match self {
            Self::ZeroOrMore => Some(Self::ZeroOrMorePossessive),
            Self::OneOrMore => Some(Self::OneOrMorePossessive),
            Self::AtMostOne => Some(Self::AtMostOnePossessive),
            Self::Exactly(n) => Some(Self::ExactlyPossessive(*n)),
            Self::AtLeast(n) => Some(Self::AtLeastPossessive(*n)),
            Self::AtMost(n) => Some(Self::AtMostPossessive(*n)),
            Self::Range(min, max) => Some(Self::RangePossessive(*min, *max)),
            _ => None,
        }
    }
}

// Display implementations

impl Display for Symbol {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            Symbol::Named(name) => write!(f, "{name}"),
            Symbol::Start => write!(f, "^"),
            Symbol::End => write!(f, "$"),
        }
    }
}

impl Display for RepetitionQuantifier {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            Self::ZeroOrMore | Self::ZeroOrMoreReluctant | Self::ZeroOrMorePossessive => {
                write!(f, "*")
            }
            Self::OneOrMore | Self::OneOrMoreReluctant | Self::OneOrMorePossessive => {
                write!(f, "+")
            }
            Self::AtMostOne | Self::AtMostOneReluctant | Self::AtMostOnePossessive => {
                write!(f, "?")
            }
            Self::Exactly(n) | Self::ExactlyReluctant(n) | Self::ExactlyPossessive(n) => {
                write!(f, "{{{n}}}")
            }
            Self::AtLeast(n) | Self::AtLeastReluctant(n) | Self::AtLeastPossessive(n) => {
                write!(f, "{{{n},}}")
            }
            Self::AtMost(n) | Self::AtMostReluctant(n) | Self::AtMostPossessive(n) => {
                write!(f, "{{,{n}}}")
            }
            Self::Range(min, max)
            | Self::RangeReluctant(min, max)
            | Self::RangePossessive(min, max) => write!(f, "{{{min},{max}}}"),
        }?;
        f.write_str(match self.bounds().preference {
            RepetitionPreference::Greedy => "",
            RepetitionPreference::Reluctant => "?",
            RepetitionPreference::Possessive => "+",
        })
    }
}

// Pattern tokens need delimiters around identifiers that could change the
// displayed syntax. Symbol itself still displays the stored name.
fn fmt_pattern_symbol(symbol: &Symbol, f: &mut Formatter<'_>) -> fmt::Result {
    let Symbol::Named(name) = symbol else {
        return Display::fmt(symbol, f);
    };
    let mut bytes = name.bytes();
    let bare_name = bytes
        .next()
        .is_some_and(|first| first.is_ascii_alphabetic() || first == b'_')
        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_');
    if bare_name && !name.eq_ignore_ascii_case("PERMUTE") {
        f.write_str(name)
    } else {
        write!(f, "\"{}\"", name.replace('"', "\"\""))
    }
}

impl Display for Pattern {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            Pattern::Symbol(symbol) => fmt_pattern_symbol(symbol, f),
            Pattern::Exclude(symbol) => {
                f.write_str("{- ")?;
                fmt_pattern_symbol(symbol, f)?;
                f.write_str(" -}")
            }
            Pattern::Permute(symbols) => {
                f.write_str("PERMUTE(")?;
                for (index, symbol) in symbols.iter().enumerate() {
                    if index > 0 {
                        f.write_str(",")?;
                    }
                    fmt_pattern_symbol(symbol, f)?;
                }
                f.write_str(")")
            }
            Pattern::Concat(patterns) | Pattern::Alternation(patterns) => {
                let is_concat = matches!(self, Pattern::Concat(_));
                let separator = if is_concat { " " } else { "|" };
                for (index, pattern) in patterns.iter().enumerate() {
                    if index > 0 {
                        f.write_str(separator)?;
                    }
                    // Normalization need not retain explicit Group nodes.
                    // Alternation binds less tightly than concatenation; an
                    // excluded atom also needs parentheses here so SQL parsers
                    // do not read its opening brace as the previous atom's bound.
                    let grouped = is_concat
                        && match pattern {
                            Pattern::Alternation(_) | Pattern::Exclude(_) => true,
                            Pattern::Repetition(inner, _) => {
                                matches!(inner.as_ref(), Pattern::Exclude(_))
                            }
                            _ => false,
                        };
                    if grouped {
                        write!(f, "({pattern})")?;
                    } else {
                        write!(f, "{pattern}")?;
                    }
                }
                Ok(())
            }
            Pattern::Group(pattern) => write!(f, "({pattern})"),
            Pattern::Repetition(pattern, quantifier) => {
                if matches!(
                    pattern.as_ref(),
                    Pattern::Repetition(..)
                        | Pattern::Concat(_)
                        | Pattern::Alternation(_)
                ) {
                    write!(f, "({pattern}){quantifier}")
                } else {
                    write!(f, "{pattern}{quantifier}")
                }
            }
        }
    }
}

#[cfg(test)]
mod tests;