datafusion-match-recognize 0.55.0

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.

//! Shared static Boolean membership and row-location contract.

use super::ResolvedBoolColumn;
use crate::core::SymbolId;
use datafusion::arrow::array::{Array, BooleanArray};
use datafusion::common::Result;
use std::ops::Range;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RowLocation {
    pub(crate) local_row: usize,
}

/// Provides row-level predicate results. Membership uses SQL `IS TRUE`.
pub(crate) trait BoolColumnProvider {
    /// Locate a row while reporting every runtime-sized search iteration.
    ///
    /// Implementations with constant-time lookup may return directly. Any
    /// input-sized traversal must report through `completed`.
    fn locate_with_work(
        &self,
        row: usize,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<Option<RowLocation>>;
    fn get_bool_with_loc(&self, symbol_id: SymbolId, loc: RowLocation) -> bool;
    /// Read a positive candidate precheck with SQL `IS TRUE` semantics.
    fn get_bool_from_col_with_loc(
        &self,
        column: ResolvedBoolColumn,
        loc: RowLocation,
    ) -> bool;
    /// A leading AND term can reject early only when it is SQL FALSE.
    /// Providers with no candidate precheck columns can use the default.
    fn precheck_is_false(&self, _column: ResolvedBoolColumn, _loc: RowLocation) -> bool {
        false
    }
    /// Return whether a precomputed static symbol matches any provider row.
    fn symbol_is_present(
        &self,
        symbol_id: SymbolId,
        completed: &mut impl FnMut(usize) -> Result<()>,
    ) -> Result<bool> {
        self.symbol_is_present_in_range(symbol_id, 0..self.num_rows(), completed)
    }
    /// Check a bounded range of rows relative to the provider's readable view.
    fn symbol_is_present_in_range(
        &self,
        symbol_id: SymbolId,
        range: Range<usize>,
        completed: &mut impl FnMut(usize) -> Result<()>,
    ) -> Result<bool> {
        if range.start > range.end || range.end > self.num_rows() {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE presence range {range:?} is outside its Boolean provider"
            );
        }
        for row in range {
            let location = self.locate_with_work(row, completed)?.ok_or_else(|| {
                datafusion::common::internal_datafusion_err!(
                    "MATCH_RECOGNIZE absence scan row is missing from its Boolean provider"
                )
            })?;
            let present = self.get_bool_with_loc(symbol_id, location);
            completed(1)?;
            if present {
                return Ok(true);
            }
        }
        Ok(false)
    }

    fn num_rows(&self) -> usize;
}

/// SQL TRUE requires both the validity bitmap and the data bitmap.
#[inline(always)]
pub(crate) fn is_true(column: &BooleanArray, row: usize) -> bool {
    column.is_valid(row) && column.value(row)
}

#[inline]
pub(super) fn packed_union(words: &[u64]) -> u64 {
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    if std::is_x86_feature_detected!("avx2") {
        // SAFETY: runtime feature detection covers this function's target.
        return unsafe { avx2_union(words) };
    }
    words.iter().fold(0, |union, word| union | word)
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[target_feature(enable = "avx2")]
unsafe fn avx2_union(words: &[u64]) -> u64 {
    words.iter().fold(0, |union, word| union | word)
}