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.

//! Temporal and Decimal128 word encodings shared by planning and execution.

use datafusion::arrow::datatypes::{DataType, TimeUnit};
use datafusion::common::ScalarValue;

/// Whether a temporal Arrow type has a supported signed one-word representation.
#[inline]
pub fn is_temporal_word_type(data_type: &DataType) -> bool {
    matches!(
        data_type,
        DataType::Date32
            | DataType::Date64
            | DataType::Time32(TimeUnit::Second | TimeUnit::Millisecond)
            | DataType::Time64(TimeUnit::Microsecond | TimeUnit::Nanosecond)
            | DataType::Timestamp(_, _)
            | DataType::Duration(_)
    )
}

/// Extract a nonnull temporal coefficient without changing its unit or timezone.
///
/// Narrow signed coefficients are sign-extended. Null and non-temporal scalars
/// return `None`; callers retain null state separately from the word.
#[inline]
pub fn temporal_scalar_to_bits(value: &ScalarValue) -> Option<u64> {
    let value = match value {
        ScalarValue::Date32(Some(value))
        | ScalarValue::Time32Second(Some(value))
        | ScalarValue::Time32Millisecond(Some(value)) => i64::from(*value),
        ScalarValue::Date64(Some(value))
        | ScalarValue::Time64Microsecond(Some(value))
        | ScalarValue::Time64Nanosecond(Some(value))
        | ScalarValue::TimestampSecond(Some(value), _)
        | ScalarValue::TimestampMillisecond(Some(value), _)
        | ScalarValue::TimestampMicrosecond(Some(value), _)
        | ScalarValue::TimestampNanosecond(Some(value), _)
        | ScalarValue::DurationSecond(Some(value))
        | ScalarValue::DurationMillisecond(Some(value))
        | ScalarValue::DurationMicrosecond(Some(value))
        | ScalarValue::DurationNanosecond(Some(value)) => *value,
        _ => return None,
    };
    Some(value as u64)
}

/// Reconstruct a temporal coefficient using the complete bound Arrow type.
///
/// No unit or timezone conversion is performed. Unsupported types return `None`.
#[inline]
pub fn temporal_scalar_from_bits(word: u64, data_type: &DataType) -> Option<ScalarValue> {
    let value = word as i64;
    Some(match data_type {
        DataType::Date32 => ScalarValue::Date32(Some(value as i32)),
        DataType::Date64 => ScalarValue::Date64(Some(value)),
        DataType::Time32(TimeUnit::Second) => {
            ScalarValue::Time32Second(Some(value as i32))
        }
        DataType::Time32(TimeUnit::Millisecond) => {
            ScalarValue::Time32Millisecond(Some(value as i32))
        }
        DataType::Time64(TimeUnit::Microsecond) => {
            ScalarValue::Time64Microsecond(Some(value))
        }
        DataType::Time64(TimeUnit::Nanosecond) => {
            ScalarValue::Time64Nanosecond(Some(value))
        }
        DataType::Timestamp(TimeUnit::Second, timezone) => {
            ScalarValue::TimestampSecond(Some(value), timezone.clone())
        }
        DataType::Timestamp(TimeUnit::Millisecond, timezone) => {
            ScalarValue::TimestampMillisecond(Some(value), timezone.clone())
        }
        DataType::Timestamp(TimeUnit::Microsecond, timezone) => {
            ScalarValue::TimestampMicrosecond(Some(value), timezone.clone())
        }
        DataType::Timestamp(TimeUnit::Nanosecond, timezone) => {
            ScalarValue::TimestampNanosecond(Some(value), timezone.clone())
        }
        DataType::Duration(TimeUnit::Second) => ScalarValue::DurationSecond(Some(value)),
        DataType::Duration(TimeUnit::Millisecond) => {
            ScalarValue::DurationMillisecond(Some(value))
        }
        DataType::Duration(TimeUnit::Microsecond) => {
            ScalarValue::DurationMicrosecond(Some(value))
        }
        DataType::Duration(TimeUnit::Nanosecond) => {
            ScalarValue::DurationNanosecond(Some(value))
        }
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn temporal_words_preserve_signed_values_and_complete_types() {
        let mut types = vec![
            DataType::Date32,
            DataType::Date64,
            DataType::Time32(TimeUnit::Second),
            DataType::Time32(TimeUnit::Millisecond),
            DataType::Time64(TimeUnit::Microsecond),
            DataType::Time64(TimeUnit::Nanosecond),
        ];
        for unit in [
            TimeUnit::Second,
            TimeUnit::Millisecond,
            TimeUnit::Microsecond,
            TimeUnit::Nanosecond,
        ] {
            types.push(DataType::Duration(unit));
            types.push(DataType::Timestamp(unit, None));
            types.push(DataType::Timestamp(unit, Some("Europe/Berlin".into())));
        }
        for data_type in types {
            assert!(is_temporal_word_type(&data_type));
            let (min, max) =
                if matches!(data_type, DataType::Date32 | DataType::Time32(_)) {
                    (i64::from(i32::MIN), i64::from(i32::MAX))
                } else {
                    (i64::MIN, i64::MAX)
                };
            for raw in [min, -1, 0, 1, max] {
                let scalar = temporal_scalar_from_bits(raw as u64, &data_type).unwrap();
                assert_eq!(scalar.data_type(), data_type);
                assert_eq!(temporal_scalar_to_bits(&scalar), Some(raw as u64));
            }
            let null = ScalarValue::try_from(&data_type).unwrap();
            assert_eq!(temporal_scalar_to_bits(&null), None);
        }
        for invalid in [
            DataType::Int64,
            DataType::Time32(TimeUnit::Nanosecond),
            DataType::Time64(TimeUnit::Second),
        ] {
            assert!(!is_temporal_word_type(&invalid));
            assert_eq!(temporal_scalar_from_bits(0, &invalid), None);
        }
    }
}

use std::cmp::Ordering;

/// Add an i128 value to a register pair with DataFusion decimal-aggregate
/// wrapping semantics.
#[inline]
pub fn wrapping_add_i128_to_registers(reg: &mut [u64], val_low: u64, val_high: u64) {
    debug_assert!(reg.len() >= 2);
    let current = i128_from_words(reg[0], reg[1]);
    let value = i128_from_words(val_low, val_high);
    let (low, high) = i128_to_words(current.wrapping_add(value));
    reg[0] = low;
    reg[1] = high;
}

#[inline]
pub(crate) fn i128_from_words(low: u64, high: u64) -> i128 {
    (low as i128) | ((high as i64 as i128) << 64)
}

#[inline]
fn i128_to_words(value: i128) -> (u64, u64) {
    (value as u64, (value >> 64) as u64)
}

/// Compare an i128 value in registers against a threshold.
///
/// The high words are interpreted as signed (i64) for correct comparison
/// of negative values.
///
/// # Arguments
/// * `reg_low` - Low 64 bits of register value
/// * `reg_high` - High 64 bits of register value (as u64 bit pattern)
/// * `thresh_low` - Low 64 bits of threshold
/// * `thresh_high` - High 64 bits of threshold (as i64, signed)
#[inline]
pub fn compare_i128(
    reg_low: u64,
    reg_high: u64,
    thresh_low: u64,
    thresh_high: i64,
) -> Ordering {
    (reg_high as i64)
        .cmp(&thresh_high)
        .then_with(|| reg_low.cmp(&thresh_low))
}

#[cfg(test)]
mod arithmetic_tests {
    use super::*;

    #[test]
    fn decimal128_register_add_wraps_at_the_signed_boundary() {
        let mut registers = [0u64; 2];
        let (max_low, max_high) = i128_to_words(i128::MAX);
        registers.copy_from_slice(&[max_low, max_high]);

        wrapping_add_i128_to_registers(&mut registers, 1, 0);

        assert_eq!(i128_from_words(registers[0], registers[1]), i128::MIN);
    }
}