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.

//! Generic MATCH_RECOGNIZE navigation aggregate UDF implementation.

use std::hash::Hash;
use std::sync::Arc;

use datafusion::arrow::datatypes::{DataType, Field, FieldRef};
use datafusion::common::Result;
use datafusion::logical_expr::function::{AccumulatorArgs, StateFieldsArgs};
use datafusion::logical_expr::utils::format_state_name;
use datafusion::logical_expr::{Accumulator, AggregateUDFImpl, Signature, Volatility};

use crate::functions::navigation_common::{
    NavigationKind, coerce_shift_navigation_types, navigation_return_field,
    nullable_navigation_data_type,
};

use super::accumulator::NavigationAccumulator;
use super::groups_accumulator::NavigationGroupsAccumulator;
use super::helpers::{
    EDGE_OFFSET_UDAF_ARG_COUNT, NavigationOrdering, base_state_fields,
    parse_navigation_args, state_history_data_type, validate_navigation_arg_count,
};
use datafusion::logical_expr::groups_accumulator::GroupsAccumulator;

/// Package-owned MATCH_RECOGNIZE navigation aggregate function.
///
/// Supports both:
/// - Logical-offset `FIRST`/`LAST` (`__mr_first_agg`, `__mr_last_agg`) with 2
///   arguments `(expr, logical_offset)` and SQL `FILTER` row selection.
/// - `PREV`/`NEXT` (`__mr_prev_agg`, `__mr_next_agg`) with 5 arguments
///   `(expr, offset, default, is_matched, classifier_mask)` or 7 arguments
///   `(..., logical_is_first, logical_offset)` for compound `PREV`/`NEXT` over
///   `FIRST`/`LAST`.
#[derive(Debug)]
pub struct NavigationAgg {
    signature: Signature,
    kind: NavigationKind,
}

impl NavigationAgg {
    pub(crate) fn new(kind: NavigationKind) -> Self {
        let signature = if kind.is_edge() {
            Signature::any(EDGE_OFFSET_UDAF_ARG_COUNT, Volatility::Immutable)
        } else {
            Signature::user_defined(Volatility::Immutable)
        };
        Self { signature, kind }
    }
}

impl PartialEq for NavigationAgg {
    fn eq(&self, other: &Self) -> bool {
        self.kind == other.kind
    }
}

impl Eq for NavigationAgg {}

impl Hash for NavigationAgg {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.kind.hash(state);
    }
}

impl AggregateUDFImpl for NavigationAgg {
    fn name(&self) -> &str {
        self.kind.aggregate_name()
    }

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

    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
        validate_navigation_arg_count(self.kind, arg_types.len())?;
        Ok(if self.kind.is_shift() {
            coerce_shift_navigation_types(arg_types)
        } else {
            arg_types.to_vec()
        })
    }

    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
        validate_navigation_arg_count(self.kind, arg_types.len())?;
        let base = if self.kind.is_shift()
            && arg_types[0].is_null()
            && !arg_types[2].is_null()
        {
            &arg_types[2]
        } else {
            &arg_types[0]
        };
        Ok(nullable_navigation_data_type(base))
    }

    fn return_field(&self, arg_fields: &[FieldRef]) -> Result<FieldRef> {
        validate_navigation_arg_count(self.kind, arg_fields.len())?;
        Ok(navigation_return_field(self.kind, arg_fields, self.name()))
    }

    fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
        let args = parse_navigation_args(self.kind, acc_args.exprs)?;
        let ordering =
            NavigationOrdering::from_sort_exprs(acc_args.order_bys, acc_args.schema)?;

        Ok(Box::new(NavigationAccumulator::try_new_configured(
            self.kind,
            acc_args.return_field.data_type().clone(),
            args.anchor,
            args.offset,
            args.default_value,
            args.fixed_arg_count,
            ordering,
        )?))
    }

    fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
        let data_type = state_history_data_type(args.return_field.data_type());
        let mut fields =
            Vec::with_capacity(base_state_fields(self.kind) + args.ordering_fields.len());
        // All values in sequence order (stored as List for state serialization)
        fields.push(Arc::new(Field::new(
            format_state_name(args.name, "values"),
            DataType::List(Arc::new(Field::new("item", data_type, true))),
            true,
        )));
        if self.kind.is_shift() {
            // Whether each row can anchor navigation
            fields.push(Arc::new(Field::new(
                format_state_name(args.name, "symbol_matched"),
                DataType::List(Arc::new(Field::new("item", DataType::Boolean, true))),
                true,
            )));
        }
        for (idx, field) in args.ordering_fields.iter().enumerate() {
            fields.push(Arc::new(Field::new(
                format_state_name(args.name, &format!("ordering_{idx}")),
                DataType::List(Arc::new(Field::new(
                    "item",
                    state_history_data_type(field.data_type()),
                    true,
                ))),
                true,
            )));
        }
        Ok(fields)
    }

    fn groups_accumulator_supported(&self, _args: AccumulatorArgs) -> bool {
        true
    }

    fn create_groups_accumulator(
        &self,
        args: AccumulatorArgs,
    ) -> Result<Box<dyn GroupsAccumulator>> {
        let navigation_args = parse_navigation_args(self.kind, args.exprs)?;
        let ordering = NavigationOrdering::from_sort_exprs(args.order_bys, args.schema)?;

        Ok(Box::new(NavigationGroupsAccumulator::try_new_configured(
            self.kind,
            args.return_field.data_type().clone(),
            navigation_args.anchor,
            navigation_args.offset,
            navigation_args.default_value,
            navigation_args.fixed_arg_count,
            ordering,
        )?))
    }
}