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.

//! Decimal averaging with scale adjustment and overflow checks matching
//! DataFusion's `AVG` accumulator semantics.

use datafusion::arrow::datatypes::{ArrowNativeType, ArrowNativeTypeOp, DecimalType};
use datafusion::common::{Result, exec_err, internal_datafusion_err};

/// Computes averages for Arrow decimal values while checking precision and
/// scale overflow, matching DataFusion's `AvgAccumulator` behavior.
pub(crate) struct DecimalAverager<T: DecimalType> {
    /// Scale factor for input sum values (`10^sum_scale`).
    sum_mul: T::Native,
    /// Scale factor for target output values (`10^target_scale`).
    target_mul: T::Native,
    /// Output decimal precision.
    target_precision: u8,
    /// Output decimal scale.
    target_scale: i8,
}

impl<T: DecimalType> DecimalAverager<T> {
    /// Creates a new averager from the input sum scale and target precision/scale.
    pub(crate) fn try_new(
        sum_scale: i8,
        target_precision: u8,
        target_scale: i8,
    ) -> Result<Self> {
        let sum_mul = T::Native::from_usize(10_usize)
            .map(|b| b.pow_wrapping(sum_scale as u32))
            .ok_or_else(|| {
                internal_datafusion_err!("Failed to compute sum_mul in DecimalAverager")
            })?;

        let target_mul = T::Native::from_usize(10_usize)
            .map(|b| b.pow_wrapping(target_scale as u32))
            .ok_or_else(|| {
                internal_datafusion_err!(
                    "Failed to compute target_mul in DecimalAverager"
                )
            })?;

        if target_mul >= sum_mul {
            Ok(Self {
                sum_mul,
                target_mul,
                target_precision,
                target_scale,
            })
        } else {
            exec_err!("Arithmetic Overflow in AvgAccumulator")
        }
    }

    /// Computes `sum / count` rescaled to `(target_precision, target_scale)`
    /// and validates the result against the target decimal precision.
    #[inline(always)]
    pub(crate) fn avg(&self, sum: T::Native, count: T::Native) -> Result<T::Native> {
        if let Ok(value) = sum.mul_checked(self.target_mul.div_wrapping(self.sum_mul)) {
            let new_value = value.div_wrapping(count);

            if T::validate_decimal_precision(
                new_value,
                self.target_precision,
                self.target_scale,
            )
            .is_ok()
            {
                Ok(new_value)
            } else {
                exec_err!("Arithmetic Overflow in AvgAccumulator")
            }
        } else {
            exec_err!("Arithmetic Overflow in AvgAccumulator")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::DecimalAverager;
    use datafusion::arrow::datatypes::Decimal128Type;

    #[test]
    fn rescales_and_divides_decimal128() {
        // Input scale 2 (e.g. 1.00 + 2.00 = 3.00 -> unscaled 300), target (10, 6)
        let avg = DecimalAverager::<Decimal128Type>::try_new(2, 10, 6).unwrap();
        // 3.00 / 2 = 1.500000 -> unscaled 1_500_000
        assert_eq!(avg.avg(300, 2).unwrap(), 1_500_000);
    }

    #[test]
    fn rejects_precision_overflow_and_shrinking_scale() {
        let avg = DecimalAverager::<Decimal128Type>::try_new(2, 3, 2).unwrap();
        // 20.00 / 2 = 10.00 -> unscaled 1000 does not fit in precision 3
        let err = avg.avg(2000, 2).unwrap_err();
        assert!(
            err.to_string()
                .contains("Arithmetic Overflow in AvgAccumulator")
        );

        let err = DecimalAverager::<Decimal128Type>::try_new(4, 10, 2)
            .err()
            .expect("shrinking target scale should fail");
        assert!(
            err.to_string()
                .contains("Arithmetic Overflow in AvgAccumulator")
        );
    }
}