datafusion-match-recognize 0.55.0

SQL MATCH_RECOGNIZE row-pattern matching for Apache 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.

//! Backport of DataFusion 56's `CoalesceFunc` runtime evaluation and field
//! metadata propagation for unsimplified `MATCH_RECOGNIZE` expressions on
//! DataFusion 55.3.
//!
//! DataFusion 55.3's `CoalesceFunc::invoke_with_args` unconditionally errors
//! when `COALESCE` reaches physical execution without being simplified to
//! `CASE`, and its `return_field_from_args` drops Arrow field metadata.
//! `MATCH_RECOGNIZE` intentionally plans demanded static `DEFINE` predicates
//! and deferred aggregate inputs without full expression simplification so
//! lazy error timing and volatile semantics stay intact.

use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};

use datafusion::arrow::array::{BooleanArray, new_null_array};
use datafusion::arrow::compute::kernels::zip::zip;
use datafusion::arrow::compute::{and, is_not_null, is_null};
use datafusion::arrow::datatypes::{DataType, Field, FieldRef};

const EXTENSION_TYPE_NAME_KEY: &str = "ARROW:extension:name";
const EXTENSION_TYPE_METADATA_KEY: &str = "ARROW:extension:metadata";
use datafusion::common::metadata::FieldMetadata;
use datafusion::common::tree_node::{Transformed, TreeNode};
use datafusion::common::{Result, exec_err, internal_err, plan_err};
use datafusion::functions::core::coalesce::CoalesceFunc;
use datafusion::logical_expr::binary::try_type_union_resolution;
use datafusion::logical_expr::conditional_expressions::CaseBuilder;
use datafusion::logical_expr::expr::ScalarFunction;
use datafusion::logical_expr::simplify::{ExprSimplifyResult, SimplifyContext};
use datafusion::logical_expr::{
    ColumnarValue, Expr, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl,
    Signature, Volatility,
};

/// Replace DataFusion 55.3's built-in `CoalesceFunc` anywhere in `expr` with
/// [`Branch55CoalesceFunc`] so unsimplified `MATCH_RECOGNIZE` expressions can
/// execute `COALESCE` directly and preserve Arrow field metadata.
pub(crate) fn rewrite_unsimplified_coalesce(expr: Expr) -> Result<Expr> {
    Ok(expr
        .transform_up(|node| match node {
            Expr::ScalarFunction(mut func)
                if func.func.inner().downcast_ref::<CoalesceFunc>().is_some() =>
            {
                func.func = branch55_coalesce_udf();
                Ok(Transformed::yes(Expr::ScalarFunction(func)))
            }
            other => Ok(Transformed::no(other)),
        })?
        .data)
}

fn branch55_coalesce_udf() -> Arc<ScalarUDF> {
    static UDF: OnceLock<Arc<ScalarUDF>> = OnceLock::new();
    Arc::clone(UDF.get_or_init(|| Arc::new(ScalarUDF::from(Branch55CoalesceFunc::new()))))
}

#[derive(Debug, PartialEq, Eq, Hash)]
struct Branch55CoalesceFunc {
    signature: Signature,
}

impl Branch55CoalesceFunc {
    fn new() -> Self {
        Self {
            signature: Signature::user_defined(Volatility::Immutable),
        }
    }
}

/// Backport of DataFusion 56's `datafusion_common::metadata::coerced_fields_metadata`.
fn coerced_fields_metadata<'a>(
    fields: impl IntoIterator<Item = &'a Field>,
) -> Result<FieldMetadata> {
    let mut merged: BTreeMap<String, String> = BTreeMap::new();
    let mut extension: Option<(String, Option<String>)> = None;

    for field in fields {
        if field.data_type().is_null() {
            continue;
        }
        let metadata = FieldMetadata::new_from_field(field);
        if let Some(name) = metadata.inner().get(EXTENSION_TYPE_NAME_KEY) {
            match &extension {
                Some((first_name, _)) if first_name != name => {
                    return plan_err!(
                        "Cannot merge field metadata with differing values of \
                         '{EXTENSION_TYPE_NAME_KEY}': '{first_name}' and '{name}'"
                    );
                }
                Some(_) => {}
                None => {
                    extension = Some((
                        name.clone(),
                        metadata.inner().get(EXTENSION_TYPE_METADATA_KEY).cloned(),
                    ));
                }
            }
        }
        for (key, value) in metadata.inner() {
            if key == EXTENSION_TYPE_NAME_KEY || key == EXTENSION_TYPE_METADATA_KEY {
                continue;
            }
            merged.entry(key.clone()).or_insert_with(|| value.clone());
        }
    }

    if let Some((name, extension_metadata)) = extension {
        merged.insert(EXTENSION_TYPE_NAME_KEY.to_string(), name);
        if let Some(extension_metadata) = extension_metadata {
            merged.insert(EXTENSION_TYPE_METADATA_KEY.to_string(), extension_metadata);
        }
    }

    Ok(FieldMetadata::from(merged))
}

impl ScalarUDFImpl for Branch55CoalesceFunc {
    fn name(&self) -> &str {
        "coalesce"
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
        internal_err!("return_field_from_args should be called instead")
    }

    fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> {
        if args.arg_fields.is_empty() {
            return plan_err!("coalesce must have at least one argument");
        }
        // If any argument in coalesce is non-null, the result is non-null.
        let nullable = args.arg_fields.iter().all(|f| f.is_nullable());
        let return_type = args
            .arg_fields
            .iter()
            .map(|f| f.data_type())
            .find(|d| !d.is_null())
            .unwrap_or_else(|| args.arg_fields[0].data_type())
            .clone();
        let metadata =
            coerced_fields_metadata(args.arg_fields.iter().map(|f| f.as_ref()))?;
        Ok(metadata
            .add_to_field(Field::new(self.name(), return_type, nullable))
            .into())
    }

    fn simplify(
        &self,
        args: Vec<Expr>,
        _info: &SimplifyContext,
    ) -> Result<ExprSimplifyResult> {
        if args.is_empty() {
            return plan_err!("coalesce must have at least one argument");
        }
        if args.len() == 1 {
            return Ok(ExprSimplifyResult::Simplified(
                args.into_iter().next().unwrap(),
            ));
        }

        let (init, last) = args.split_at(args.len() - 1);
        let (prefix, rest) = match init.iter().position(Expr::is_volatile) {
            None => (init, last[0].clone()),
            Some(0) => return Ok(ExprSimplifyResult::Original(args)),
            Some(i) => (
                &init[..i],
                Expr::ScalarFunction(ScalarFunction::new_udf(
                    branch55_coalesce_udf(),
                    args[i..].to_vec(),
                )),
            ),
        };

        let whens = prefix.iter().map(|x| x.clone().is_not_null()).collect();
        Ok(ExprSimplifyResult::Simplified(
            CaseBuilder::new(None, whens, prefix.to_vec(), Some(Box::new(rest))).end()?,
        ))
    }

    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
        let args = args.args;
        if args.is_empty() {
            return exec_err!(
                "coalesce was called with {} arguments. It requires at least 1.",
                args.len()
            );
        }

        let return_type = args
            .iter()
            .map(ColumnarValue::data_type)
            .find(|d| !d.is_null())
            .unwrap_or_else(|| args[0].data_type());
        let mut return_array = args.iter().filter_map(|x| match x {
            ColumnarValue::Array(array) => Some(array.len()),
            _ => None,
        });

        if let Some(size) = return_array.next() {
            let mut current_value = new_null_array(&return_type, size);
            let mut remainder = BooleanArray::from(vec![true; size]);

            for arg in args {
                match arg {
                    ColumnarValue::Array(ref array) => {
                        let to_apply = and(&remainder, &is_not_null(array.as_ref())?)?;
                        current_value = zip(&to_apply, array, &current_value)?;
                        remainder = and(&remainder, &is_null(array)?)?;
                    }
                    ColumnarValue::Scalar(value) => {
                        if value.is_null() {
                            continue;
                        } else {
                            let last_value = value.to_scalar()?;
                            current_value = zip(&remainder, &last_value, &current_value)?;
                            break;
                        }
                    }
                }
                if remainder.true_count() == 0 {
                    break;
                }
            }
            Ok(ColumnarValue::Array(current_value))
        } else {
            let result = args
                .iter()
                .find_map(|x| match x {
                    ColumnarValue::Scalar(s) if !s.is_null() => Some(x.clone()),
                    _ => None,
                })
                .unwrap_or_else(|| args[0].clone());
            Ok(result)
        }
    }

    fn conditional_arguments<'a>(
        &self,
        args: &'a [Expr],
    ) -> Option<(Vec<&'a Expr>, Vec<&'a Expr>)> {
        let eager = vec![&args[0]];
        let lazy = args[1..].iter().collect();
        Some((eager, lazy))
    }

    fn short_circuits(&self) -> bool {
        true
    }

    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
        if arg_types.is_empty() {
            return exec_err!("coalesce must have at least one argument");
        }

        try_type_union_resolution(arg_types)
    }
}