datafusion-match-recognize 0.56.1

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.

//! A single ordered stack for the admitted direct-predicate domain.
//! Unsupported expressions use the existing whole-expression PhysicalExpr route.
use super::aggregate_engine::AggregateEngine;
use super::lane_scan::direct_payload::DirectRow;
use super::row_data::ResolvedRowBindings;
use super::types::{NavigationDatum, NavigationReadView};
use super::vm_scratch::{
    BoundNavigation, BoundStateCell, BoundStateRead, BoundStateSource, CandidateInput,
    i128_from_words, register_average, register_decimal_average,
};
use crate::core::vm::{NavigationValueDomain, RegisterLayout};
pub(crate) use crate::execution::common::coordinates::checked_match_number;
use crate::planning::predicate::{
    DirectPredicatePlan, PredicateNode, VmBinaryOp, VmScalarType, VmSourceRef, VmTriBool,
    VmType, VmUnaryOp,
};
use datafusion::arrow::array::*;
use datafusion::arrow::datatypes::{DataType, Schema, TimeUnit};
use datafusion::common::ScalarValue;
mod binding;
mod eval;
mod inputs;
mod values;
pub(crate) use binding::*;
pub(crate) use eval::evaluate_bound_predicate;
use eval::{Op, Unary};
use inputs::*;
use values::*;

/// Typed failures stay compact; external causes are retained only on failure.
#[derive(Debug, Clone)]
pub(crate) enum VmError {
    TypeMismatch,
    InvalidSource,
    DivisionByZero,
    Overflow,
    External(std::sync::Arc<datafusion::common::DataFusionError>),
}

impl VmError {
    pub(crate) fn into_datafusion(self) -> datafusion::common::DataFusionError {
        use datafusion::arrow::error::ArrowError;
        use datafusion::common::DataFusionError;
        match self {
            Self::DivisionByZero => ArrowError::DivideByZero.into(),
            Self::External(error) => DataFusionError::Shared(error),
            error => DataFusionError::Execution(error.to_string()),
        }
    }
}

impl std::fmt::Display for VmError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TypeMismatch => f.write_str("internal typed predicate type mismatch"),
            Self::InvalidSource => {
                f.write_str("internal typed predicate source is invalid")
            }
            Self::DivisionByZero => f.write_str("Divide by zero"),
            Self::Overflow => f.write_str("numeric overflow"),
            Self::External(error) => error.fmt(f),
        }
    }
}

impl std::error::Error for VmError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::External(error) => Some(error.as_ref()),
            _ => None,
        }
    }
}

impl From<datafusion::common::DataFusionError> for VmError {
    #[cold]
    fn from(error: datafusion::common::DataFusionError) -> Self {
        Self::External(std::sync::Arc::new(error))
    }
}

impl From<datafusion::arrow::error::ArrowError> for VmError {
    #[cold]
    fn from(error: datafusion::arrow::error::ArrowError) -> Self {
        match error {
            datafusion::arrow::error::ArrowError::DivideByZero => Self::DivisionByZero,
            error => Self::from(datafusion::common::DataFusionError::from(error)),
        }
    }
}

/// Exact visited work for one typed predicate.
///
/// Each demanded source, operator, Boolean guard and final result is counted.
/// A skipped subtree contributes no work; reached errors retain prior visits.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct VmIrEvalStats {
    #[cfg(test)]
    pub(crate) and_short_circuits: usize,
    #[cfg(test)]
    pub(crate) or_short_circuits: usize,
    pub(crate) visited_ops: usize,
}

impl VmIrEvalStats {
    #[inline]
    pub(crate) fn visit_op(&mut self) {
        self.visited_ops += 1;
    }
}

/// Result and aggregate statistics for one typed predicate evaluation.
#[derive(Debug)]
pub(crate) struct VmIrEvalOutcome {
    pub(crate) result: Result<VmTriBool, VmError>,
    pub(crate) stats: VmIrEvalStats,
}

impl VmIrEvalOutcome {
    pub(crate) const fn new(
        result: Result<VmTriBool, VmError>,
        stats: VmIrEvalStats,
    ) -> Self {
        Self { result, stats }
    }
}

#[cfg(test)]
mod tests;