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.

//! Shared constants and helpers for MATCH_RECOGNIZE virtual columns.
//!
//! These are used across source planning, logical planning, and physical
//! execution, including generated columns for managed DEFINE state and
//! partial static extraction.

use std::fmt::{self, Display, Formatter};
use std::str::FromStr;
use std::sync::Arc;

use datafusion::arrow::datatypes::{DataType, Field};

/// Prefix reserved for MATCH_RECOGNIZE internal columns.
pub const MR_INTERNAL_PREFIX: &str = "__mr_";
// Prefix for DEFINE-derived boolean symbol columns
const MR_SYMBOL_PREFIX: &str = "__mr_symbol_";
// Prefix for classifier bitset columns
const MR_CLASSIFIER_BITS_PREFIX: &str = "__mr_classifier_";
// Prefix for managed aggregate columns
const MR_MANAGED_AGGREGATE_PREFIX: &str = "__mr_managed_agg_";
/// Prefix for generated static-extraction columns.
pub const MR_STATIC_EXTRACTION_PREFIX: &str = "__mr_static_";

/// Lower bound used to distinguish matched rows from `PREV` buffer rows.
pub const MIN_VALID_MATCH_SEQUENCE_NUMBER: i64 = 0;
/// Upper bound used to distinguish matched rows from `NEXT` buffer rows.
pub const MAX_VALID_MATCH_SEQUENCE_NUMBER: i64 = (1i64 << 62) - 1;

#[derive(Debug, Clone)]
struct MetadataDescriptor {
    name: &'static str,
    data_type: DataType,
    nullable: bool,
    measure_function_name: &'static str,
}

/// Metadata columns produced at the matcher boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MatchMetadataColumn {
    /// Pattern symbol assigned to the output row.
    Classifier,
    /// One-based selected-match number within a partition.
    MatchNumber,
    /// One-based row position within a match.
    MatchSequenceNumber,
    /// Whether the row was consumed inside an exclusion block.
    Excluded,
    /// Internal candidate-path identity used for match-aware reconciliation.
    PathId,
}

impl MatchMetadataColumn {
    fn descriptor(self) -> MetadataDescriptor {
        match self {
            Self::Classifier => MetadataDescriptor {
                name: "__mr_classifier",
                data_type: DataType::Utf8,
                nullable: true,
                measure_function_name: "classifier",
            },
            Self::MatchNumber => MetadataDescriptor {
                name: "__mr_match_number",
                data_type: DataType::Int64,
                nullable: true,
                measure_function_name: "match_number",
            },
            Self::MatchSequenceNumber => MetadataDescriptor {
                name: "__mr_match_sequence_number",
                data_type: DataType::Int64,
                nullable: true,
                measure_function_name: "match_sequence_number",
            },
            Self::Excluded => MetadataDescriptor {
                name: "__mr_excluded",
                data_type: DataType::Boolean,
                nullable: true,
                measure_function_name: "excluded",
            },
            Self::PathId => MetadataDescriptor {
                name: "__mr_path_id",
                data_type: DataType::Int64,
                nullable: false,
                measure_function_name: "path_id",
            },
        }
    }

    /// Return the Arrow data type of this metadata column.
    pub fn data_type(&self) -> DataType {
        self.descriptor().data_type
    }

    /// Return whether this metadata column is nullable.
    pub fn is_nullable(&self) -> bool {
        self.descriptor().nullable
    }

    /// Return the associated function name without parentheses.
    ///
    /// [`Self::PathId`] returns `path_id`, an internal name, not a public SQL function.
    pub fn measure_function_name(&self) -> &'static str {
        self.descriptor().measure_function_name
    }

    /// Return all metadata columns in their defined output order.
    pub const fn all() -> [Self; 5] {
        [
            Self::Classifier,
            Self::MatchNumber,
            Self::MatchSequenceNumber,
            Self::Excluded,
            Self::PathId,
        ]
    }

    /// Metadata columns that may appear in a final public output specification.
    ///
    /// Internal-only metadata such as [`Self::PathId`] is deliberately excluded.
    pub const fn public_output() -> [Self; 4] {
        [
            Self::Classifier,
            Self::MatchNumber,
            Self::MatchSequenceNumber,
            Self::Excluded,
        ]
    }

    /// Return the unqualified Arrow field for this metadata column.
    pub fn arrow_field(self) -> Arc<Field> {
        let descriptor = self.descriptor();
        Arc::new(Field::new(
            descriptor.name,
            descriptor.data_type,
            descriptor.nullable,
        ))
    }
}

impl AsRef<str> for MatchMetadataColumn {
    fn as_ref(&self) -> &str {
        self.descriptor().name
    }
}

impl FromStr for MatchMetadataColumn {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::all()
            .into_iter()
            .find(|column| column.as_ref() == s)
            .ok_or(())
    }
}

impl Display for MatchMetadataColumn {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_ref())
    }
}

/// Build the generated Boolean predicate-column name for `symbol`.
pub fn symbol_col_name(symbol: &str) -> String {
    format!("{MR_SYMBOL_PREFIX}{}", symbol.to_ascii_lowercase())
}

/// Check if a column name is reserved for MATCH_RECOGNIZE internal use.
pub fn is_reserved_internal_column_name(name: &str) -> bool {
    name.get(..MR_INTERNAL_PREFIX.len())
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(MR_INTERNAL_PREFIX))
}

/// Build the generated classifier-bitset column name for `symbol`.
pub fn classifier_bits_col_name(symbol: &str) -> String {
    format!("{MR_CLASSIFIER_BITS_PREFIX}{}", symbol.to_ascii_lowercase())
}

fn classifier_bits_field(symbol: &str) -> Arc<Field> {
    Arc::new(Field::new(
        classifier_bits_col_name(symbol),
        DataType::Boolean,
        true,
    ))
}

/// Arrow fields for classifier bitset columns `__mr_classifier_<SYM>`.
///
/// These are nullable because unmatched and buffered rows can carry NULL
/// classifier bits.
pub fn classifier_bits_arrow_fields(symbols: &[String]) -> Vec<Arc<Field>> {
    symbols
        .iter()
        .map(|symbol| classifier_bits_field(symbol))
        .collect()
}

/// Build the generated column name for an AND-side static predicate.
pub fn static_predicate_and_col_name(id: usize) -> String {
    format!("{MR_STATIC_EXTRACTION_PREFIX}predicate_and_{id}")
}

/// Build the generated column name for an OR-side static predicate.
pub fn static_predicate_or_col_name(id: usize) -> String {
    format!("{MR_STATIC_EXTRACTION_PREFIX}predicate_or_{id}")
}

/// Build the generated column name for an extracted static scalar.
pub fn static_scalar_col_name(id: usize) -> String {
    format!("{MR_STATIC_EXTRACTION_PREFIX}scalar_{id}")
}

/// Build `__mr_managed_agg_<id>` column name.
pub fn managed_aggregate_col_name(id: usize) -> String {
    format!("{MR_MANAGED_AGGREGATE_PREFIX}{id}")
}

/// The Boolean position in which a static predicate can short-circuit evaluation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StaticPredicateKind {
    /// A false predicate short-circuits the AND condition and rejects the symbol.
    BooleanAnd,
    /// A true predicate short-circuits the OR condition and accepts the symbol.
    BooleanOr,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn public_output_metadata_excludes_internal_path_id() {
        assert!(
            !MatchMetadataColumn::public_output().contains(&MatchMetadataColumn::PathId)
        );
        assert!(MatchMetadataColumn::all().contains(&MatchMetadataColumn::PathId));
    }

    #[test]
    fn internal_column_reservation_checks_case_and_prefix_boundaries() {
        for (name, reserved) in [
            ("__mr_match_number", true),
            ("__MR_classifier_a", true),
            ("__Mr_symbol_a", true),
            ("__mr", false),
            ("user___mr_match_number", false),
            ("match_number", false),
            ("", false),
        ] {
            assert_eq!(is_reserved_internal_column_name(name), reserved, "{name}");
        }
    }
}