Skip to main content

datafusion_match_recognize/planning/
mod.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//! SQL-independent semantic planning for `MATCH_RECOGNIZE`.
17//!
18//! Source adapters supply a [`BoundMatchSpec`] with bound input expressions,
19//! column references, and Arrow types. Structured scalar and aggregate calls
20//! retain their identities; lowering resolves registry calls through
21//! [`MatchRecognizePlanningContext`]. Planning validates and canonicalizes the
22//! request, then builds the semantic logical node and final output. It retains
23//! the canonical source so exporters can reproduce the request. Static DEFINEs
24//! can become checked Boolean input columns. Planning also prepares candidate
25//! predicates, aggregate state, and Deferred history inputs from the bound source.
26
27pub use crate::core::{
28    AfterMatchSkip, EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeDefinition,
29    MatchRecognizeMeasure, MatchRecognizeNamedExpression, MatchRecognizeNullOrdering,
30    MatchRecognizeOutputContract, MatchRecognizeSortDirection, MatchRecognizeSortExpr,
31    MatchRecognizeSpec, MatchRecognizeSpecError, MatchRecognizeSpecResult,
32    NormalizedPattern, Pattern, PatternStructuralInfo, RepetitionPreference,
33    RepetitionQuantifier, RowsPerMatch, Symbol,
34};
35use datafusion::common::config::ConfigOptions;
36use datafusion::logical_expr::{AggregateUDF, ScalarUDF};
37pub(crate) use deferred_program::{
38    DeferredHistorySlotOwner, DeferredOperationSpec, DeferredProgramSpec,
39};
40#[cfg(feature = "substrait")]
41pub(crate) use define::preparation::static_define_predicate_expr;
42pub use define::{
43    DefineRequirement, MatchRecognizeRequirements, analyze_match_recognize_requirements,
44};
45pub(crate) use expressions::NamedExpr;
46pub(crate) use extract::{
47    ManagedAggregate, ManagedAggregateBackend, ManagedAggregateBackendSet,
48};
49pub(crate) use hybrid_guard::LogicalHybridGuardExpr;
50#[cfg(test)]
51pub(crate) use logical::ExecutableMatchProgramInput;
52pub use logical::MatchRecognize;
53pub(crate) use physical_derivation::compile_match_program;
54pub(crate) use routed_program::{
55    AccumulatorInputMode, MatchCompilerOptions, RoutedAggregate, RoutedEvaluator,
56    RoutedHistoryGuard, RoutedMatchProgram, RoutedPredicate, RoutedSymbol,
57};
58#[allow(deprecated)]
59pub use source::validate_pattern_qualifiers;
60pub use source::{
61    BoundMatchAggregateCall, BoundMatchExpr, BoundMatchExprSort, BoundMatchNavigation,
62    BoundMatchSpec, CanonicalBoundMatchSpec, MatchAggregateCall, MatchExpr,
63    MatchExprSort, MatchMetadataFunction, MatchNavigation, MatchPatternFieldRef,
64    MatchPredicateKind, MatchRecognizePlanningCapabilities, MatchUnaryOperator,
65};
66#[cfg(feature = "substrait")]
67pub(crate) use source_lowering::plan_match_recognize_native_one_row_node_from_source_with_capabilities;
68pub use source_lowering::{
69    plan_match_recognize_from_source, plan_match_recognize_from_source_with_capabilities,
70    plan_match_recognize_node_from_source_with_capabilities,
71};
72use std::sync::Arc;
73pub(crate) use symbol_relationships::SymbolRelationships;
74pub(crate) use type_validation::can_have_nulls_outside_bitmap;
75pub(crate) use vm_assembly::VmAssemblyDowngrade;
76
77/// Semantic logical-plan nodes and programs shared with physical planning and
78/// source exporters.
79pub(crate) mod logical;
80pub(crate) mod predicate;
81
82mod bound_expr_lowering;
83mod deferred_program;
84mod define;
85mod expr_safety;
86mod expressions;
87pub(crate) mod extract;
88mod hybrid_guard;
89mod measures;
90mod navigation_names;
91mod phases;
92pub(crate) mod physical_derivation;
93pub(crate) mod routed_program;
94mod semantic_metadata;
95mod source;
96mod source_lowering;
97mod static_extraction;
98pub(crate) mod symbol_relationships;
99mod type_validation;
100mod vm_assembly;
101
102/// Whether a row-local input expression can move across an ordered matcher boundary
103/// without changing errors or the number of volatile calls.
104pub(crate) fn can_reorder_input_scalar(
105    expr: &datafusion::logical_expr::Expr,
106    schema: &datafusion::common::DFSchema,
107) -> bool {
108    expr_safety::can_discard_scalar(expr, Some(schema))
109}
110
111/// Internal source and wire identity for the SQL SUBSTRING operator.
112pub(crate) const BUILTIN_SUBSTRING_NAME: &str = "__mr_builtin_substr";
113
114/// Planning-only switches read from the registered session extension.
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
116pub struct MatchRecognizePlanningOptions {
117    /// Route match-aware aggregates away from local managed state.
118    pub disable_managed_aggregates: bool,
119    /// Keep complete `DEFINE` expressions instead of extracting static columns.
120    pub disable_static_extraction: bool,
121}
122
123impl MatchRecognizePlanningOptions {
124    pub(crate) fn from_config_options(options: &ConfigOptions) -> Self {
125        let Some(config) = options
126            .extensions
127            .get::<crate::config::MatchRecognizeConfig>()
128        else {
129            return Self::default();
130        };
131        Self {
132            disable_managed_aggregates: config.diagnostics.disable_managed_aggregates,
133            disable_static_extraction: config.diagnostics.disable_static_extraction,
134        }
135    }
136}
137
138/// Planning context used by SQL-free source lowering.
139///
140/// Source lowering needs DataFusion configuration and function resolution, but
141/// not SQL parser or planner state. Keeping this local trait avoids depending on
142/// DataFusion's SQL-only `RelationPlannerContext`.
143pub trait MatchRecognizePlanningContext {
144    /// Return the DataFusion options used while binding and lowering the source.
145    fn options(&self) -> &ConfigOptions;
146
147    /// Read this package's planning switches from [`Self::options`].
148    fn match_recognize_options(&self) -> MatchRecognizePlanningOptions {
149        MatchRecognizePlanningOptions::from_config_options(self.options())
150    }
151
152    /// Resolve a scalar function by name.
153    ///
154    /// The default context exposes no named scalar functions. Importers may
155    /// still supply already-resolved DataFusion expressions through
156    /// [`crate::planning::MatchExpr::InputExpr`].
157    fn scalar_udf(&self, _name: &str) -> Option<Arc<ScalarUDF>> {
158        None
159    }
160
161    /// Resolve an aggregate function by name.
162    ///
163    /// The default implementation recognizes DataFusion built-in aggregates.
164    fn aggregate_udf(&self, name: &str) -> Option<Arc<AggregateUDF>> {
165        bound_expr_lowering::builtin_aggregate_udf(name)
166    }
167}
168
169/// Planning context backed by owned DataFusion configuration and the package's
170/// built-in aggregate resolver.
171#[derive(Debug, Clone, Default)]
172pub struct DefaultMatchRecognizePlanningContext {
173    options: ConfigOptions,
174}
175
176impl DefaultMatchRecognizePlanningContext {
177    /// Create a context with default DataFusion options.
178    pub fn new() -> Self {
179        Self::default()
180    }
181
182    /// Create a context with the supplied DataFusion options.
183    pub fn with_options(options: ConfigOptions) -> Self {
184        Self { options }
185    }
186}
187
188impl MatchRecognizePlanningContext for DefaultMatchRecognizePlanningContext {
189    fn options(&self) -> &ConfigOptions {
190        &self.options
191    }
192}
193
194impl MatchRecognizePlanningContext for ConfigOptions {
195    fn options(&self) -> &ConfigOptions {
196        self
197    }
198}
199
200#[cfg(test)]
201mod options_tests {
202    use super::*;
203    #[test]
204    fn reads_planning_overrides_from_registered_options() {
205        let mut options = ConfigOptions::default();
206        assert_eq!(
207            MatchRecognizePlanningOptions::from_config_options(&options),
208            MatchRecognizePlanningOptions::default()
209        );
210        options
211            .extensions
212            .insert(crate::config::MatchRecognizeConfig::default());
213
214        assert_eq!(
215            MatchRecognizePlanningOptions::from_config_options(&options),
216            MatchRecognizePlanningOptions::default()
217        );
218        options
219            .set(
220                "match_recognize.diagnostics.disable_managed_aggregates",
221                "true",
222            )
223            .unwrap();
224        options
225            .set(
226                "match_recognize.diagnostics.disable_static_extraction",
227                "true",
228            )
229            .unwrap();
230
231        assert_eq!(
232            MatchRecognizePlanningOptions::from_config_options(&options),
233            MatchRecognizePlanningOptions {
234                disable_managed_aggregates: true,
235                disable_static_extraction: true,
236            }
237        );
238    }
239}