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.

//! Resolves parsed SQL expressions against the input schema, then calls the
//! SQL-independent planner.

use std::cell::RefCell;

use super::syntax::strip_outer_parentheses;
use super::*;

pub(super) fn plan_bound_match(
    context: &mut dyn RelationPlannerContext,
    input: LogicalPlan,
    bound_spec: BoundMatchSpec,
) -> Result<LogicalPlan> {
    let mut planning_context = SqlPlanningContext {
        provider: context.context_provider(),
    };
    plan_match_recognize_from_source(&mut planning_context, input, bound_spec)
}

pub(super) fn bind_parsed_match_clause(
    context: &mut dyn RelationPlannerContext,
    schema: &DFSchema,
    spec: ParsedMatchClause,
) -> Result<BoundMatchSpec> {
    Ok(BoundMatchSpec {
        partition_by: spec
            .partition_by
            .into_iter()
            .map(|expr| bind_parsed_match_expr(context, schema, expr))
            .collect::<Result<Vec<_>>>()?,
        order_by: spec
            .order_by
            .into_iter()
            .map(|sort| {
                Ok(MatchRecognizeSortExpr {
                    expr: bind_parsed_match_expr(context, schema, sort.expr)?,
                    direction: sort.direction,
                    null_ordering: sort.null_ordering,
                })
            })
            .collect::<Result<Vec<_>>>()?,
        source_rows_per_match: spec.source_rows_per_match,
        after_match_skip: spec.after_match_skip,
        pattern: spec.pattern,
        symbols: spec.symbols,
        definitions: spec
            .definitions
            .into_iter()
            .map(|definition| {
                Ok(MatchRecognizeDefinition {
                    symbol: definition.symbol,
                    predicate: bind_parsed_match_expr(
                        context,
                        schema,
                        definition.predicate,
                    )?,
                })
            })
            .collect::<Result<Vec<_>>>()?,
        measures: spec
            .measures
            .into_iter()
            .map(|measure| {
                Ok(MatchRecognizeMeasure {
                    name: measure.name,
                    expression: bind_parsed_match_expr(
                        context,
                        schema,
                        measure.expression,
                    )?,
                })
            })
            .collect::<Result<Vec<_>>>()?,
        output: match spec.output {
            MatchRecognizeOutputContract::Derived => {
                MatchRecognizeOutputContract::Derived
            }
            MatchRecognizeOutputContract::ExplicitNamedExpressions(expressions) => {
                MatchRecognizeOutputContract::ExplicitNamedExpressions(
                    expressions
                        .into_iter()
                        .map(|expression| {
                            Ok(MatchRecognizeNamedExpression {
                                name: expression.name,
                                expression: bind_parsed_match_expr(
                                    context,
                                    schema,
                                    expression.expression,
                                )?,
                            })
                        })
                        .collect::<Result<Vec<_>>>()?,
                )
            }
        },
    })
}

pub(super) fn bind_parsed_match_expr(
    context: &mut dyn RelationPlannerContext,
    schema: &DFSchema,
    expr: ParsedMatchExpr,
) -> Result<BoundMatchExpr> {
    // Mapping callbacks run sequentially. Share the planner without holding
    // overlapping mutable borrows for ordinary expressions and cast targets.
    let context = RefCell::new(context);
    let mut bound = expr.try_map_adapter_parts(
        // Outer grouping on ordinary leaves only affects source rendering.
        &mut |expr| {
            context
                .borrow_mut()
                .sql_to_expr(strip_outer_parentheses(*expr), schema)
        },
        &mut |column| Ok(Column::from_name(column)),
        &mut |field| {
            Ok(MatchPatternFieldRef {
                symbol: field.symbol,
                column: Column::from_name(context.borrow().normalize_ident(field.column)),
            })
        },
        &mut |data_type| cast_target(&mut **context.borrow_mut(), schema, data_type),
    )?;
    supply_ordered_set_values(context.borrow().context_provider(), &mut bound);
    Ok(bound)
}

fn supply_ordered_set_values(context: &dyn ContextProvider, expr: &mut BoundMatchExpr) {
    // Walk iteratively to preserve binding's support for deep binary chains.
    let mut pending = vec![expr];
    while let Some(expr) = pending.pop() {
        match expr {
            BoundMatchExpr::Aggregate(call) => {
                // WITHIN GROUP already has the sort key as its first argument.
                // For inline ORDER BY, compare the bound expressions so SQL
                // spelling differences do not introduce a second ordered value.
                if let [sort] = call.order_by.as_slice()
                    && context
                        .get_aggregate_meta(&call.name)
                        .is_some_and(|udaf| udaf.supports_within_group_clause())
                    && call.args.first() != Some(sort.expr.as_ref())
                {
                    call.args.insert(0, (*sort.expr).clone());
                }
                pending.extend(&mut call.args);
                pending.extend(call.filter.as_deref_mut());
                pending.extend(call.order_by.iter_mut().map(|sort| sort.expr.as_mut()));
            }
            BoundMatchExpr::Navigation(nav) => match nav {
                MatchNavigation::First { expr, offset }
                | MatchNavigation::Last { expr, offset } => {
                    pending.push(expr);
                    pending.extend(offset.as_deref_mut());
                }
                MatchNavigation::Prev {
                    expr,
                    offset,
                    default,
                }
                | MatchNavigation::Next {
                    expr,
                    offset,
                    default,
                } => {
                    pending.push(expr);
                    pending.extend(offset.as_deref_mut());
                    pending.extend(default.as_deref_mut());
                }
            },
            BoundMatchExpr::Alias { expr, .. }
            | BoundMatchExpr::Unary { expr, .. }
            | BoundMatchExpr::Predicate { expr, .. }
            | BoundMatchExpr::Cast { expr, .. } => pending.push(expr),
            BoundMatchExpr::ScalarFunction { args, .. } => pending.extend(args),
            BoundMatchExpr::Binary { left, right, .. }
            | BoundMatchExpr::Like {
                expr: left,
                pattern: right,
                ..
            } => {
                pending.push(right);
                pending.push(left);
            }
            BoundMatchExpr::Case {
                expr,
                when_then,
                else_expr,
            } => {
                pending.extend(expr.as_deref_mut());
                for (when, then) in when_then {
                    pending.push(when);
                    pending.push(then);
                }
                pending.extend(else_expr.as_deref_mut());
            }
            BoundMatchExpr::Between {
                expr, low, high, ..
            } => {
                pending.push(expr);
                pending.push(low);
                pending.push(high);
            }
            BoundMatchExpr::InList { expr, list, .. } => {
                pending.push(expr);
                pending.extend(list);
            }
            BoundMatchExpr::InputExpr(_)
            | BoundMatchExpr::InputColumn(_)
            | BoundMatchExpr::PatternField(_)
            | BoundMatchExpr::Metadata(_)
            | BoundMatchExpr::Literal(_) => {}
        }
    }
}

fn cast_target(
    context: &mut dyn RelationPlannerContext,
    schema: &DFSchema,
    data_type: SQLDataType,
) -> Result<ArrowDataType> {
    // Let DataFusion resolve precision, timezone and configured string types.
    // NULL avoids introducing input-dependent timestamp coercion in this probe.
    let expr = context.sql_to_expr(
        SQLExpr::Cast {
            kind: CastKind::Cast,
            expr: Box::new(SQLExpr::Value(Value::Null.into())),
            data_type,
            format: None,
        },
        schema,
    )?;
    match expr {
        datafusion::logical_expr::Expr::Cast(cast) => {
            // DataFusion treats named, non-nullable or metadata-bearing targets
            // as explicit fields. The source model stores only their datatype.
            if !cast.field.name().is_empty()
                || !cast.field.is_nullable()
                || !cast.field.metadata().is_empty()
            {
                return plan_err!(
                    "MATCH_RECOGNIZE CAST does not support explicit target fields"
                );
            }
            Ok(cast.field.data_type().clone())
        }
        _ => internal_err!("DataFusion did not return CAST for a cast target probe"),
    }
}

struct SqlPlanningContext<'a> {
    provider: &'a dyn ContextProvider,
}

impl MatchRecognizePlanningContext for SqlPlanningContext<'_> {
    fn options(&self) -> &ConfigOptions {
        self.provider.options()
    }

    fn scalar_udf(&self, name: &str) -> Option<Arc<ScalarUDF>> {
        self.provider.get_function_meta(name)
    }

    fn aggregate_udf(&self, name: &str) -> Option<Arc<AggregateUDF>> {
        self.provider
            .get_aggregate_meta(name)
            .or_else(|| self.options().aggregate_udf(name))
    }
}