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.

//! Ordered instructions charge each reached source, operator, guard and final result.
use super::*;
use arrayvec::ArrayVec;
#[derive(Debug, Clone, Copy)]
pub(super) enum Unary {
    Operator(VmUnaryOp, VmScalarType),
    Cast(VmScalarType),
    NullTest(bool),
}
#[derive(Debug, Clone)]
pub(super) enum Op {
    Read(Source),
    Unary(Unary),
    Binary(VmBinaryOp, VmScalarType),
    Guard { decisive: bool, resume: usize },
    GuardNotNull { resume: usize },
    Pop,
}
impl BoundPredicate {
    pub(super) fn evaluate<'a>(
        &'a self,
        load: impl FnMut(&'a Source) -> Result<Value<'a>, VmError>,
        stats: &mut VmIrEvalStats,
    ) -> Result<VmTriBool, VmError> {
        self.evaluate_inner::<true, 64>(load, stats)
    }

    fn evaluate_inner<'a, const TRACK_STATS: bool, const STACK: usize>(
        &'a self,
        mut load: impl FnMut(&'a Source) -> Result<Value<'a>, VmError>,
        stats: &mut VmIrEvalStats,
    ) -> Result<VmTriBool, VmError> {
        let mut stack = ArrayVec::<Value<'a>, STACK>::new();
        let mut pc = 0;
        while let Some(op) = self.ops.get(pc) {
            if TRACK_STATS {
                stats.visit_op();
            }
            pc += 1;
            match op {
                Op::Read(s) => stack.push(load(s)?),
                Op::Unary(op) => {
                    let v = stack.pop().expect("operand");
                    stack.push(match op {
                        Unary::NullTest(null) => {
                            Value::Bool(matches!(v, Value::Null) == *null)
                        }
                        Unary::Cast(target) => v.cast(*target)?,
                        Unary::Operator(VmUnaryOp::Not, _) => {
                            Value::truth(v.boolean()?.not())
                        }
                        Unary::Operator(op, ty) => v.unary(*op, *ty)?,
                    });
                }
                Op::Binary(op, ty) => {
                    let right = stack.pop().expect("right");
                    let left = stack.pop().expect("left");
                    stack.push(left.binary(*op, *ty, right)?);
                }
                Op::Guard { decisive, resume } => {
                    if stack.last().expect("guard").boolean()?
                        == if *decisive {
                            VmTriBool::True
                        } else {
                            VmTriBool::False
                        }
                    {
                        pc = *resume;
                        #[cfg(test)]
                        if TRACK_STATS {
                            if *decisive {
                                stats.or_short_circuits += 1;
                            } else {
                                stats.and_short_circuits += 1;
                            }
                        }
                    }
                }
                Op::GuardNotNull { resume } => {
                    if !matches!(stack.last().expect("coalesce guard"), Value::Null) {
                        pc = *resume;
                    }
                }
                Op::Pop => {
                    stack.pop().expect("pop");
                }
            }
        }
        if TRACK_STATS {
            stats.visit_op();
        }
        stack.pop().ok_or(VmError::InvalidSource)?.boolean()
    }
    #[inline]
    pub(crate) fn evaluate_direct_row(
        &self,
        row: DirectRow<'_>,
        registers: &[u64],
        nav: NavigationReadView<'_>,
    ) -> Option<bool> {
        if !self.has_direct_readers() {
            return None;
        }
        let inputs = Inputs {
            row,
            registers,
            nav,
            candidate: None,
            batch: None,
            aggregates: &[],
            symbols: &[],
        };
        let mut stats = VmIrEvalStats::default();
        let result = if self.ops.len() <= 8 {
            self.evaluate_inner::<false, 8>(|s| inputs.load(s), &mut stats)
        } else {
            self.evaluate_inner::<false, 64>(|s| inputs.load(s), &mut stats)
        };
        result.ok().map(|v| v == VmTriBool::True)
    }
}
pub(crate) fn evaluate_bound_predicate(
    engine: &AggregateEngine<'_, '_>,
    registers: &[u64],
    nav: NavigationReadView<'_>,
    predicate: &BoundPredicate,
) -> VmIrEvalOutcome {
    let inputs = Inputs {
        row: DirectRow {
            current: engine.bound_row,
            candidate_start: engine.bound_candidate_start(),
            sequence: engine.state.evaluation.current_match_sequence_number,
            match_number: engine.next_match_number,
        },
        registers,
        nav,
        candidate: Some(engine.candidate_input()),
        batch: engine
            .cached_batch_location
            .map(|(batch, row)| (engine.input_buffer.batch(batch), row)),
        aggregates: &engine.state.scratch.scratch_agg_results,
        symbols: engine.matcher.automaton().id_to_symbol(),
    };
    let mut stats = VmIrEvalStats::default();
    let result = predicate.evaluate(|s| inputs.load(s), &mut stats);
    VmIrEvalOutcome::new(result, stats)
}