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.

//! Checked `Int64` arithmetic and offset comparisons for `OffsetExpression`.

use super::{NavigationInput, Neighbor, is_strict_comparison};
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
use datafusion::arrow::array::{Array, AsArray};
use datafusion::arrow::datatypes::{DataType, Int64Type, SchemaRef};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{Result, ScalarValue};
use datafusion::logical_expr::Operator;
use datafusion::physical_expr::expressions::{BinaryExpr, Column, Literal};
use datafusion::physical_plan::PhysicalExpr;

/// Checked arithmetic on two current or shifted Int64 leaves. Results stay
/// private until the entire chunk succeeds, including across partition edges.
#[derive(Debug, Clone)]
pub(super) struct Int64Compare {
    pub(super) shape: Int64ComparisonShape,
    left: usize,
    right: usize,
    subtract: bool,
    op: Operator,
    literal: i64,
}

#[derive(Debug, Clone, Copy)]
pub(super) enum Int64ComparisonShape {
    /// `(left +/- right) op literal`.
    Arithmetic,
    /// `left op (right +/- literal)`; evaluate RHS even when LHS is NULL.
    Offset,
}

impl Int64Compare {
    pub(super) fn bind_arithmetic(
        predicate: &dyn PhysicalExpr,
        schema: &SchemaRef,
    ) -> Option<Self> {
        let compare = predicate.downcast_ref::<BinaryExpr>()?;
        if !is_strict_comparison(*compare.op()) {
            return None;
        }
        let arithmetic = compare.left().downcast_ref::<BinaryExpr>()?;
        if !matches!(arithmetic.op(), Operator::Plus | Operator::Minus) {
            return None;
        }
        let left = arithmetic.left().downcast_ref::<Column>()?.index();
        let right = arithmetic.right().downcast_ref::<Column>()?.index();
        if schema.field(left).data_type() != &DataType::Int64
            || schema.field(right).data_type() != &DataType::Int64
        {
            return None;
        }
        let ScalarValue::Int64(Some(literal)) =
            compare.right().downcast_ref::<Literal>()?.value()
        else {
            return None;
        };
        Some(Self {
            shape: Int64ComparisonShape::Arithmetic,
            left,
            right,
            subtract: *arithmetic.op() == Operator::Minus,
            op: *compare.op(),
            literal: *literal,
        })
    }

    #[inline(always)]
    fn evaluate(&self, left: Option<i64>, right: Option<i64>) -> Option<bool> {
        let Some(right) = right else {
            return Some(false);
        };
        let checked = |a: i64, b: i64| {
            if self.subtract {
                a.checked_sub(b)
            } else {
                a.checked_add(b)
            }
        };
        let (left, right) = match self.shape {
            Int64ComparisonShape::Arithmetic => {
                let Some(left) = left else {
                    return Some(false);
                };
                (checked(left, right)?, self.literal)
            }
            Int64ComparisonShape::Offset => {
                let adjusted = checked(right, self.literal)?;
                let Some(left) = left else {
                    return Some(false);
                };
                (left, adjusted)
            }
        };
        Some(match self.op {
            Operator::Eq => left == right,
            Operator::NotEq => left != right,
            Operator::Lt => left < right,
            Operator::LtEq => left <= right,
            Operator::Gt => left > right,
            Operator::GtEq => left >= right,
            _ => unreachable!("strict comparison checked at binding"),
        })
    }

    #[inline]
    pub(super) fn apply(
        &self,
        leaves: &[Neighbor],
        batch: &RecordBatch,
        start: usize,
        out: &mut [u64],
        bit: u64,
        navigation: Option<(&SharedHistoryBuffer, NavigationInput<'_>, usize)>,
    ) -> Result<bool> {
        if out.len() > 64 {
            return Ok(false);
        }
        let mut passing = 0u64;
        let mut offset = 0;
        while offset < out.len() {
            let mut len = out.len() - offset;
            let (lhs, rhs) = if let Some((history, input, base)) = navigation {
                let local = base + start + offset;
                let segment = input.ranges.partition_point(|r| r.end <= local);
                let range = &input.ranges[segment];
                len = len.min(range.end - local);
                let partition = if segment == 0 {
                    input.first_start
                } else {
                    input.origin + range.start
                }..if segment + 1 == input.ranges.len() {
                    input.last_end
                } else {
                    input.origin + range.end
                };
                let (lhs, n) = leaves[self.left].span(
                    history,
                    &partition,
                    input.origin + local,
                    len,
                )?;
                len = len.min(n);
                let (rhs, n) = leaves[self.right].span(
                    history,
                    &partition,
                    input.origin + local,
                    len,
                )?;
                len = len.min(n);
                (lhs, rhs)
            } else {
                if leaves[self.left].shift != 0 || leaves[self.right].shift != 0 {
                    return Ok(false);
                }
                (
                    Some((batch.column(leaves[self.left].column), start + offset)),
                    Some((batch.column(leaves[self.right].column), start + offset)),
                )
            };
            let lhs = lhs.map(|(array, at)| (array.as_primitive::<Int64Type>(), at));
            let rhs = rhs.map(|(array, at)| (array.as_primitive::<Int64Type>(), at));
            if let (Some((left, left_at)), Some((right, right_at))) = (lhs, rhs)
                && left.null_count() == 0
                && right.null_count() == 0
            {
                // Keep the common all-valid path over contiguous value slices.
                // No validity checks, dynamic array casts, or default lookups run
                // per row, and no output is published before overflow is ruled out.
                let left = &left.values()[left_at..left_at + len];
                let right = &right.values()[right_at..right_at + len];
                for i in 0..len {
                    let Some(accepted) = self.evaluate(Some(left[i]), Some(right[i]))
                    else {
                        return Ok(false);
                    };
                    passing |= u64::from(accepted) << (offset + i);
                }
            } else {
                let read = |span: Option<(
                    &datafusion::arrow::array::PrimitiveArray<Int64Type>,
                    usize,
                )>,
                            leaf: &Neighbor,
                            i| {
                    if let Some((array, at)) = span {
                        array.is_valid(at + i).then(|| array.value(at + i))
                    } else {
                        match leaf.default.as_deref() {
                            Some(ScalarValue::Int64(value)) => *value,
                            _ => None,
                        }
                    }
                };
                for i in 0..len {
                    let Some(accepted) = self.evaluate(
                        read(lhs, &leaves[self.left], i),
                        read(rhs, &leaves[self.right], i),
                    ) else {
                        return Ok(false);
                    };
                    passing |= u64::from(accepted) << (offset + i);
                }
            }
            offset += len;
        }
        for (i, word) in out.iter_mut().enumerate() {
            if passing & (1 << i) != 0 {
                *word |= bit;
            }
        }
        Ok(true)
    }

    pub(super) fn bind_offset(
        predicate: &dyn PhysicalExpr,
        schema: &SchemaRef,
    ) -> Option<Self> {
        let cmp = predicate.downcast_ref::<BinaryExpr>()?;
        let raw_op = *cmp.op();
        if !is_strict_comparison(raw_op) {
            return None;
        }
        let (col, shifted, op) = if let Some(col) = cmp.left().downcast_ref::<Column>() {
            (col, cmp.right(), raw_op)
        } else {
            let flipped = match raw_op {
                Operator::Lt => Operator::Gt,
                Operator::LtEq => Operator::GtEq,
                Operator::Gt => Operator::Lt,
                Operator::GtEq => Operator::LtEq,
                other => other,
            };
            (cmp.right().downcast_ref::<Column>()?, cmp.left(), flipped)
        };
        let shifted = shifted.downcast_ref::<BinaryExpr>()?;
        let subtract = match shifted.op() {
            Operator::Plus => false,
            Operator::Minus => true,
            _ => return None,
        };
        let (base, literal) = if let Some(base) = shifted.left().downcast_ref::<Column>()
        {
            (base, shifted.right())
        } else if !subtract {
            (shifted.right().downcast_ref::<Column>()?, shifted.left())
        } else {
            return None;
        };
        let ScalarValue::Int64(Some(literal)) =
            literal.downcast_ref::<Literal>()?.value()
        else {
            return None;
        };
        let (left, right) = (col.index(), base.index());
        if [left, right]
            .into_iter()
            .any(|i| schema.field(i).data_type() != &DataType::Int64)
        {
            return None;
        }
        Some(Self {
            shape: Int64ComparisonShape::Offset,
            left,
            right,
            literal: *literal,
            subtract,
            op,
        })
    }
}