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.

//! Compact typed arena; literals use DataFusion's scalar representation.

use datafusion::arrow::datatypes::{DataType, TimeUnit};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// Exact source domains; timestamp zones compare stored instants within a unit.
/// Decimal256 and fixed binary descriptors also serve aggregate storage planning.
pub enum VmScalarType {
    Bool,
    Int8,
    Int16,
    Int32,
    Int64,
    UInt8,
    UInt16,
    UInt32,
    UInt64,
    Float32,
    Float64,
    Utf8,
    LargeUtf8,
    Utf8View,
    FixedSizeBinary(u8),
    Date32,
    Date64,
    Time32(TimeUnit),
    Time64(TimeUnit),
    Duration(TimeUnit),
    Timestamp {
        unit: TimeUnit,
        timezone_aware: bool,
    },
    Decimal128 {
        precision: u8,
        scale: i8,
    },
    Decimal256 {
        precision: u8,
        scale: i8,
    },
    MetadataI64,
}

impl VmScalarType {
    #[inline]
    pub fn arrow_type(self) -> DataType {
        match self {
            Self::Bool => DataType::Boolean,
            Self::Int8 => DataType::Int8,
            Self::Int16 => DataType::Int16,
            Self::Int32 => DataType::Int32,
            Self::Int64 | Self::MetadataI64 => DataType::Int64,
            Self::UInt8 => DataType::UInt8,
            Self::UInt16 => DataType::UInt16,
            Self::UInt32 => DataType::UInt32,
            Self::UInt64 => DataType::UInt64,
            Self::Float32 => DataType::Float32,
            Self::Float64 => DataType::Float64,
            Self::Utf8 => DataType::Utf8,
            Self::LargeUtf8 => DataType::LargeUtf8,
            Self::Utf8View => DataType::Utf8View,
            Self::FixedSizeBinary(width) => DataType::FixedSizeBinary(i32::from(width)),
            Self::Date32 => DataType::Date32,
            Self::Date64 => DataType::Date64,
            Self::Time32(unit) => DataType::Time32(unit),
            Self::Time64(unit) => DataType::Time64(unit),
            Self::Duration(unit) => DataType::Duration(unit),
            Self::Timestamp {
                unit,
                timezone_aware,
            } => DataType::Timestamp(unit, timezone_aware.then(|| "UTC".into())),
            Self::Decimal128 { precision, scale } => {
                DataType::Decimal128(precision, scale)
            }
            Self::Decimal256 { precision, scale } => {
                DataType::Decimal256(precision, scale)
            }
        }
    }

    pub const fn is_string(self) -> bool {
        matches!(self, Self::Utf8 | Self::LargeUtf8 | Self::Utf8View)
    }

    pub const fn is_temporal(self) -> bool {
        matches!(
            self,
            Self::Date32
                | Self::Date64
                | Self::Time32(TimeUnit::Second | TimeUnit::Millisecond)
                | Self::Time64(TimeUnit::Microsecond | TimeUnit::Nanosecond)
                | Self::Duration(_)
                | Self::Timestamp { .. }
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VmType {
    pub scalar: VmScalarType,
    pub nullable: bool,
}

impl VmType {
    pub const fn non_null(scalar: VmScalarType) -> Self {
        Self {
            scalar,
            nullable: false,
        }
    }

    pub const fn nullable(scalar: VmScalarType) -> Self {
        Self {
            scalar,
            nullable: true,
        }
    }
}

/// Immutable plan literals reuse DataFusion's type, equality and hashing rules.
pub type VmLiteral = datafusion::common::ScalarValue;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum VmSourceRef {
    Literal(VmLiteral),
    ManagedSlot { slot_idx: u16, ty: VmType },
    RowValue { column_ref: u16, ty: VmType },
    StaticScalar { scalar_idx: u16, ty: VmType },
    StaticPredicate { bool_idx: u16 },
    MatchNumber,
    MatchSequenceNumber,
}

impl VmSourceRef {
    pub fn output_type(&self) -> VmType {
        match self {
            Self::Literal(literal) => {
                super::vm_type_from_data_type(&literal.data_type(), literal.is_null())
                    .expect("admitted literal")
            }
            Self::ManagedSlot { ty, .. }
            | Self::RowValue { ty, .. }
            | Self::StaticScalar { ty, .. } => *ty,
            Self::StaticPredicate { .. } => VmType::nullable(VmScalarType::Bool),
            Self::MatchNumber | Self::MatchSequenceNumber => {
                VmType::non_null(VmScalarType::MetadataI64)
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VmUnaryOp {
    Not,
    IsTrue,
    Neg,
    CheckedNeg,
    Abs,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VmBinaryOp {
    And,
    Or,
    Add,
    Sub,
    Mul,
    AddInterval,
    SubInterval,
    Eq,
    Ne,
    Gt,
    Ge,
    Lt,
    Le,
    IsDistinctFrom,
    IsNotDistinctFrom,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PredicateNode {
    Source(VmSourceRef),
    Unary {
        op: VmUnaryOp,
        out_ty: VmType,
        input: u16,
    },
    Binary {
        op: VmBinaryOp,
        out_ty: VmType,
        left: u16,
        right: u16,
    },
    Coalesce {
        left: u16,
        right: u16,
        out_ty: VmType,
    },
    Cast {
        target_ty: VmType,
        input: u16,
    },
    IsNull {
        input: u16,
    },
    IsNotNull {
        input: u16,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectPredicatePlan {
    pub(super) nodes: Vec<PredicateNode>,
    pub(super) root: u16,
    pub(super) value_slots: u16,
    pub(super) row_columns: Vec<String>,
}

impl DirectPredicatePlan {
    pub fn nodes(&self) -> &[PredicateNode] {
        &self.nodes
    }
    pub fn root(&self) -> u16 {
        self.root
    }
    #[cfg(any(test, feature = "test-support"))]
    pub fn value_slots(&self) -> u16 {
        self.value_slots
    }
    pub fn row_columns(&self) -> &[String] {
        &self.row_columns
    }
    pub fn sources(&self) -> impl Iterator<Item = &VmSourceRef> {
        self.nodes.iter().filter_map(|node| match node {
            PredicateNode::Source(source) => Some(source),
            _ => None,
        })
    }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VmTriBool {
    True,
    False,
    Unknown,
}

impl VmTriBool {
    pub const fn and(self, rhs: Self) -> Self {
        use VmTriBool::{False, True, Unknown};
        match (self, rhs) {
            (False, _) | (_, False) => False,
            (True, True) => True,
            _ => Unknown,
        }
    }

    pub const fn or(self, rhs: Self) -> Self {
        use VmTriBool::{False, True, Unknown};
        match (self, rhs) {
            (True, _) | (_, True) => True,
            (False, False) => False,
            _ => Unknown,
        }
    }

    pub const fn not(self) -> Self {
        match self {
            Self::True => Self::False,
            Self::False => Self::True,
            Self::Unknown => Self::Unknown,
        }
    }
}