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