datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for DataFusion
Documentation
// Licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Scalar UDFs used by `MATCH_RECOGNIZE` to expose metadata columns.
//!
//! Registering these functions lets DataFusion check calls and report useful
//! type errors. Planning replaces valid calls with internal metadata-column
//! references before physical execution.

use datafusion::arrow::datatypes::DataType;
use datafusion::logical_expr::{
    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility,
};
use datafusion_common::{Result, plan_err};

/// Generate an immutable nullary metadata placeholder with a fixed, nullable
/// Arrow return field. Planning replaces valid calls with metadata columns;
/// invocation returns an error if an unresolved placeholder reaches execution.
macro_rules! define_mr_metadata_udf {
    ($struct_name:ident, $fn_name:expr, $return_dt:expr) => {
        #[derive(Debug, PartialEq, Eq, Hash)]
        /// Generated nullary metadata UDF used for type-checking before source normalization.
        ///
        /// Planning replaces calls with internal metadata columns, so this UDF
        /// should never run.
        pub struct $struct_name {
            signature: Signature,
        }

        impl Default for $struct_name {
            fn default() -> Self {
                Self::new()
            }
        }

        impl $struct_name {
            /// Creates an immutable nullary signature for metadata access.
            pub fn new() -> Self {
                Self {
                    signature: Signature::nullary(Volatility::Immutable),
                }
            }
        }

        impl ScalarUDFImpl for $struct_name {
            fn name(&self) -> &str {
                $fn_name
            }
            fn signature(&self) -> &Signature {
                &self.signature
            }

            fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
                Ok($return_dt)
            }

            fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
                if !args.args.is_empty() {
                    return plan_err!(concat!($fn_name, "() does not take arguments"));
                }
                plan_err!(concat!(
                    $fn_name,
                    "() must be normalized to a metadata column during MATCH_RECOGNIZE planning and cannot be executed directly"
                ))
            }
        }
    };
}

define_mr_metadata_udf!(MatchNumberUdf, "match_number", DataType::Int64);
define_mr_metadata_udf!(
    MatchSequenceNumberUdf,
    "match_sequence_number",
    DataType::Int64
);
define_mr_metadata_udf!(ClassifierUdf, "classifier", DataType::Utf8);

define_mr_metadata_udf!(ExcludedUdf, "excluded", DataType::Boolean);

#[cfg(test)]
mod tests {
    use datafusion::logical_expr::ReturnFieldArgs;

    use super::*;

    #[test]
    fn metadata_udfs_match_metadata_column_types_and_nullability() {
        let cases: [(&dyn ScalarUDFImpl, &str, DataType); 4] = [
            (&MatchNumberUdf::new(), "match_number", DataType::Int64),
            (
                &MatchSequenceNumberUdf::new(),
                "match_sequence_number",
                DataType::Int64,
            ),
            (&ClassifierUdf::new(), "classifier", DataType::Utf8),
            (&ExcludedUdf::new(), "excluded", DataType::Boolean),
        ];

        for (udf, expected_name, expected_type) in cases {
            let field = udf
                .return_field_from_args(ReturnFieldArgs {
                    arg_fields: &[],
                    scalar_arguments: &[],
                })
                .unwrap();
            assert_eq!(field.name(), expected_name);
            assert_eq!(field.data_type(), &expected_type);
            assert!(field.is_nullable(), "{expected_name} must be nullable");
            assert_eq!(udf.return_type(&[]).unwrap(), expected_type);
        }
    }
}