Skip to main content

datafusion_match_recognize/planning/source/
capabilities.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
16use crate::core::MatchRecognizeOutputContract;
17use crate::functions::udf::metadata::{ExcludedUdf, MatchSequenceNumberUdf};
18use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
19use datafusion::common::{Result, plan_err};
20use datafusion::logical_expr::Expr;
21
22use super::{BoundMatchExpr, BoundMatchSpec, MatchMetadataFunction};
23
24/// Optional features an importer can represent without changing their meaning.
25///
26/// The planner rejects a request that uses a disabled feature. This type records
27/// individual planning features, not a named database or file-format profile.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub struct MatchRecognizePlanningCapabilities {
30    match_sequence_number: bool,
31    excluded: bool,
32}
33
34impl Default for MatchRecognizePlanningCapabilities {
35    fn default() -> Self {
36        Self {
37            match_sequence_number: true,
38            excluded: true,
39        }
40    }
41}
42
43impl MatchRecognizePlanningCapabilities {
44    /// Enable or disable each optional feature explicitly.
45    pub const fn restricted(match_sequence_number: bool, excluded: bool) -> Self {
46        Self {
47            match_sequence_number,
48            excluded,
49        }
50    }
51
52    /// Return whether `MATCH_SEQUENCE_NUMBER` expressions are enabled.
53    pub const fn match_sequence_number(self) -> bool {
54        self.match_sequence_number
55    }
56
57    /// Return whether `EXCLUDED` expressions are enabled.
58    pub const fn excluded(self) -> bool {
59        self.excluded
60    }
61
62    /// Return the optional features that `spec` actually uses.
63    pub fn required_for_spec(spec: &BoundMatchSpec) -> Result<Self> {
64        let required = metadata_requirements_for_spec(spec)?;
65        Ok(Self::restricted(
66            required.match_sequence_number,
67            required.excluded,
68        ))
69    }
70
71    /// Check that every optional feature used by `spec` is enabled.
72    ///
73    /// # Errors
74    ///
75    /// Returns a planning error for a `MATCH_SEQUENCE_NUMBER` or `EXCLUDED`
76    /// expression when its corresponding capability is disabled.
77    pub fn validate_for_spec(self, spec: &BoundMatchSpec) -> Result<()> {
78        let required = metadata_requirements_for_spec(spec)?;
79        if required.match_sequence_number && !self.match_sequence_number {
80            return plan_err!(
81                "MATCH_RECOGNIZE source adapter does not enable metadata function MATCH_SEQUENCE_NUMBER"
82            );
83        }
84        if required.excluded && !self.excluded {
85            return plan_err!(
86                "MATCH_RECOGNIZE source adapter does not enable metadata function EXCLUDED"
87            );
88        }
89        Ok(())
90    }
91}
92#[derive(Default)]
93struct MetadataRequirements {
94    match_sequence_number: bool,
95    excluded: bool,
96}
97
98fn metadata_requirements_for_spec(spec: &BoundMatchSpec) -> Result<MetadataRequirements> {
99    let mut required = MetadataRequirements::default();
100    for expr in &spec.partition_by {
101        collect_metadata_requirements(expr, &mut required)?;
102    }
103    for sort in &spec.order_by {
104        collect_metadata_requirements(&sort.expr, &mut required)?;
105    }
106    for definition in &spec.definitions {
107        collect_metadata_requirements(&definition.predicate, &mut required)?;
108    }
109    for measure in &spec.measures {
110        collect_metadata_requirements(&measure.expression, &mut required)?;
111    }
112    match &spec.output {
113        MatchRecognizeOutputContract::Derived => {}
114        MatchRecognizeOutputContract::ExplicitNamedExpressions(expressions) => {
115            for expr in expressions {
116                collect_metadata_requirements(&expr.expression, &mut required)?;
117            }
118        }
119    }
120    Ok(required)
121}
122fn collect_metadata_requirements(
123    expr: &BoundMatchExpr,
124    requirements: &mut MetadataRequirements,
125) -> Result<()> {
126    let mut pending = vec![expr];
127    while let Some(expr) = pending.pop() {
128        match expr {
129            BoundMatchExpr::InputExpr(expr) => {
130                expr.apply(|node| {
131                    if let Expr::ScalarFunction(function) = node {
132                        // Representation capabilities describe built-in metadata,
133                        // never a same-named ordinary scalar implementation.
134                        if function.func.inner().is::<MatchSequenceNumberUdf>() {
135                            requirements.match_sequence_number = true;
136                        } else if function.func.inner().is::<ExcludedUdf>() {
137                            requirements.excluded = true;
138                        }
139                    }
140                    Ok(TreeNodeRecursion::Continue)
141                })?;
142            }
143            BoundMatchExpr::Metadata(metadata) => match metadata {
144                MatchMetadataFunction::MatchSequenceNumber => {
145                    requirements.match_sequence_number = true;
146                }
147                MatchMetadataFunction::Excluded => {
148                    requirements.excluded = true;
149                }
150                MatchMetadataFunction::Classifier
151                | MatchMetadataFunction::MatchNumber => {}
152            },
153            _ => {}
154        }
155        let child_start = pending.len();
156        expr.try_for_each_child(|child| {
157            pending.push(child);
158            Ok(())
159        })?;
160        pending[child_start..].reverse();
161    }
162    Ok(())
163}