Skip to main content

datafusion_match_recognize/core/
metadata.rs

1// Licensed under the Apache License, Version 2.0 (the
2// "License"); you may not use this file except in compliance
3// with the License.  You may obtain a copy of the License at
4//
5//   http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing,
8// software distributed under the License is distributed on an
9// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
10// KIND, either express or implied.  See the License for the
11// specific language governing permissions and limitations
12// under the License.
13//
14// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.
15
16//! Shared constants and helpers for MATCH_RECOGNIZE virtual columns.
17//!
18//! These are used across source planning, logical planning, and physical
19//! execution, including generated columns for managed DEFINE state and
20//! partial static extraction.
21
22use std::fmt::{self, Display, Formatter};
23use std::str::FromStr;
24use std::sync::Arc;
25
26use datafusion::arrow::datatypes::{DataType, Field};
27
28/// Prefix reserved for MATCH_RECOGNIZE internal columns.
29pub const MR_INTERNAL_PREFIX: &str = "__mr_";
30// Prefix for DEFINE-derived boolean symbol columns
31const MR_SYMBOL_PREFIX: &str = "__mr_symbol_";
32// Prefix for classifier bitset columns
33const MR_CLASSIFIER_BITS_PREFIX: &str = "__mr_classifier_";
34// Prefix for managed aggregate columns
35const MR_MANAGED_AGGREGATE_PREFIX: &str = "__mr_managed_agg_";
36/// Prefix for generated static-extraction columns.
37pub const MR_STATIC_EXTRACTION_PREFIX: &str = "__mr_static_";
38
39/// Lower bound used to distinguish matched rows from `PREV` buffer rows.
40pub const MIN_VALID_MATCH_SEQUENCE_NUMBER: i64 = 0;
41/// Upper bound used to distinguish matched rows from `NEXT` buffer rows.
42pub const MAX_VALID_MATCH_SEQUENCE_NUMBER: i64 = (1i64 << 62) - 1;
43
44#[derive(Debug, Clone)]
45struct MetadataDescriptor {
46    name: &'static str,
47    data_type: DataType,
48    nullable: bool,
49    measure_function_name: &'static str,
50}
51
52/// Metadata columns produced at the matcher boundary.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
54pub enum MatchMetadataColumn {
55    /// Pattern symbol assigned to the output row.
56    Classifier,
57    /// One-based selected-match number within a partition.
58    MatchNumber,
59    /// One-based row position within a match.
60    MatchSequenceNumber,
61    /// Whether the row was consumed inside an exclusion block.
62    Excluded,
63    /// Internal candidate-path identity used for match-aware reconciliation.
64    PathId,
65}
66
67impl MatchMetadataColumn {
68    fn descriptor(self) -> MetadataDescriptor {
69        match self {
70            Self::Classifier => MetadataDescriptor {
71                name: "__mr_classifier",
72                data_type: DataType::Utf8,
73                nullable: true,
74                measure_function_name: "classifier",
75            },
76            Self::MatchNumber => MetadataDescriptor {
77                name: "__mr_match_number",
78                data_type: DataType::Int64,
79                nullable: true,
80                measure_function_name: "match_number",
81            },
82            Self::MatchSequenceNumber => MetadataDescriptor {
83                name: "__mr_match_sequence_number",
84                data_type: DataType::Int64,
85                nullable: true,
86                measure_function_name: "match_sequence_number",
87            },
88            Self::Excluded => MetadataDescriptor {
89                name: "__mr_excluded",
90                data_type: DataType::Boolean,
91                nullable: true,
92                measure_function_name: "excluded",
93            },
94            Self::PathId => MetadataDescriptor {
95                name: "__mr_path_id",
96                data_type: DataType::Int64,
97                nullable: false,
98                measure_function_name: "path_id",
99            },
100        }
101    }
102
103    /// Return the Arrow data type of this metadata column.
104    pub fn data_type(&self) -> DataType {
105        self.descriptor().data_type
106    }
107
108    /// Return whether this metadata column is nullable.
109    pub fn is_nullable(&self) -> bool {
110        self.descriptor().nullable
111    }
112
113    /// Return the associated function name without parentheses.
114    ///
115    /// [`Self::PathId`] returns `path_id`, an internal name, not a public SQL function.
116    pub fn measure_function_name(&self) -> &'static str {
117        self.descriptor().measure_function_name
118    }
119
120    /// Return all metadata columns in their defined output order.
121    pub const fn all() -> [Self; 5] {
122        [
123            Self::Classifier,
124            Self::MatchNumber,
125            Self::MatchSequenceNumber,
126            Self::Excluded,
127            Self::PathId,
128        ]
129    }
130
131    /// Metadata columns that may appear in a final public output specification.
132    ///
133    /// Internal-only metadata such as [`Self::PathId`] is deliberately excluded.
134    pub const fn public_output() -> [Self; 4] {
135        [
136            Self::Classifier,
137            Self::MatchNumber,
138            Self::MatchSequenceNumber,
139            Self::Excluded,
140        ]
141    }
142
143    /// Return the unqualified Arrow field for this metadata column.
144    pub fn arrow_field(self) -> Arc<Field> {
145        let descriptor = self.descriptor();
146        Arc::new(Field::new(
147            descriptor.name,
148            descriptor.data_type,
149            descriptor.nullable,
150        ))
151    }
152}
153
154impl AsRef<str> for MatchMetadataColumn {
155    fn as_ref(&self) -> &str {
156        self.descriptor().name
157    }
158}
159
160impl FromStr for MatchMetadataColumn {
161    type Err = ();
162    fn from_str(s: &str) -> Result<Self, Self::Err> {
163        Self::all()
164            .into_iter()
165            .find(|column| column.as_ref() == s)
166            .ok_or(())
167    }
168}
169
170impl Display for MatchMetadataColumn {
171    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
172        f.write_str(self.as_ref())
173    }
174}
175
176/// Build the generated Boolean predicate-column name for `symbol`.
177pub fn symbol_col_name(symbol: &str) -> String {
178    format!("{MR_SYMBOL_PREFIX}{}", symbol.to_ascii_lowercase())
179}
180
181/// Check if a column name is reserved for MATCH_RECOGNIZE internal use.
182pub fn is_reserved_internal_column_name(name: &str) -> bool {
183    name.get(..MR_INTERNAL_PREFIX.len())
184        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(MR_INTERNAL_PREFIX))
185}
186
187/// Build the generated classifier-bitset column name for `symbol`.
188pub fn classifier_bits_col_name(symbol: &str) -> String {
189    format!("{MR_CLASSIFIER_BITS_PREFIX}{}", symbol.to_ascii_lowercase())
190}
191
192fn classifier_bits_field(symbol: &str) -> Arc<Field> {
193    Arc::new(Field::new(
194        classifier_bits_col_name(symbol),
195        DataType::Boolean,
196        true,
197    ))
198}
199
200/// Arrow fields for classifier bitset columns `__mr_classifier_<SYM>`.
201///
202/// These are nullable because unmatched and buffered rows can carry NULL
203/// classifier bits.
204pub fn classifier_bits_arrow_fields(symbols: &[String]) -> Vec<Arc<Field>> {
205    symbols
206        .iter()
207        .map(|symbol| classifier_bits_field(symbol))
208        .collect()
209}
210
211/// Build the generated column name for an AND-side static predicate.
212pub fn static_predicate_and_col_name(id: usize) -> String {
213    format!("{MR_STATIC_EXTRACTION_PREFIX}predicate_and_{id}")
214}
215
216/// Build the generated column name for an OR-side static predicate.
217pub fn static_predicate_or_col_name(id: usize) -> String {
218    format!("{MR_STATIC_EXTRACTION_PREFIX}predicate_or_{id}")
219}
220
221/// Build the generated column name for an extracted static scalar.
222pub fn static_scalar_col_name(id: usize) -> String {
223    format!("{MR_STATIC_EXTRACTION_PREFIX}scalar_{id}")
224}
225
226/// Build `__mr_managed_agg_<id>` column name.
227pub fn managed_aggregate_col_name(id: usize) -> String {
228    format!("{MR_MANAGED_AGGREGATE_PREFIX}{id}")
229}
230
231/// The Boolean position in which a static predicate can short-circuit evaluation.
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
233pub enum StaticPredicateKind {
234    /// A false predicate short-circuits the AND condition and rejects the symbol.
235    BooleanAnd,
236    /// A true predicate short-circuits the OR condition and accepts the symbol.
237    BooleanOr,
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn public_output_metadata_excludes_internal_path_id() {
246        assert!(
247            !MatchMetadataColumn::public_output().contains(&MatchMetadataColumn::PathId)
248        );
249        assert!(MatchMetadataColumn::all().contains(&MatchMetadataColumn::PathId));
250    }
251
252    #[test]
253    fn internal_column_reservation_checks_case_and_prefix_boundaries() {
254        for (name, reserved) in [
255            ("__mr_match_number", true),
256            ("__MR_classifier_a", true),
257            ("__Mr_symbol_a", true),
258            ("__mr", false),
259            ("user___mr_match_number", false),
260            ("match_number", false),
261            ("", false),
262        ] {
263            assert_eq!(is_reserved_internal_column_name(name), reserved, "{name}");
264        }
265    }
266}