Skip to main content

datafusion_match_recognize/
lib.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 `MATCH_RECOGNIZE` for Apache DataFusion.
17//!
18//! This is the main application crate. [`new_match_recognize_context`] installs
19//! the functions, planners, and optimizer rules required by the extension and
20//! returns a new DataFusion context. [`MatchRecognizeConfig`] controls compile
21//! and runtime limits when an application needs values other than the defaults.
22//!
23//! # Install the extension
24//!
25//! Applications must depend on the matching official Apache DataFusion `55`
26//! release line from crates.io. See [Add the extension to an application] for
27//! the dependency declaration.
28//!
29//! ```rust,no_run
30//! use datafusion::execution::SessionStateBuilder;
31//! use datafusion_match_recognize::new_match_recognize_context;
32//!
33//! # fn build() -> datafusion::error::Result<()> {
34//! let builder = SessionStateBuilder::new().with_default_features();
35//! let ctx = new_match_recognize_context(builder)?;
36//! # let _ = ctx;
37//! # Ok(())
38//! # }
39//! ```
40//!
41//! Register tables and run queries on the returned context. The installer
42//! preserves the builder's configuration and extensions, replaces its query
43//! planner, and appends the required optimizer rules. See
44//! [`new_match_recognize_context`] for the registration order, replaced function
45//! registrations, duplicate-installation behavior, and possible errors. An
46//! already-created `SessionContext` is not modified in place.
47//!
48//! # Cargo features
49//!
50//! - `sql` (default) installs the adapter that turns `MATCH_RECOGNIZE` SQL into
51//!   a DataFusion logical plan. Without it, applications build plans directly
52//!   through [`planning`] or supply them through another integration.
53//! - `substrait` exposes this package's Substrait import and export helpers in
54//!   the `substrait` module.
55//!
56//! The [`advanced`] module exposes unstable component-by-component registration
57//! for hosts that cannot use the normal installer. Applications that build
58//! patterns directly in Rust use [`planning`] rather than those hooks.
59//!
60//! # Guides and reference
61//!
62//! - [Run the example and its assertions]
63//! - [Add the extension to an application]
64//! - [Build a row pattern step by step]
65//! - [Check SQL support]
66//! - [Review configuration and feature combinations]
67//! - [Evaluate a production workload]
68//!
69//! These web links follow the current `main` branch. When using a pinned
70//! revision, read the corresponding files and Rustdoc from that checkout.
71//!
72//! [Run the example and its assertions]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/docs/getting_started.md
73//! [Add the extension to an application]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/docs/integration.md
74//! [Build a row pattern step by step]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/docs/sql/README.md
75//! [Check SQL support]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/docs/sql/reference.md
76//! [Review configuration and feature combinations]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/match-recognize/README.md
77//! [Evaluate a production workload]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/docs/production_evaluation.md
78
79use std::sync::Arc;
80
81use datafusion::execution::{SessionState, SessionStateBuilder};
82use datafusion::prelude::SessionContext;
83
84/// Session settings used by physical planning and execution.
85pub mod config;
86pub mod planning;
87#[cfg(feature = "substrait")]
88pub mod substrait;
89
90pub(crate) mod compat;
91pub(crate) mod core;
92pub(crate) mod execution;
93pub(crate) mod functions;
94pub(crate) mod nfa;
95pub(crate) mod nfa_executor;
96mod optimizer;
97#[cfg(feature = "sql")]
98pub(crate) mod sql;
99
100pub use config::MatchRecognizeConfig;
101
102use execution::physical::{
103    MatchRecognizeQueryPlanner,
104    match_recognize_extension_planner as new_match_recognize_extension_planner,
105};
106use optimizer::{MatchRecognizePhysicalOptimizer, MatchRecognizeProjectionPushdown};
107#[cfg(feature = "sql")]
108use sql::MatchRecognizePlanner;
109
110/// Build a DataFusion context with `MATCH_RECOGNIZE` support for the enabled
111/// Cargo features.
112///
113/// This function consumes `builder` and performs these operations in order:
114///
115/// 1. Replace any configured query planner with the `MATCH_RECOGNIZE` query
116///    planner and append the extension's physical optimizer rule.
117/// 2. Build a [`SessionState`].
118/// 3. Register the extension's scalar, window, and aggregate functions. An
119///    existing function in the same registry with the same name is replaced.
120/// 4. With the `sql` feature, prepend the `MATCH_RECOGNIZE` relation planner,
121///    giving it priority over relation planners already on the state.
122/// 5. Construct a new [`SessionContext`] and append the extension's logical
123///    optimizer rule.
124///
125/// The installer preserves other builder fields. In particular, the supplied
126/// session configuration and its extensions are preserved. It does not call
127/// `with_default_features`. Applications that
128/// want DataFusion's ordinary defaults must add them to the builder before this
129/// call. The installer does not modify an existing [`SessionContext`] in place.
130///
131/// Function registration uses the following names:
132///
133/// - scalar: `match_number`, `match_sequence_number`, `classifier`, and
134///   `excluded`;
135/// - window: `first`, `last`, `prev`, and `next`;
136/// - aggregate: `__mr_first_agg`, `__mr_last_agg`, `__mr_prev_agg`, and
137///   `__mr_next_agg`. Zero-offset match-level `FIRST` and `LAST` continue to
138///   use DataFusion's native `first_value` and `last_value` implementations.
139///
140/// Use the installer once when constructing a session state. Rebuilding from a
141/// state that already contains this installation and applying it again replaces
142/// the named functions, but adds another logical and physical optimizer rule
143/// and, with the `sql` feature, another SQL relation planner.
144///
145/// Applications with a custom query planner can add
146/// [`advanced::physical_extension_planner`] to it and append
147/// [`advanced::physical_optimizer_rule`] to their builder. Complete registration
148/// with [`advanced::register_state`] and [`advanced::register_optimizer_rules`].
149///
150/// Default runtime options work without explicitly inserting
151/// [`MatchRecognizeConfig`]. Insert it into `SessionConfig` before building the
152/// state when the application needs SQL `SET match_recognize.*` commands or
153/// custom tuning.
154///
155/// # Errors
156///
157/// Returns an error propagated from registration of a scalar, window, or
158/// aggregate function or, with the `sql` feature, from registration of the SQL
159/// relation planner. No context is returned when registration fails.
160pub fn new_match_recognize_context(
161    builder: SessionStateBuilder,
162) -> datafusion::common::Result<SessionContext> {
163    let mut state = advanced::configure_builder(builder).build();
164    advanced::register_state(&mut state)?;
165    let ctx = SessionContext::new_with_state(state);
166    advanced::register_optimizer_rules(&ctx);
167    Ok(ctx)
168}
169
170/// Unstable hooks for hosts that perform DataFusion registration manually.
171///
172/// Most applications should use [`new_match_recognize_context`] instead. These
173/// functions expose DataFusion registry ordering and are not part of the stable
174/// application API.
175///
176/// A complete manual installation calls [`advanced::configure_builder`] or
177/// configures a custom query planner containing the physical extension planner
178/// and appends [`advanced::physical_optimizer_rule`] to its builder.
179/// It then builds the [`SessionStateBuilder`], calls [`advanced::register_state`]
180/// on that state, constructs a [`SessionContext`], and calls
181/// [`advanced::register_optimizer_rules`] on the context. Call each hook once.
182/// The hooks do not deduplicate optimizer rules or, with the `sql` feature, SQL
183/// relation planners.
184pub mod advanced {
185    use super::*;
186
187    /// Build the standard query planner with the host's physical extension
188    /// planners followed by the `MATCH_RECOGNIZE` extension planner.
189    ///
190    /// This is the simplest composition path for hosts whose planner
191    /// customization consists of DataFusion [`ExtensionPlanner`]s. Install the
192    /// returned planner on a builder, build the state, then call
193    /// [`register_state`] and [`register_optimizer_rules`].
194    ///
195    /// ```rust,no_run
196    /// use std::sync::Arc;
197    ///
198    /// use datafusion::execution::{
199    ///     SessionState, SessionStateBuilder, context::SessionContext,
200    /// };
201    /// use datafusion::physical_planner::ExtensionPlanner;
202    /// use datafusion_match_recognize::advanced;
203    ///
204    /// # fn build(existing_state: SessionState) -> datafusion::error::Result<()> {
205    /// let host_planners: Vec<Arc<dyn ExtensionPlanner + Send + Sync>> = vec![];
206    /// let query_planner = advanced::query_planner_with_extensions(host_planners);
207    /// let builder = SessionStateBuilder::new_from_existing(existing_state)
208    ///     .with_query_planner(query_planner)
209    ///     .with_physical_optimizer_rule(advanced::physical_optimizer_rule());
210    /// let mut state = builder.build();
211    /// advanced::register_state(&mut state)?;
212    /// let ctx = SessionContext::new_with_state(state);
213    /// advanced::register_optimizer_rules(&ctx);
214    /// # let _ = ctx;
215    /// # Ok(())
216    /// # }
217    /// ```
218    ///
219    /// [`ExtensionPlanner`]: datafusion::physical_planner::ExtensionPlanner
220    pub fn query_planner_with_extensions(
221        extension_planners: Vec<
222            Arc<dyn datafusion::physical_planner::ExtensionPlanner + Send + Sync>,
223        >,
224    ) -> Arc<dyn datafusion::execution::context::QueryPlanner + Send + Sync> {
225        Arc::new(MatchRecognizeQueryPlanner::with_extension_planners(
226            extension_planners,
227        ))
228    }
229
230    /// Return the physical extension planner for `MATCH_RECOGNIZE` nodes.
231    ///
232    /// Add this planner to the host query planner's extension-planner chain,
233    /// preserving that custom query planner when building the state. DataFusion
234    /// tries extension planners in order and uses the first one that handles a
235    /// logical extension node. Append [`physical_optimizer_rule`] to the builder.
236    /// After building the state, complete installation with [`register_state`],
237    /// construct a [`SessionContext`], and call [`register_optimizer_rules`].
238    pub fn physical_extension_planner()
239    -> Arc<dyn datafusion::physical_planner::ExtensionPlanner + Send + Sync> {
240        new_match_recognize_extension_planner()
241    }
242
243    /// Return the physical rule that optimizes matcher input and ordered output.
244    ///
245    /// Append it with [`SessionStateBuilder::with_physical_optimizer_rule`] when
246    /// installing a custom query planner. [`configure_builder`] and the normal
247    /// installer already append it. The rule restores eligible cheap constants
248    /// after matcher input sorting and buffers eligible ordered output. Buffering
249    /// skips known fetch paths and existing buffering boundaries, enforces a
250    /// 256 MiB shared aggregate cap (with a per-partition floor) under unlimited
251    /// memory pools, scales to a headroom-bounded aggregate fraction
252    /// (`min(256 MiB, L / 8)`, pausing speculative lookahead at 75% pool
253    /// utilization) under finite pools, and passes through when the per-partition
254    /// share falls below 64 KiB or the pool limit is unknown.
255    pub fn physical_optimizer_rule()
256    -> Arc<dyn datafusion::physical_optimizer::PhysicalOptimizerRule + Send + Sync> {
257        Arc::new(MatchRecognizePhysicalOptimizer)
258    }
259
260    /// Install the builder-time physical planning components.
261    ///
262    /// This replaces any query planner already configured on `builder`,
263    /// installs the DataFusion 55 compatibility wrappers for `EnsureRequirements`
264    /// sort/limit pushdown and leaf-expression projection merging, and appends
265    /// [`physical_optimizer_rule`]. Other builder fields are preserved.
266    /// Calling this hook repeatedly replaces the query planner and appends
267    /// another physical rule each time.
268    pub fn configure_builder(builder: SessionStateBuilder) -> SessionStateBuilder {
269        let builder =
270            compat::leaf_projections::install_leaf_projection_workaround(builder);
271        compat::ensure_requirements::install_ensure_requirements_workaround(builder)
272            .with_query_planner(Arc::new(MatchRecognizeQueryPlanner::new()))
273            .with_physical_optimizer_rule(physical_optimizer_rule())
274    }
275
276    /// Register functions and the optional SQL relation planner on built state.
277    ///
278    /// Scalar functions are registered first, followed by window functions and
279    /// aggregate functions. Existing entries with the same names are replaced.
280    /// With the `sql` feature, the relation planner is registered last and is
281    /// given priority over existing relation planners. The exact function names
282    /// and collision behavior are listed by [`crate::new_match_recognize_context`].
283    ///
284    /// Calling this hook repeatedly replaces the named function entries rather
285    /// than adding duplicates. With the `sql` feature, each call prepends
286    /// another relation planner. Relation planners are not deduplicated.
287    ///
288    /// This operation mutates `state` as it proceeds. If registration returns an
289    /// error, registrations completed before that error are not rolled back.
290    ///
291    /// # Errors
292    ///
293    /// Returns an error propagated from registration of a scalar, window, or
294    /// aggregate function or, with the `sql` feature, from registration of the
295    /// SQL relation planner.
296    pub fn register_state(state: &mut SessionState) -> datafusion::common::Result<()> {
297        functions::register_all(state)?;
298
299        #[cfg(feature = "sql")]
300        state.register_relation_planner(Arc::new(MatchRecognizePlanner))?;
301
302        Ok(())
303    }
304
305    /// Append the logical optimizer rule to a context.
306    ///
307    /// Existing logical optimizer rules keep their order and the
308    /// `MATCH_RECOGNIZE` rule is added at the end. Calling this hook repeatedly
309    /// appends duplicate rules.
310    pub fn register_optimizer_rules(ctx: &SessionContext) {
311        ctx.add_optimizer_rule(Arc::new(MatchRecognizeProjectionPushdown::new()));
312    }
313}
314
315/// Workspace-only hooks for Criterion benchmarks and developer tools.
316#[cfg(feature = "internal-bench")]
317#[doc(hidden)]
318pub mod internal_bench {
319    pub use crate::nfa::CompiledAutomaton;
320    pub use crate::planning::logical::MatchRecognize;
321    pub use crate::planning::physical_derivation::compile_match_program;
322    pub use crate::planning::routed_program::MatchCompilerOptions;
323
324    pub fn match_recognize_program(
325        node: &MatchRecognize,
326    ) -> &crate::planning::logical::LogicalMatchProgram {
327        node.program()
328    }
329}
330
331/// Workspace-only hooks for integration tests, reference oracles, and snapshot tooling.
332#[cfg(feature = "test-support")]
333#[doc(hidden)]
334pub mod test_support {
335    pub use crate::core::test_support::{EndPolicy, all_matches_with_policy};
336    pub use crate::nfa::PatternOptimizer;
337    pub use crate::planning::logical::{LogicalMatchProgram, MatchRecognize};
338    pub use crate::planning::physical_derivation::compile_match_program;
339    pub use crate::planning::predicate::{
340        PredicateNode, VmBinaryOp, VmLiteral, VmSourceRef,
341    };
342    pub use crate::planning::routed_program::{MatchCompilerOptions, RoutedPredicate};
343    #[cfg(feature = "sql")]
344    pub use crate::sql::adapter::{
345        build_parsed_match_clause, render_parsed_match_clause,
346    };
347
348    pub fn match_recognize_program(node: &MatchRecognize) -> &LogicalMatchProgram {
349        node.program()
350    }
351}
352
353#[cfg(all(test, feature = "substrait"))]
354mod substrait_reexport_tests {
355    use std::collections::BTreeSet;
356
357    use crate::substrait::{
358        DATAFUSION_EXCLUDED_FEATURE, DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE,
359        DATAFUSION_SEMANTIC_ONE_ROW_FEATURE, DATAFUSION_WINDOW_MODIFIERS_FEATURE,
360        MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE, MATCH_RECOGNIZE_EXTENSION_FEATURE,
361        MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE,
362        MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE,
363        MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE,
364        MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE,
365    };
366
367    #[test]
368    fn facade_reexports_all_substrait_feature_constants() {
369        let features = [
370            MATCH_RECOGNIZE_EXTENSION_FEATURE,
371            MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE,
372            MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE,
373            MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE,
374            MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE,
375            MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE,
376            DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE,
377            DATAFUSION_EXCLUDED_FEATURE,
378            DATAFUSION_WINDOW_MODIFIERS_FEATURE,
379            DATAFUSION_SEMANTIC_ONE_ROW_FEATURE,
380        ];
381        assert!(features.iter().all(|feature| !feature.is_empty()));
382        assert_eq!(features.into_iter().collect::<BTreeSet<_>>().len(), 10);
383    }
384}