Skip to main content

datafusion_physical_expr_common/
datum.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use arrow::array::BooleanArray;
6use arrow::array::{Array, ArrayRef, Datum, make_array, make_comparator};
7use arrow::buffer::{BooleanBuffer, NullBuffer};
8use arrow::compute::kernels::cmp::{
9    distinct, eq, gt, gt_eq, lt, lt_eq, neq, not_distinct,
10};
11use arrow::compute::{SortOptions, ilike, like, nilike, nlike};
12use arrow::error::ArrowError;
13use datafusion_common::float_semantics::{has_float_leaf, normalize_floats};
14use datafusion_common::{Result, ScalarValue};
15use datafusion_common::{arrow_datafusion_err, assert_or_internal_err, internal_err};
16use datafusion_expr_common::columnar_value::ColumnarValue;
17use datafusion_expr_common::operator::Operator;
18use std::sync::Arc;
19
20/// Applies a binary [`Datum`] kernel `f` to `lhs` and `rhs`
21///
22/// This maps arrow-rs' [`Datum`] kernels to DataFusion's [`ColumnarValue`] abstraction
23pub fn apply(
24    lhs: &ColumnarValue,
25    rhs: &ColumnarValue,
26    f: impl Fn(&dyn Datum, &dyn Datum) -> Result<ArrayRef, ArrowError>,
27) -> Result<ColumnarValue> {
28    match (&lhs, &rhs) {
29        (ColumnarValue::Array(left), ColumnarValue::Array(right)) => {
30            Ok(ColumnarValue::Array(f(&left.as_ref(), &right.as_ref())?))
31        }
32        (ColumnarValue::Scalar(left), ColumnarValue::Array(right)) => Ok(
33            ColumnarValue::Array(f(&left.to_scalar()?, &right.as_ref())?),
34        ),
35        (ColumnarValue::Array(left), ColumnarValue::Scalar(right)) => Ok(
36            ColumnarValue::Array(f(&left.as_ref(), &right.to_scalar()?)?),
37        ),
38        (ColumnarValue::Scalar(left), ColumnarValue::Scalar(right)) => {
39            let array = f(&left.to_scalar()?, &right.to_scalar()?)?;
40            let scalar = ScalarValue::try_from_array(array.as_ref(), 0)?;
41            Ok(ColumnarValue::Scalar(scalar))
42        }
43    }
44}
45
46/// Applies a binary [`Datum`] comparison operator `op` to `lhs` and `rhs`
47pub fn apply_cmp(
48    op: Operator,
49    lhs: &ColumnarValue,
50    rhs: &ColumnarValue,
51) -> Result<ColumnarValue> {
52    if lhs.data_type().is_nested() {
53        apply_cmp_for_nested(op, lhs, rhs)
54    } else {
55        let f = match op {
56            Operator::Eq => eq,
57            Operator::NotEq => neq,
58            Operator::Lt => lt,
59            Operator::LtEq => lt_eq,
60            Operator::Gt => gt,
61            Operator::GtEq => gt_eq,
62            Operator::IsDistinctFrom => distinct,
63            Operator::IsNotDistinctFrom => not_distinct,
64
65            Operator::LikeMatch => like,
66            Operator::ILikeMatch => ilike,
67            Operator::NotLikeMatch => nlike,
68            Operator::NotILikeMatch => nilike,
69
70            _ => {
71                return internal_err!("Invalid compare operator: {}", op);
72            }
73        };
74
75        // Arrow's comparison kernels use IEEE 754 totalOrder semantics for
76        // floats, which treats `-0.0` and `+0.0` as distinct. Normalize float
77        // operands so SQL semantics (`+0.0 == -0.0`) hold. No-op for
78        // non-float types.
79        let lhs = normalize_cmp_input(lhs);
80        let rhs = normalize_cmp_input(rhs);
81        apply(&lhs, &rhs, |l, r| Ok(Arc::new(f(l, r)?)))
82    }
83}
84
85fn normalize_cmp_input(cv: &ColumnarValue) -> ColumnarValue {
86    match cv {
87        ColumnarValue::Array(a) => ColumnarValue::Array(normalize_floats(a)),
88        ColumnarValue::Scalar(s) => ColumnarValue::Scalar(s.clone().normalize()),
89    }
90}
91
92/// Applies a binary [`Datum`] comparison operator `op` to `lhs` and `rhs` for nested type like
93/// List, FixedSizeList, LargeList, Struct, Union, Map, or a dictionary of a nested type
94pub fn apply_cmp_for_nested(
95    op: Operator,
96    lhs: &ColumnarValue,
97    rhs: &ColumnarValue,
98) -> Result<ColumnarValue> {
99    let left_data_type = lhs.data_type();
100    let right_data_type = rhs.data_type();
101
102    assert_or_internal_err!(
103        matches!(
104            op,
105            Operator::Eq
106                | Operator::NotEq
107                | Operator::Lt
108                | Operator::Gt
109                | Operator::LtEq
110                | Operator::GtEq
111                | Operator::IsDistinctFrom
112                | Operator::IsNotDistinctFrom
113        ) && left_data_type.equals_datatype(&right_data_type),
114        "invalid operator or data type mismatch for nested data, op {op} left {left_data_type}, right {right_data_type}",
115    );
116
117    apply(lhs, rhs, |l, r| {
118        Ok(Arc::new(compare_op_for_nested(op, l, r)?))
119    })
120}
121
122/// Compare with eq with either nested or non-nested
123pub fn compare_with_eq(
124    lhs: &dyn Datum,
125    rhs: &dyn Datum,
126    is_nested: bool,
127) -> Result<BooleanArray> {
128    if is_nested {
129        compare_op_for_nested(Operator::Eq, lhs, rhs)
130    } else {
131        eq(lhs, rhs).map_err(|e| arrow_datafusion_err!(e))
132    }
133}
134
135fn normalize_nested_float_zero(array: &dyn Array) -> Option<ArrayRef> {
136    has_float_leaf(array.data_type())
137        .then(|| normalize_floats(&make_array(array.to_data())))
138}
139
140/// Compare on nested type List, Struct, and so on
141pub fn compare_op_for_nested(
142    op: Operator,
143    lhs: &dyn Datum,
144    rhs: &dyn Datum,
145) -> Result<BooleanArray> {
146    let (l, is_l_scalar) = lhs.get();
147    let (r, is_r_scalar) = rhs.get();
148    let l_norm = normalize_nested_float_zero(l);
149    let r_norm = normalize_nested_float_zero(r);
150    let l = l_norm.as_deref().unwrap_or(l);
151    let r = r_norm.as_deref().unwrap_or(r);
152    let l_len = l.len();
153    let r_len = r.len();
154
155    assert_or_internal_err!(l_len == r_len || is_l_scalar || is_r_scalar, "len mismatch");
156
157    let len = match is_l_scalar {
158        true => r_len,
159        false => l_len,
160    };
161
162    // fast path, if compare with one null and operator is not 'distinct', then we can return null array directly
163    if !matches!(op, Operator::IsDistinctFrom | Operator::IsNotDistinctFrom)
164        && (is_l_scalar && l.null_count() == 1 || is_r_scalar && r.null_count() == 1)
165    {
166        return Ok(BooleanArray::new_null(len));
167    }
168
169    // TODO: make SortOptions configurable
170    // we choose the default behaviour from arrow-rs which has null-first that follow spark's behaviour
171    let cmp = make_comparator(l, r, SortOptions::default())?;
172
173    let cmp_with_op = |i, j| match op {
174        Operator::Eq | Operator::IsNotDistinctFrom => cmp(i, j).is_eq(),
175        Operator::Lt => cmp(i, j).is_lt(),
176        Operator::Gt => cmp(i, j).is_gt(),
177        Operator::LtEq => !cmp(i, j).is_gt(),
178        Operator::GtEq => !cmp(i, j).is_lt(),
179        Operator::NotEq | Operator::IsDistinctFrom => !cmp(i, j).is_eq(),
180        _ => unreachable!("unexpected operator found"),
181    };
182
183    let values = match (is_l_scalar, is_r_scalar) {
184        (false, false) => BooleanBuffer::collect_bool(len, |i| cmp_with_op(i, i)),
185        (true, false) => BooleanBuffer::collect_bool(len, |i| cmp_with_op(0, i)),
186        (false, true) => BooleanBuffer::collect_bool(len, |i| cmp_with_op(i, 0)),
187        (true, true) => std::iter::once(cmp_with_op(0, 0)).collect(),
188    };
189
190    // Distinct understand how to compare with NULL
191    // i.e NULL is distinct from NULL -> false
192    if matches!(op, Operator::IsDistinctFrom | Operator::IsNotDistinctFrom) {
193        Ok(BooleanArray::new(values, None))
194    } else {
195        // If one of the side is NULL, we return NULL
196        // i.e. NULL eq NULL -> NULL
197        // For nested comparisons, we need to ensure the null buffer matches the result length
198        let nulls = match (is_l_scalar, is_r_scalar) {
199            (false, false) | (true, true) => NullBuffer::union(l.nulls(), r.nulls()),
200            (true, false) => {
201                // When left is null-scalar and right is array, expand left nulls to match result length
202                match l.nulls().filter(|nulls| nulls.is_null(0)) {
203                    Some(_) => Some(NullBuffer::new_null(len)), // Left scalar is null
204                    None => r.nulls().cloned(),                 // Left scalar is non-null
205                }
206            }
207            (false, true) => {
208                // When right is null-scalar and left is array, expand right nulls to match result length
209                match r.nulls().filter(|nulls| nulls.is_null(0)) {
210                    Some(_) => Some(NullBuffer::new_null(len)), // Right scalar is null
211                    None => l.nulls().cloned(), // Right scalar is non-null
212                }
213            }
214        };
215        Ok(BooleanArray::new(values, nulls))
216    }
217}