datafusion-match-recognize 0.55.0

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.

//! Pattern queries for symbols, anchors, exclusions, and compact paths.

use std::collections::BTreeSet;

use super::{Pattern, Symbol};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SingleNamedSymbolMode {
    Exact,
    CompactPath,
    FixedWidth,
}

impl Pattern {
    /// Returns `true` when a repetition can choose to exit before continuing.
    /// Fixed-count reluctant spellings have no such choice.
    pub fn has_reluctant_choice(&self) -> bool {
        match self {
            Self::Repetition(inner, quantifier) => {
                (quantifier.is_reluctant() && quantifier.fixed_count().is_none())
                    || inner.has_reluctant_choice()
            }
            Self::Concat(parts) | Self::Alternation(parts) => {
                parts.iter().any(Self::has_reluctant_choice)
            }
            Self::Group(inner) => inner.has_reluctant_choice(),
            Self::Symbol(_) | Self::Exclude(_) | Self::Permute(_) => false,
        }
    }

    /// Return sorted, distinct named symbols with their exact spelling.
    ///
    /// Includes excluded and permuted symbols; anchors are omitted.
    pub fn symbol_names(&self) -> BTreeSet<String> {
        fn collect(pattern: &Pattern, output: &mut BTreeSet<String>) {
            match pattern {
                Pattern::Symbol(Symbol::Named(name))
                | Pattern::Exclude(Symbol::Named(name)) => {
                    output.insert(name.clone());
                }
                Pattern::Permute(permuted) => {
                    for symbol in permuted {
                        if let Symbol::Named(name) = symbol {
                            output.insert(name.clone());
                        }
                    }
                }
                Pattern::Concat(patterns) | Pattern::Alternation(patterns) => {
                    for pattern in patterns {
                        collect(pattern, output);
                    }
                }
                Pattern::Group(pattern) | Pattern::Repetition(pattern, _) => {
                    collect(pattern, output);
                }
                Pattern::Symbol(Symbol::Start | Symbol::End)
                | Pattern::Exclude(Symbol::Start | Symbol::End) => {}
            }
        }

        let mut symbols = BTreeSet::new();
        collect(self, &mut symbols);
        symbols
    }

    /// Returns `true` if this pattern contains any anchors (^ or $).
    pub fn has_anchors(&self) -> bool {
        self.structural_info().has_anchors()
    }

    /// Returns `true` if any branch contains an end-of-partition anchor.
    pub fn has_end_anchor(&self) -> bool {
        match self {
            Self::Symbol(Symbol::End) | Self::Exclude(Symbol::End) => true,
            Self::Symbol(_) | Self::Exclude(_) => false,
            Self::Permute(symbols) => symbols.contains(&Symbol::End),
            Self::Concat(patterns) | Self::Alternation(patterns) => {
                patterns.iter().any(Self::has_end_anchor)
            }
            Self::Group(inner) | Self::Repetition(inner, _) => inner.has_end_anchor(),
        }
    }

    /// Returns `true` if this pattern contains any exclusion constructs ({- ... -}).
    pub fn has_exclusions(&self) -> bool {
        self.structural_info().has_exclusions()
    }

    /// Identify the symbol in a repetition whose preference follows its endpoint.
    ///
    /// The outer repetition is fixed-count or prefers continuation. Its body is
    /// a named symbol, optionally wrapped in groups and fixed-count repetitions.
    pub fn single_symbol_name(&self) -> Option<&str> {
        self.single_named_symbol_name(SingleNamedSymbolMode::CompactPath)
    }

    fn single_named_symbol_name(&self, mode: SingleNamedSymbolMode) -> Option<&str> {
        match self {
            Pattern::Symbol(Symbol::Named(name)) => {
                (mode != SingleNamedSymbolMode::CompactPath).then_some(name)
            }
            Pattern::Repetition(inner, quantifier) => {
                let fixed_count = quantifier.fixed_count().is_some();
                let eligible = match mode {
                    SingleNamedSymbolMode::Exact => false,
                    SingleNamedSymbolMode::CompactPath => {
                        fixed_count || !quantifier.is_reluctant()
                    }
                    SingleNamedSymbolMode::FixedWidth => fixed_count,
                };
                // Endpoints alone preserve the outer continuation order only
                // when each copy consumes the same number of rows. For example,
                // (A{2,3})+ can prefer three rows over two copies of two.
                if eligible {
                    inner.single_named_symbol_name(SingleNamedSymbolMode::FixedWidth)
                } else {
                    None
                }
            }
            Pattern::Group(inner) => inner.single_named_symbol_name(mode),
            _ => None,
        }
    }

    /// Returns the symbol name if this pattern is exactly a single named symbol.
    pub(crate) fn get_single_named_symbol(&self) -> Option<&str> {
        self.single_named_symbol_name(SingleNamedSymbolMode::Exact)
    }
}