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.

//! Demand-driven borrowed reads from Arrow, registers and navigation state.
use super::*;
pub(super) struct Inputs<'a> {
    pub row: DirectRow<'a>,
    pub registers: &'a [u64],
    pub nav: NavigationReadView<'a>,
    pub candidate: Option<CandidateInput<'a>>,
    pub batch: Option<(&'a RecordBatch, usize)>,
    pub aggregates: &'a [ScalarValue],
    pub symbols: &'a [Option<String>],
}
impl<'a> Inputs<'a> {
    #[inline]
    pub(super) fn load(&self, s: &'a Source) -> Result<Value<'a>, VmError> {
        Ok(match s {
            Source::Literal(v) => Value::scalar(v)?,
            Source::MatchNumber => {
                Value::I64(checked_match_number(self.row.match_number)?)
            }
            Source::MatchSequenceNumber => Value::I64(self.row.sequence),
            Source::Column(col, ty) => self.column(false, *col, *ty)?,
            Source::Navigation(read, resolved, ty, count) => {
                if count.is_some_and(|slot| self.registers[slot.index()] == 0) {
                    Value::Null
                } else {
                    self.navigation(read, *resolved, *ty)?
                }
            }
            Source::Managed(slot, cell, ty) => {
                if cell.has_no_nonnull_rows(self.registers) {
                    return Ok(Value::Null);
                }
                // Aggregate accumulators retain DataFusion's wrapping coefficients.
                // Precision is checked by arithmetic/casts, never by a source read.
                let decimal = |v| {
                    let VmScalarType::Decimal128 { precision, scale } = ty else {
                        return Err(VmError::TypeMismatch);
                    };
                    Ok(Value::Decimal(v, *precision, *scale))
                };
                match cell.source() {
                    BoundStateSource::Register { slot } => {
                        Value::word(self.registers[slot.index()], *ty)?
                    }
                    BoundStateSource::RegisterD128 { slot } => decimal(i128_from_words(
                        self.registers[slot.index()],
                        self.registers[slot.index() + 1],
                    ))?,
                    BoundStateSource::CandidateStart { column } => {
                        self.column(true, column.index(), *ty)?
                    }
                    BoundStateSource::RetainedRow { slot, column } => {
                        let (batch, row) = self
                            .candidate
                            .ok_or(VmError::InvalidSource)?
                            .batch_row_at(crate::core::AbsoluteRow::new(
                                self.registers[slot.index()],
                            ))?;
                        array_value(batch.column(column.index()).as_ref(), row)?
                    }
                    BoundStateSource::AccumulatorOwned => Value::scalar(
                        self.aggregates.get(*slot).ok_or(VmError::InvalidSource)?,
                    )?,
                    BoundStateSource::Avg {
                        sum_slot,
                        count_slot,
                    } => register_average(
                        self.registers[sum_slot.index()],
                        self.registers[count_slot.index()],
                    )
                    .map_or(Value::Null, Value::F64),
                    BoundStateSource::AvgDecimal128 {
                        sum_slot,
                        count_slot,
                        scale_factor,
                    } => {
                        let sum = i128_from_words(
                            self.registers[sum_slot.index()],
                            self.registers[sum_slot.index() + 1],
                        );
                        register_decimal_average(
                            sum,
                            self.registers[count_slot.index()],
                            *scale_factor,
                        )?
                        .map(decimal)
                        .transpose()?
                        .unwrap_or(Value::Null)
                    }
                    BoundStateSource::Navigation(read) => {
                        self.navigation(read, None, *ty)?
                    }
                    // Statistical state keeps its existing shared projection implementation.
                    BoundStateSource::Variance { .. } => {
                        let BoundStateRead::Scalar(v) =
                            cell.read(self.registers, self.nav, self.symbols)?
                        else {
                            return Err(VmError::InvalidSource);
                        };
                        Value::scalar(&v)?.owned()?
                    }
                }
            }
        })
    }
    #[inline]
    fn navigation(
        &self,
        read: &'a BoundNavigation,
        resolved: Option<super::super::types::PackedNavigationRead>,
        ty: VmScalarType,
    ) -> Result<Value<'a>, VmError> {
        Ok(match read.domain {
            NavigationValueDomain::Decimal128 => {
                match resolved.map_or_else(
                    || self.nav.decimal128(read.lookup()),
                    |r| match self.nav.resolved::<2>(r) {
                        NavigationDatum::Value([lo, hi]) => {
                            NavigationDatum::Value((lo, hi))
                        }
                        NavigationDatum::Null => NavigationDatum::Null,
                        NavigationDatum::Missing => NavigationDatum::Missing,
                    },
                ) {
                    NavigationDatum::Value((lo, hi)) => {
                        let VmScalarType::Decimal128 { precision, scale } = ty else {
                            return Err(VmError::TypeMismatch);
                        };
                        Value::Decimal(i128_from_words(lo, hi), precision, scale)
                    }
                    NavigationDatum::Null => Value::Null,
                    NavigationDatum::Missing => read
                        .default_value
                        .as_ref()
                        .map(Value::scalar)
                        .transpose()?
                        .unwrap_or(Value::Null),
                }
            }
            _ => match resolved.map_or_else(
                || self.nav.primitive(read.lookup()),
                |r| match self.nav.resolved::<1>(r) {
                    NavigationDatum::Value([word]) => NavigationDatum::Value(word),
                    NavigationDatum::Null => NavigationDatum::Null,
                    NavigationDatum::Missing => NavigationDatum::Missing,
                },
            ) {
                NavigationDatum::Value(word) => {
                    if read.domain == NavigationValueDomain::Classifier {
                        Value::Str(BoundNavigation::classifier_name(word, self.symbols)?)
                    } else {
                        Value::word(word, ty)?
                    }
                }
                NavigationDatum::Null => Value::Null,
                NavigationDatum::Missing => read
                    .default_value
                    .as_ref()
                    .map(Value::scalar)
                    .transpose()?
                    .unwrap_or(Value::Null),
            },
        })
    }

    #[inline]
    fn column(
        &self,
        start: bool,
        column: usize,
        ty: VmScalarType,
    ) -> Result<Value<'a>, VmError> {
        let bound = if start {
            self.row.candidate_start
        } else {
            self.row.current
        };
        if let Some(row) = bound {
            if let VmScalarType::Decimal128 { precision, scale } = ty {
                if let Some(value) = row.read_decimal_checked(column) {
                    return Ok(value
                        .map_or(Value::Null, |v| Value::Decimal(v, precision, scale)));
                }
            } else if !ty.is_string()
                && let Some(value) = row.read_word_checked(column, false)
            {
                return value
                    .map(|v| Value::word(v, ty))
                    .transpose()
                    .map(|v| v.unwrap_or(Value::Null));
            }
        }
        // A bound row may omit this column (for example in a sparse wide batch).
        // Read its typed Arrow value without constructing a row scalar.
        let (batch, row) = if start {
            self.candidate.ok_or(VmError::InvalidSource)?.batch_row()?
        } else {
            self.batch.ok_or(VmError::InvalidSource)?
        };
        array_value(
            batch
                .columns()
                .get(column)
                .ok_or(VmError::InvalidSource)?
                .as_ref(),
            row,
        )
    }
}
pub(super) fn array_value(array: &dyn Array, row: usize) -> Result<Value<'_>, VmError> {
    if row >= array.len() {
        return Err(VmError::InvalidSource);
    }
    if array.is_null(row) {
        return Ok(Value::Null);
    }
    macro_rules! read {
        ($t:ty,$variant:ident) => {
            Value::$variant(
                array
                    .as_any()
                    .downcast_ref::<$t>()
                    .ok_or(VmError::TypeMismatch)?
                    .value(row)
                    .into(),
            )
        };
    }
    Ok(match array.data_type() {
        DataType::Boolean => read!(BooleanArray, Bool),
        DataType::Int8 => read!(Int8Array, I64),
        DataType::Int16 => read!(Int16Array, I64),
        DataType::Int32 => read!(Int32Array, I64),
        DataType::Date32 => read!(Date32Array, I64),
        DataType::Time32(TimeUnit::Second) => read!(Time32SecondArray, I64),
        DataType::Time32(TimeUnit::Millisecond) => read!(Time32MillisecondArray, I64),
        DataType::Int64 => read!(Int64Array, I64),
        DataType::Date64 => read!(Date64Array, I64),
        DataType::Time64(TimeUnit::Microsecond) => read!(Time64MicrosecondArray, I64),
        DataType::Time64(TimeUnit::Nanosecond) => read!(Time64NanosecondArray, I64),
        DataType::Duration(TimeUnit::Second) => read!(DurationSecondArray, I64),
        DataType::Duration(TimeUnit::Millisecond) => read!(DurationMillisecondArray, I64),
        DataType::Duration(TimeUnit::Microsecond) => read!(DurationMicrosecondArray, I64),
        DataType::Duration(TimeUnit::Nanosecond) => read!(DurationNanosecondArray, I64),
        DataType::Timestamp(TimeUnit::Second, _) => read!(TimestampSecondArray, I64),
        DataType::Timestamp(TimeUnit::Millisecond, _) => {
            read!(TimestampMillisecondArray, I64)
        }
        DataType::Timestamp(TimeUnit::Microsecond, _) => {
            read!(TimestampMicrosecondArray, I64)
        }
        DataType::Timestamp(TimeUnit::Nanosecond, _) => {
            read!(TimestampNanosecondArray, I64)
        }
        DataType::UInt8 => read!(UInt8Array, U64),
        DataType::UInt16 => read!(UInt16Array, U64),
        DataType::UInt32 => read!(UInt32Array, U64),
        DataType::UInt64 => read!(UInt64Array, U64),
        DataType::Float32 => read!(Float32Array, F32),
        DataType::Float64 => read!(Float64Array, F64),
        DataType::Utf8 => read!(StringArray, Str),
        DataType::LargeUtf8 => read!(LargeStringArray, Str),
        DataType::Utf8View => read!(StringViewArray, Str),
        DataType::Decimal128(p, s) => Value::Decimal(
            array
                .as_any()
                .downcast_ref::<Decimal128Array>()
                .ok_or(VmError::TypeMismatch)?
                .value(row),
            *p,
            *s,
        ),
        _ => Value::scalar(&ScalarValue::try_from_array(array, row)?)?.owned()?,
    })
}