Skip to main content

datafusion_physical_expr/expressions/
binary.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
5mod kernels;
6
7use crate::PhysicalExpr;
8use crate::expressions::SqlSimilarToPattern;
9use crate::expressions::translate_scalar;
10use crate::intervals::cp_solver::{propagate_arithmetic, propagate_comparison};
11use std::borrow::Cow;
12use std::cmp::Ordering;
13use std::hash::Hash;
14use std::sync::Arc;
15
16use arrow::array::*;
17use arrow::buffer::NullBuffer;
18use arrow::compute::kernels::boolean::{and_kleene, or_kleene};
19use arrow::compute::kernels::concat_elements::concat_elements_dyn;
20use arrow::compute::{SlicesIterator, cast, filter, filter_record_batch};
21use arrow::datatypes::*;
22use arrow::error::ArrowError;
23use datafusion_common::cast::as_boolean_array;
24use datafusion_common::{Result, ScalarValue, internal_err, not_impl_err};
25
26use datafusion_expr::binary::BinaryTypeCoercer;
27use datafusion_expr::interval_arithmetic::{Interval, apply_operator};
28use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
29#[expect(deprecated)]
30use datafusion_expr::statistics::Distribution::{Bernoulli, Gaussian};
31#[expect(deprecated)]
32use datafusion_expr::statistics::{
33    Distribution, combine_bernoullis, combine_gaussians,
34    create_bernoulli_from_comparison, new_generic_from_binary_op,
35};
36use datafusion_expr::{ColumnarValue, Operator};
37use datafusion_physical_expr_common::datum::{apply, apply_cmp};
38
39use kernels::{
40    bitwise_and_dyn, bitwise_and_dyn_scalar, bitwise_or_dyn, bitwise_or_dyn_scalar,
41    bitwise_shift_left_dyn, bitwise_shift_left_dyn_scalar, bitwise_shift_right_dyn,
42    bitwise_shift_right_dyn_scalar, bitwise_xor_dyn, bitwise_xor_dyn_scalar,
43    regex_match_dyn, regex_match_dyn_scalar,
44};
45
46/// Binary expression
47#[derive(Debug, Clone, Eq)]
48pub struct BinaryExpr {
49    left: Arc<dyn PhysicalExpr>,
50    op: Operator,
51    right: Arc<dyn PhysicalExpr>,
52    /// Specifies whether an error is returned on overflow or not
53    fail_on_overflow: bool,
54}
55
56// Manually derive PartialEq and Hash to work around https://github.com/rust-lang/rust/issues/78808
57impl PartialEq for BinaryExpr {
58    fn eq(&self, other: &Self) -> bool {
59        self.left.eq(&other.left)
60            && self.op.eq(&other.op)
61            && self.right.eq(&other.right)
62            && self.fail_on_overflow.eq(&other.fail_on_overflow)
63    }
64}
65impl Hash for BinaryExpr {
66    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
67        self.left.hash(state);
68        self.op.hash(state);
69        self.right.hash(state);
70        self.fail_on_overflow.hash(state);
71    }
72}
73
74impl BinaryExpr {
75    /// Create new binary expression
76    pub fn new(
77        left: Arc<dyn PhysicalExpr>,
78        op: Operator,
79        right: Arc<dyn PhysicalExpr>,
80    ) -> Self {
81        Self {
82            left,
83            op,
84            right,
85            fail_on_overflow: false,
86        }
87    }
88
89    /// Create new binary expression with explicit fail_on_overflow value
90    pub fn with_fail_on_overflow(self, fail_on_overflow: bool) -> Self {
91        Self {
92            left: self.left,
93            op: self.op,
94            right: self.right,
95            fail_on_overflow,
96        }
97    }
98
99    /// Get the left side of the binary expression
100    pub fn left(&self) -> &Arc<dyn PhysicalExpr> {
101        &self.left
102    }
103
104    /// Get the right side of the binary expression
105    pub fn right(&self) -> &Arc<dyn PhysicalExpr> {
106        &self.right
107    }
108
109    /// Get the operator for this binary expression
110    pub fn op(&self) -> &Operator {
111        &self.op
112    }
113
114    /// Mathematical intervals do not cover values produced by wrapping arithmetic.
115    fn integer_arithmetic_may_wrap(
116        &self,
117        left: &Interval,
118        right: &Interval,
119        result: &Interval,
120    ) -> bool {
121        !self.fail_on_overflow
122            && result.data_type().is_integer()
123            && matches!(
124                self.op,
125                Operator::Plus | Operator::Minus | Operator::Multiply
126            )
127            && (result.is_unbounded()
128                || unsigned_subtraction_may_underflow(self.op, left, right, result))
129    }
130
131    /// Wrapping on overflow breaks monotonicity (e.g. the sum of two
132    /// ascending `UInt8` columns can wrap back to small values), so the
133    /// derived ordering is kept only when overflow is impossible. `time ±
134    /// interval` wraps around the 24-hour clock even in checked mode, so it
135    /// never preserves ordering.
136    fn arithmetic_sort_properties(
137        &self,
138        sort_properties: SortProperties,
139        l_range: &Interval,
140        r_range: &Interval,
141        range: &Interval,
142    ) -> SortProperties {
143        if sort_properties == SortProperties::Singleton {
144            return sort_properties;
145        }
146        let wraps_in_domain = match self.op {
147            Operator::Plus => {
148                is_time_plus_interval(&l_range.data_type(), &r_range.data_type())
149            }
150            Operator::Minus => {
151                is_time_minus_interval(&l_range.data_type(), &r_range.data_type())
152            }
153            _ => false,
154        };
155        let cannot_overflow = !range.is_unbounded()
156            && !unsigned_subtraction_may_underflow(self.op, l_range, r_range, range);
157        if !wraps_in_domain && (self.fail_on_overflow || cannot_overflow) {
158            sort_properties
159        } else {
160            SortProperties::Unordered
161        }
162    }
163}
164
165/// Returns `true` unless `l_range - r_range` provably stays within an unsigned
166/// domain.
167///
168/// [`Interval`] standardizes an underflowed (i.e. `null`) lower bound of an
169/// unsigned type back to zero, so an apparently bounded result range is not
170/// enough to rule out wrapping here -- e.g. `[0, 10] - [0, 10]` over `UInt32`
171/// yields `[0, 10]` even though `0 - 10` wraps to `u32::MAX`. Compare the
172/// endpoints that produce the smallest difference instead.
173fn unsigned_subtraction_may_underflow(
174    op: Operator,
175    l_range: &Interval,
176    r_range: &Interval,
177    range: &Interval,
178) -> bool {
179    if op != Operator::Minus || !range.data_type().is_unsigned_integer() {
180        return false;
181    }
182    let (smallest_lhs, largest_rhs) = (l_range.lower(), r_range.upper());
183    if smallest_lhs.is_null() || largest_rhs.is_null() {
184        return true;
185    }
186    // Operands of differing types compare as incomparable, in which case we
187    // conservatively assume an underflow is possible.
188    !matches!(
189        smallest_lhs.partial_cmp(largest_rhs),
190        Some(Ordering::Greater | Ordering::Equal)
191    )
192}
193
194impl std::fmt::Display for BinaryExpr {
195    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
196        // Put parentheses around child binary expressions so that we can see the difference
197        // between `(a OR b) AND c` and `a OR (b AND c)`. We only insert parentheses when needed,
198        // based on operator precedence. For example, `(a AND b) OR c` and `a AND b OR c` are
199        // equivalent and the parentheses are not necessary.
200
201        fn write_child(
202            f: &mut std::fmt::Formatter,
203            expr: &dyn PhysicalExpr,
204            precedence: u8,
205        ) -> std::fmt::Result {
206            if let Some(child) = expr.downcast_ref::<BinaryExpr>() {
207                let p = child.op.precedence();
208                if p == 0 || p < precedence {
209                    write!(f, "({child})")?;
210                } else {
211                    write!(f, "{child}")?;
212                }
213            } else {
214                write!(f, "{expr}")?;
215            }
216
217            Ok(())
218        }
219
220        let precedence = self.op.precedence();
221        write_child(f, self.left.as_ref(), precedence)?;
222        write!(f, " {} ", self.op)?;
223        write_child(f, self.right.as_ref(), precedence)
224    }
225}
226
227/// Invoke a boolean kernel on a pair of arrays
228#[inline]
229fn boolean_op(
230    left: &dyn Array,
231    right: &dyn Array,
232    op: impl FnOnce(&BooleanArray, &BooleanArray) -> Result<BooleanArray, ArrowError>,
233) -> Result<Arc<dyn Array + 'static>, ArrowError> {
234    let ll = as_boolean_array(left).expect("boolean_op failed to downcast left array");
235    let rr = as_boolean_array(right).expect("boolean_op failed to downcast right array");
236    op(ll, rr).map(|t| Arc::new(t) as _)
237}
238
239/// Returns true if both operands are Date types (Date32 or Date64)
240/// Used to detect Date - Date operations which should return Int64 (days difference)
241fn is_date_minus_date(lhs: &DataType, rhs: &DataType) -> bool {
242    matches!(
243        (lhs, rhs),
244        (DataType::Date32, DataType::Date32) | (DataType::Date64, DataType::Date64)
245    )
246}
247
248/// Milliseconds per day, used for Date64 subtraction.
249const MILLIS_PER_DAY: i64 = 86_400_000;
250
251/// Evaluates `Date32 - Date32` or `Date64 - Date64`, returning the difference in
252/// whole days as `Int64`.
253///
254/// This matches the behavior of PostgreSQL, DuckDB, and MySQL, where
255/// `date - date` yields an integer day count rather than an interval.
256fn apply_date_subtraction(
257    lhs: &ColumnarValue,
258    rhs: &ColumnarValue,
259) -> Result<ColumnarValue> {
260    match (lhs.data_type(), rhs.data_type()) {
261        (DataType::Date32, DataType::Date32) => {
262            subtract_date_to_days::<Date32Type>(lhs, rhs, |l, r| l - r)
263        }
264        (DataType::Date64, DataType::Date64) => {
265            subtract_date_to_days::<Date64Type>(lhs, rhs, |l, r| {
266                l.wrapping_sub(r) / MILLIS_PER_DAY
267            })
268        }
269        (_, _) => unreachable!("apply_date_subtraction called with non-date types"),
270    }
271}
272
273/// Generic date subtraction: operates directly on the native primitive values
274/// of `T` (i32 for Date32, i64 for Date64), applying `day_diff_fn` to produce
275/// an Int64 day count.
276fn subtract_date_to_days<T: ArrowPrimitiveType>(
277    lhs: &ColumnarValue,
278    rhs: &ColumnarValue,
279    day_diff_fn: impl Fn(i64, i64) -> i64,
280) -> Result<ColumnarValue>
281where
282    T::Native: Copy + Into<i64>,
283{
284    /// Extract the date value as `i64`. Returns `None` for null scalars.
285    fn date_scalar_to_i64<P: ArrowPrimitiveType>(
286        scalar: &ScalarValue,
287    ) -> Result<Option<i64>> {
288        match scalar {
289            ScalarValue::Date32(value) if P::DATA_TYPE == DataType::Date32 => {
290                Ok(value.map(i64::from))
291            }
292            ScalarValue::Date64(value) if P::DATA_TYPE == DataType::Date64 => Ok(*value),
293            other => {
294                internal_err!(
295                    "{} date scalar expected, got: {}",
296                    P::DATA_TYPE,
297                    other.data_type()
298                )
299            }
300        }
301    }
302
303    match (lhs, rhs) {
304        (ColumnarValue::Array(left), ColumnarValue::Array(right)) => {
305            let left = left.as_primitive::<T>();
306            let right = right.as_primitive::<T>();
307            let result: Int64Array =
308                arrow::compute::binary::<_, _, _, Int64Type>(left, right, |l, r| {
309                    day_diff_fn(l.into(), r.into())
310                })?;
311            Ok(ColumnarValue::Array(Arc::new(result)))
312        }
313        (ColumnarValue::Array(left), ColumnarValue::Scalar(right)) => {
314            let left = left.as_primitive::<T>();
315            match date_scalar_to_i64::<T>(right)? {
316                Some(right_val) => {
317                    let result: Int64Array =
318                        left.unary(|l| day_diff_fn(l.into(), right_val));
319                    Ok(ColumnarValue::Array(Arc::new(result)))
320                }
321                None => Ok(ColumnarValue::Scalar(ScalarValue::Int64(None))),
322            }
323        }
324        (ColumnarValue::Scalar(left), ColumnarValue::Array(right)) => {
325            let right = right.as_primitive::<T>();
326            match date_scalar_to_i64::<T>(left)? {
327                Some(left_val) => {
328                    let result: Int64Array =
329                        right.unary(|r| day_diff_fn(left_val, r.into()));
330                    Ok(ColumnarValue::Array(Arc::new(result)))
331                }
332                None => Ok(ColumnarValue::Scalar(ScalarValue::Int64(None))),
333            }
334        }
335        (ColumnarValue::Scalar(left), ColumnarValue::Scalar(right)) => {
336            let left_val = date_scalar_to_i64::<T>(left)?;
337            let right_val = date_scalar_to_i64::<T>(right)?;
338            Ok(ColumnarValue::Scalar(ScalarValue::Int64(
339                left_val.zip(right_val).map(|(l, r)| day_diff_fn(l, r)),
340            )))
341        }
342    }
343}
344
345/// Returns true for `time + interval` or `interval + time`.
346fn is_time_plus_interval(lhs: &DataType, rhs: &DataType) -> bool {
347    matches!(
348        (lhs, rhs),
349        (
350            DataType::Time32(_) | DataType::Time64(_),
351            DataType::Interval(_)
352        ) | (
353            DataType::Interval(_),
354            DataType::Time32(_) | DataType::Time64(_)
355        )
356    )
357}
358
359/// Returns true for `time - interval`.
360fn is_time_minus_interval(lhs: &DataType, rhs: &DataType) -> bool {
361    matches!(
362        (lhs, rhs),
363        (
364            DataType::Time32(_) | DataType::Time64(_),
365            DataType::Interval(_)
366        )
367    )
368}
369
370/// Evaluates `time + interval`, `interval + time`, or `time - interval`, returning a
371/// `time` wrapped within the 24-hour clock to match PostgreSQL and DuckDB (e.g.
372/// `time '23:30' + interval '2 hours'` is `01:30:00`). arrow's arithmetic kernels do
373/// not implement time-of-day arithmetic, so it is handled here.
374///
375/// The result keeps the input time's unit; the interval (normalized to `MonthDayNano`
376/// by the coercion layer) is applied at nanosecond precision and floored to that unit,
377/// mirroring `timestamp(unit) + interval`. Only the sub-day portion of the interval
378/// affects a time-of-day -- whole months and days are ignored, matching PostgreSQL. The
379/// floor is applied after the sign, so `time(s) + interval '1 nanosecond'` is a no-op
380/// while `time(s) - interval '1 nanosecond'` rolls back a second, exactly as the
381/// timestamp case does.
382fn apply_time_interval(
383    lhs: &ColumnarValue,
384    rhs: &ColumnarValue,
385    subtract: bool,
386) -> Result<ColumnarValue> {
387    // The `time` operand determines the result type; the other is the interval.
388    let (time, interval) = if matches!(lhs.data_type(), DataType::Interval(_)) {
389        (rhs, lhs)
390    } else {
391        (lhs, rhs)
392    };
393
394    // Dispatch on the time unit; `ns_per_unit` converts the interval's nanoseconds to
395    // that unit, and the arithmetic is done (and wrapped) at that resolution.
396    match time.data_type() {
397        DataType::Time32(TimeUnit::Second) => wrap_time_interval::<Time32SecondType>(
398            time,
399            interval,
400            subtract,
401            1_000_000_000,
402        ),
403        DataType::Time32(TimeUnit::Millisecond) => {
404            wrap_time_interval::<Time32MillisecondType>(
405                time, interval, subtract, 1_000_000,
406            )
407        }
408        DataType::Time64(TimeUnit::Microsecond) => {
409            wrap_time_interval::<Time64MicrosecondType>(time, interval, subtract, 1_000)
410        }
411        DataType::Time64(TimeUnit::Nanosecond) => {
412            wrap_time_interval::<Time64NanosecondType>(time, interval, subtract, 1)
413        }
414        other => internal_err!("time operand expected, got: {other}"),
415    }
416}
417
418/// Adds or subtracts an interval to/from a `time` of arrow primitive type `T`, wrapping
419/// the result within the 24-hour clock and keeping the type `T`. `ns_per_unit` is the
420/// number of nanoseconds in one unit of `T` (e.g. `1_000` for microseconds).
421fn wrap_time_interval<T: ArrowPrimitiveType>(
422    time: &ColumnarValue,
423    interval: &ColumnarValue,
424    subtract: bool,
425    ns_per_unit: i64,
426) -> Result<ColumnarValue>
427where
428    T::Native: Copy + Into<i64> + TryFrom<i64>,
429{
430    /// Nanoseconds in a 24-hour day.
431    const DAY_NANOS: i64 = 86_400_000_000_000;
432    // Units in a 24-hour day, at `T`'s resolution.
433    let day_units = DAY_NANOS / ns_per_unit;
434
435    // Wraps `time ± interval` into `[0, day_units)`. The interval is reduced modulo a day
436    // (so the sum stays within `i64`), applied at nanosecond precision, then floored to
437    // `T`'s unit -- matching `timestamp(unit) ± interval`. Because the floor is applied
438    // after the sign, `time(s) - interval '1 nanosecond'` rolls back a full second, just
439    // as the timestamp case does, while `time(s) + interval '1 nanosecond'` is a no-op.
440    // `div_euclid`/`rem_euclid` floor toward negative infinity, so the wrapped value stays
441    // in `[0, day_units)`, which always fits `T::Native`.
442    let wrap = |time_unit: i64, iv: IntervalMonthDayNano| -> T::Native {
443        let iv_ns = iv.nanoseconds % DAY_NANOS;
444        let signed_ns = if subtract { -iv_ns } else { iv_ns };
445        let delta = signed_ns.div_euclid(ns_per_unit);
446        let wrapped = (time_unit + delta).rem_euclid(day_units);
447        T::Native::try_from(wrapped).unwrap_or_default()
448    };
449
450    /// Extracts an `Interval(MonthDayNano)` scalar.
451    fn interval_scalar(scalar: &ScalarValue) -> Result<Option<IntervalMonthDayNano>> {
452        match scalar {
453            ScalarValue::IntervalMonthDayNano(value) => Ok(*value),
454            other => internal_err!(
455                "Interval(MonthDayNano) scalar expected, got: {}",
456                other.data_type()
457            ),
458        }
459    }
460
461    /// Extracts a time scalar as its unit count since midnight.
462    fn time_scalar_units(scalar: &ScalarValue) -> Result<Option<i64>> {
463        match scalar {
464            ScalarValue::Time32Second(value) | ScalarValue::Time32Millisecond(value) => {
465                Ok(value.map(i64::from))
466            }
467            ScalarValue::Time64Microsecond(value)
468            | ScalarValue::Time64Nanosecond(value) => Ok(*value),
469            other => {
470                internal_err!("time scalar expected, got: {}", other.data_type())
471            }
472        }
473    }
474
475    /// Builds a time scalar of type `P` from a unit count.
476    fn time_scalar<P: ArrowPrimitiveType>(value: Option<i64>) -> ScalarValue {
477        match P::DATA_TYPE {
478            DataType::Time32(TimeUnit::Second) => {
479                ScalarValue::Time32Second(value.map(|v| v as i32))
480            }
481            DataType::Time32(TimeUnit::Millisecond) => {
482                ScalarValue::Time32Millisecond(value.map(|v| v as i32))
483            }
484            DataType::Time64(TimeUnit::Microsecond) => {
485                ScalarValue::Time64Microsecond(value)
486            }
487            _ => ScalarValue::Time64Nanosecond(value),
488        }
489    }
490
491    match (time, interval) {
492        (ColumnarValue::Array(time), ColumnarValue::Array(interval)) => {
493            let time = time.as_primitive::<T>();
494            let interval = interval.as_primitive::<IntervalMonthDayNanoType>();
495            let result: PrimitiveArray<T> =
496                arrow::compute::binary(time, interval, |t, iv| wrap(t.into(), iv))?;
497            Ok(ColumnarValue::Array(Arc::new(result)))
498        }
499        (ColumnarValue::Array(time), ColumnarValue::Scalar(interval)) => {
500            let time = time.as_primitive::<T>();
501            match interval_scalar(interval)? {
502                Some(iv) => {
503                    let result: PrimitiveArray<T> = time.unary(|t| wrap(t.into(), iv));
504                    Ok(ColumnarValue::Array(Arc::new(result)))
505                }
506                None => Ok(ColumnarValue::Scalar(time_scalar::<T>(None))),
507            }
508        }
509        (ColumnarValue::Scalar(time), ColumnarValue::Array(interval)) => {
510            let interval = interval.as_primitive::<IntervalMonthDayNanoType>();
511            match time_scalar_units(time)? {
512                Some(t) => {
513                    let result: PrimitiveArray<T> = interval.unary(|iv| wrap(t, iv));
514                    Ok(ColumnarValue::Array(Arc::new(result)))
515                }
516                None => Ok(ColumnarValue::Scalar(time_scalar::<T>(None))),
517            }
518        }
519        (ColumnarValue::Scalar(time), ColumnarValue::Scalar(interval)) => {
520            let result = time_scalar_units(time)?
521                .zip(interval_scalar(interval)?)
522                .map(|(t, iv)| wrap(t, iv).into());
523            Ok(ColumnarValue::Scalar(time_scalar::<T>(result)))
524        }
525    }
526}
527
528impl PhysicalExpr for BinaryExpr {
529    fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
530        BinaryTypeCoercer::new(
531            &self.left.data_type(input_schema)?,
532            &self.op,
533            &self.right.data_type(input_schema)?,
534        )
535        .get_result_type()
536    }
537
538    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
539        match self.op {
540            Operator::IsDistinctFrom | Operator::IsNotDistinctFrom => Ok(false),
541            _ => {
542                Ok(self.left.nullable(input_schema)?
543                    || self.right.nullable(input_schema)?)
544            }
545        }
546    }
547
548    fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
549        use arrow::compute::kernels::numeric::*;
550
551        if self.op == Operator::And {
552            return self.evaluate_conjunction(batch);
553        }
554
555        // Evaluate left-hand side expression.
556        let lhs = self.left.evaluate(batch)?;
557
558        // Check if we can apply short-circuit evaluation.
559        match check_short_circuit(&lhs, &self.op) {
560            ShortCircuitStrategy::None => {}
561            ShortCircuitStrategy::ReturnLeft => return Ok(lhs),
562            ShortCircuitStrategy::ReturnRight => {
563                let rhs = self.right.evaluate(batch)?;
564                return Ok(rhs);
565            }
566            ShortCircuitStrategy::PreSelection { mask, fill_value } => {
567                // `mask` selects the rows whose result depends on the RHS; the
568                // unselected rows are all `fill_value` (see `ShortCircuitStrategy`).
569                //
570                // Use `filter_record_batch` directly because `evaluate_selection`
571                // scatters the RHS back to the original batch length.
572                let selection_batch = filter_record_batch(batch, &mask)?;
573                let right_ret = self.right.evaluate(&selection_batch)?;
574
575                match &right_ret {
576                    ColumnarValue::Array(array) => {
577                        let boolean_array = array.as_boolean();
578                        // If the RHS is uniform on the selected rows, the whole
579                        // expression collapses and no scatter is needed.
580                        if boolean_array.null_count() == 0 {
581                            let rhs_value = if !boolean_array.has_false() {
582                                Some(true)
583                            } else if !boolean_array.has_true() {
584                                Some(false)
585                            } else {
586                                None
587                            };
588                            if let Some(rhs_value) = rhs_value {
589                                return Ok(uniform_pre_selection_result(
590                                    rhs_value, fill_value, lhs,
591                                ));
592                            }
593                        }
594
595                        return pre_selection_scatter(
596                            &mask,
597                            Some(boolean_array),
598                            fill_value,
599                        );
600                    }
601                    ColumnarValue::Scalar(scalar) => {
602                        if let ScalarValue::Boolean(v) = scalar {
603                            // A scalar RHS applies uniformly to all selected rows.
604                            if let Some(v) = v {
605                                return Ok(uniform_pre_selection_result(
606                                    *v, fill_value, lhs,
607                                ));
608                            } else {
609                                return pre_selection_scatter(&mask, None, fill_value);
610                            }
611                        } else {
612                            return internal_err!(
613                                "Expected boolean scalar value, found: {right_ret:?}"
614                            );
615                        }
616                    }
617                }
618            }
619        }
620
621        let rhs = self.right.evaluate(batch)?;
622        let left_data_type = lhs.data_type();
623        let right_data_type = rhs.data_type();
624
625        let schema = batch.schema();
626        let input_schema = schema.as_ref();
627
628        match self.op {
629            // `time ± interval` returns a wrapped `time` (PostgreSQL/DuckDB
630            // semantics); arrow's arithmetic kernels don't implement it.
631            Operator::Plus
632                if is_time_plus_interval(&left_data_type, &right_data_type) =>
633            {
634                return apply_time_interval(&lhs, &rhs, false);
635            }
636            Operator::Minus
637                if is_time_minus_interval(&left_data_type, &right_data_type) =>
638            {
639                return apply_time_interval(&lhs, &rhs, true);
640            }
641            Operator::Plus if self.fail_on_overflow => return apply(&lhs, &rhs, add),
642            Operator::Plus => return apply(&lhs, &rhs, add_wrapping),
643            // Special case: Date - Date returns Int64 (days difference)
644            // This aligns with PostgreSQL, DuckDB, and MySQL behavior
645            Operator::Minus if is_date_minus_date(&left_data_type, &right_data_type) => {
646                return apply_date_subtraction(&lhs, &rhs);
647            }
648            Operator::Minus if self.fail_on_overflow => return apply(&lhs, &rhs, sub),
649            Operator::Minus => return apply(&lhs, &rhs, sub_wrapping),
650            Operator::Multiply if self.fail_on_overflow => return apply(&lhs, &rhs, mul),
651            Operator::Multiply => return apply(&lhs, &rhs, mul_wrapping),
652            Operator::Divide => return apply(&lhs, &rhs, div),
653            Operator::Modulo => return apply(&lhs, &rhs, rem),
654
655            Operator::Eq
656            | Operator::NotEq
657            | Operator::Lt
658            | Operator::Gt
659            | Operator::LtEq
660            | Operator::GtEq
661            | Operator::IsDistinctFrom
662            | Operator::IsNotDistinctFrom
663            | Operator::LikeMatch
664            | Operator::ILikeMatch
665            | Operator::NotLikeMatch
666            | Operator::NotILikeMatch => {
667                return apply_cmp(self.op, &lhs, &rhs);
668            }
669            _ => {}
670        }
671
672        let result_type = self.data_type(input_schema)?;
673
674        // If the left-hand side is an array and the right-hand side is a non-null scalar, try the optimized kernel.
675        if let (ColumnarValue::Array(array), ColumnarValue::Scalar(scalar)) = (&lhs, &rhs)
676            && !scalar.is_null()
677            && let Some(result_array) =
678                self.evaluate_array_scalar(array, scalar.clone())?
679        {
680            let final_array = result_array
681                .and_then(|a| to_result_type_array(&self.op, a, &result_type));
682            return final_array.map(ColumnarValue::Array);
683        }
684
685        // if both arrays or both literals - extract arrays and continue execution
686        let (left, right) = (
687            lhs.into_array(batch.num_rows())?,
688            rhs.into_array(batch.num_rows())?,
689        );
690        self.evaluate_with_resolved_args(left, &left_data_type, right, &right_data_type)
691            .map(ColumnarValue::Array)
692    }
693
694    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
695        vec![&self.left, &self.right]
696    }
697
698    fn with_new_children(
699        self: Arc<Self>,
700        children: Vec<Arc<dyn PhysicalExpr>>,
701    ) -> Result<Arc<dyn PhysicalExpr>> {
702        Ok(Arc::new(
703            BinaryExpr::new(Arc::clone(&children[0]), self.op, Arc::clone(&children[1]))
704                .with_fail_on_overflow(self.fail_on_overflow),
705        ))
706    }
707
708    fn evaluate_bounds(&self, children: &[&Interval]) -> Result<Interval> {
709        // Get children intervals:
710        let left_interval = children[0];
711        let right_interval = children[1];
712        // Calculate current node's interval:
713        let result = apply_operator(&self.op, left_interval, right_interval)?;
714        if self.integer_arithmetic_may_wrap(left_interval, right_interval, &result) {
715            Interval::make_unbounded(&result.data_type())
716        } else {
717            Ok(result)
718        }
719    }
720
721    fn propagate_constraints(
722        &self,
723        interval: &Interval,
724        children: &[&Interval],
725    ) -> Result<Option<Vec<Interval>>> {
726        // Get children intervals.
727        let left_interval = children[0];
728        let right_interval = children[1];
729
730        if left_interval.data_type().is_integer()
731            && right_interval.data_type().is_integer()
732            && matches!(
733                self.op,
734                Operator::Plus | Operator::Minus | Operator::Multiply | Operator::Divide
735            )
736        {
737            // Integer division truncates: a / 2 = 1 permits both 2 and 3.
738            // Wrapping arithmetic is likewise not invertible over mathematical
739            // intervals. Keep the input domains rather than exclude valid rows.
740            let contains_zero = |range: &Interval| -> Result<bool> {
741                range.contains_value(ScalarValue::new_zero(&range.data_type())?)
742            };
743            // If an operand can be zero, a zero product does not constrain
744            // the other operand. Dividing the parent interval loses that case.
745            let zero_product = self.op == Operator::Multiply
746                && contains_zero(interval)?
747                && (contains_zero(left_interval)? || contains_zero(right_interval)?);
748            if self.op == Operator::Divide
749                || zero_product
750                || self.integer_arithmetic_may_wrap(
751                    left_interval,
752                    right_interval,
753                    &apply_operator(&self.op, left_interval, right_interval)?,
754                )
755            {
756                return Ok(Some(vec![]));
757            }
758        }
759
760        if self.op.eq(&Operator::And) {
761            if interval.eq(&Interval::TRUE) {
762                // A certainly true logical conjunction can only derive from possibly
763                // true operands. Otherwise, we prove infeasibility.
764                Ok((!left_interval.eq(&Interval::FALSE)
765                    && !right_interval.eq(&Interval::FALSE))
766                .then(|| vec![Interval::TRUE, Interval::TRUE]))
767            } else if interval.eq(&Interval::FALSE) {
768                // If the logical conjunction is certainly false, one of the
769                // operands must be false. However, it's not always possible to
770                // determine which operand is false, leading to different scenarios.
771
772                // If one operand is certainly true and the other one is uncertain,
773                // then the latter must be certainly false.
774                if left_interval.eq(&Interval::TRUE)
775                    && right_interval.eq(&Interval::TRUE_OR_FALSE)
776                {
777                    Ok(Some(vec![Interval::TRUE, Interval::FALSE]))
778                } else if right_interval.eq(&Interval::TRUE)
779                    && left_interval.eq(&Interval::TRUE_OR_FALSE)
780                {
781                    Ok(Some(vec![Interval::FALSE, Interval::TRUE]))
782                }
783                // If both children are uncertain, or if one is certainly false,
784                // we cannot conclusively refine their intervals. In this case,
785                // propagation does not result in any interval changes.
786                else {
787                    Ok(Some(vec![]))
788                }
789            } else {
790                // An uncertain logical conjunction result can not shrink the
791                // end-points of its children.
792                Ok(Some(vec![]))
793            }
794        } else if self.op.eq(&Operator::Or) {
795            if interval.eq(&Interval::FALSE) {
796                // A certainly false logical disjunction can only derive from certainly
797                // false operands. Otherwise, we prove infeasibility.
798                Ok((!left_interval.eq(&Interval::TRUE)
799                    && !right_interval.eq(&Interval::TRUE))
800                .then(|| vec![Interval::FALSE, Interval::FALSE]))
801            } else if interval.eq(&Interval::TRUE) {
802                // If the logical disjunction is certainly true, one of the
803                // operands must be true. However, it's not always possible to
804                // determine which operand is true, leading to different scenarios.
805
806                // If one operand is certainly false and the other one is uncertain,
807                // then the latter must be certainly true.
808                if left_interval.eq(&Interval::FALSE)
809                    && right_interval.eq(&Interval::TRUE_OR_FALSE)
810                {
811                    Ok(Some(vec![Interval::FALSE, Interval::TRUE]))
812                } else if right_interval.eq(&Interval::FALSE)
813                    && left_interval.eq(&Interval::TRUE_OR_FALSE)
814                {
815                    Ok(Some(vec![Interval::TRUE, Interval::FALSE]))
816                }
817                // If both children are uncertain, or if one is certainly true,
818                // we cannot conclusively refine their intervals. In this case,
819                // propagation does not result in any interval changes.
820                else {
821                    Ok(Some(vec![]))
822                }
823            } else {
824                // An uncertain logical disjunction result can not shrink the
825                // end-points of its children.
826                Ok(Some(vec![]))
827            }
828        } else if self.op.supports_propagation() {
829            Ok(
830                propagate_comparison(&self.op, interval, left_interval, right_interval)?
831                    .map(|(left, right)| vec![left, right]),
832            )
833        } else {
834            Ok(
835                propagate_arithmetic(&self.op, interval, left_interval, right_interval)?
836                    .map(|(left, right)| vec![left, right]),
837            )
838        }
839    }
840
841    #[expect(deprecated)]
842    fn evaluate_statistics(&self, children: &[&Distribution]) -> Result<Distribution> {
843        let (left, right) = (children[0], children[1]);
844
845        if self.op.is_numerical_operators() {
846            // We might be able to construct the output statistics more accurately,
847            // without falling back to an unknown distribution, if we are dealing
848            // with Gaussian distributions and numerical operations.
849            if let (Gaussian(left), Gaussian(right)) = (left, right)
850                && let Some(result) = combine_gaussians(&self.op, left, right)?
851            {
852                return Ok(Gaussian(result));
853            }
854        } else if self.op.is_logic_operator() {
855            // If we are dealing with logical operators, we expect (and can only
856            // operate on) Bernoulli distributions.
857            return if let (Bernoulli(left), Bernoulli(right)) = (left, right) {
858                combine_bernoullis(&self.op, left, right).map(Bernoulli)
859            } else {
860                internal_err!(
861                    "Logical operators are only compatible with `Bernoulli` distributions"
862                )
863            };
864        } else if self.op.supports_propagation() {
865            // If we are handling comparison operators, we expect (and can only
866            // operate on) numeric distributions.
867            return create_bernoulli_from_comparison(&self.op, left, right);
868        }
869        // Fall back to an unknown distribution with only summary statistics:
870        new_generic_from_binary_op(&self.op, left, right)
871    }
872
873    /// For each operator, [`BinaryExpr`] has distinct rules.
874    /// TODO: There may be rules specific to some data types and expression ranges.
875    fn get_properties(&self, children: &[ExprProperties]) -> Result<ExprProperties> {
876        let (l_order, l_range) = (children[0].sort_properties, &children[0].range);
877        let (r_order, r_range) = (children[1].sort_properties, &children[1].range);
878        match self.op() {
879            Operator::Plus => {
880                let range = self.evaluate_bounds(&[l_range, r_range])?;
881                Ok(ExprProperties {
882                    sort_properties: self.arithmetic_sort_properties(
883                        l_order.add(&r_order),
884                        l_range,
885                        r_range,
886                        &range,
887                    ),
888                    range,
889                    preserves_lex_ordering: false,
890                    strictly_order_preserving: false,
891                })
892            }
893            Operator::Minus => {
894                let range = self.evaluate_bounds(&[l_range, r_range])?;
895                Ok(ExprProperties {
896                    sort_properties: self.arithmetic_sort_properties(
897                        l_order.sub(&r_order),
898                        l_range,
899                        r_range,
900                        &range,
901                    ),
902                    range,
903                    preserves_lex_ordering: false,
904                    strictly_order_preserving: false,
905                })
906            }
907            Operator::Gt => Ok(ExprProperties {
908                sort_properties: l_order.gt_or_gteq(&r_order),
909                range: l_range.gt(r_range)?,
910                preserves_lex_ordering: false,
911                strictly_order_preserving: false,
912            }),
913            Operator::GtEq => Ok(ExprProperties {
914                sort_properties: l_order.gt_or_gteq(&r_order),
915                range: l_range.gt_eq(r_range)?,
916                preserves_lex_ordering: false,
917                strictly_order_preserving: false,
918            }),
919            Operator::Lt => Ok(ExprProperties {
920                sort_properties: r_order.gt_or_gteq(&l_order),
921                range: l_range.lt(r_range)?,
922                preserves_lex_ordering: false,
923                strictly_order_preserving: false,
924            }),
925            Operator::LtEq => Ok(ExprProperties {
926                sort_properties: r_order.gt_or_gteq(&l_order),
927                range: l_range.lt_eq(r_range)?,
928                preserves_lex_ordering: false,
929                strictly_order_preserving: false,
930            }),
931            Operator::And => Ok(ExprProperties {
932                sort_properties: l_order.and(&r_order),
933                range: l_range.and(r_range)?,
934                preserves_lex_ordering: false,
935                strictly_order_preserving: false,
936            }),
937            Operator::Or => Ok(ExprProperties {
938                sort_properties: l_order.or(&r_order),
939                range: l_range.or(r_range)?,
940                preserves_lex_ordering: false,
941                strictly_order_preserving: false,
942            }),
943            _ => Ok(ExprProperties::new_unknown()),
944        }
945    }
946
947    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
948        fn write_child(
949            f: &mut std::fmt::Formatter,
950            expr: &dyn PhysicalExpr,
951            precedence: u8,
952        ) -> std::fmt::Result {
953            if let Some(child) = expr.downcast_ref::<BinaryExpr>() {
954                let p = child.op.precedence();
955                if p == 0 || p < precedence {
956                    write!(f, "(")?;
957                    child.fmt_sql(f)?;
958                    write!(f, ")")
959                } else {
960                    child.fmt_sql(f)
961                }
962            } else {
963                expr.fmt_sql(f)
964            }
965        }
966
967        let precedence = self.op.precedence();
968        write_child(f, self.left.as_ref(), precedence)?;
969        write!(f, " {} ", self.op)?;
970        write_child(f, self.right.as_ref(), precedence)
971    }
972
973    #[cfg(feature = "proto")]
974    fn try_to_proto(
975        &self,
976        ctx: &datafusion_physical_expr_common::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
977    ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalExprNode>> {
978        use datafusion_proto_models::protobuf;
979
980        let Self {
981            left,
982            op,
983            right,
984            fail_on_overflow,
985        } = self;
986
987        // Linearize a nested binary expression tree with the same operator and
988        // overflow policy into flat operands to avoid deep recursion in proto.
989        let mut operand_refs: Vec<&Arc<dyn PhysicalExpr>> = vec![right];
990        let mut current_left = left;
991        loop {
992            match current_left.downcast_ref::<BinaryExpr>() {
993                Some(bin)
994                    if bin.op == *op && bin.fail_on_overflow == *fail_on_overflow =>
995                {
996                    operand_refs.push(&bin.right);
997                    current_left = &bin.left;
998                }
999                _ => {
1000                    operand_refs.push(current_left);
1001                    break;
1002                }
1003            }
1004        }
1005        // Reverse so operands are ordered from left innermost to right outermost.
1006        operand_refs.reverse();
1007
1008        let operands = ctx.encode_children_expressions(operand_refs)?;
1009
1010        Ok(Some(protobuf::PhysicalExprNode {
1011            expr_id: None,
1012            expr_type: Some(protobuf::physical_expr_node::ExprType::BinaryExpr(
1013                Box::new(protobuf::PhysicalBinaryExprNode {
1014                    l: None,
1015                    r: None,
1016                    op: format!("{op:?}"),
1017                    operands,
1018                    fail_on_overflow: *fail_on_overflow,
1019                }),
1020            )),
1021        }))
1022    }
1023}
1024
1025#[cfg(feature = "proto")]
1026impl BinaryExpr {
1027    /// Reconstruct a [`BinaryExpr`] (or a left-deep tree of them when the proto
1028    /// uses the linearized `operands` form) from its protobuf representation.
1029    ///
1030    /// Takes the whole [`PhysicalExprNode`] — the exact inverse of what
1031    /// [`PhysicalExpr::try_to_proto`] produces — so every expression's
1032    /// `try_from_proto` shares one signature. The operator string is parsed
1033    /// via the canonical [`Operator::from_proto_name`] mapping, so no `op`
1034    /// argument needs to be threaded in by the caller.
1035    ///
1036    /// [`PhysicalExprNode`]: datafusion_proto_models::protobuf::PhysicalExprNode
1037    /// [`PhysicalExpr::try_to_proto`]: datafusion_physical_expr_common::physical_expr::PhysicalExpr::try_to_proto
1038    /// [`PhysicalExprDecodeCtx::decode`]: datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx::decode
1039    pub fn try_from_proto(
1040        node: &datafusion_proto_models::protobuf::PhysicalExprNode,
1041        ctx: &datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
1042    ) -> Result<Arc<dyn PhysicalExpr>> {
1043        use datafusion_physical_expr_common::expect_expr_variant;
1044        use datafusion_proto_models::protobuf;
1045        let node = expect_expr_variant!(
1046            node,
1047            protobuf::physical_expr_node::ExprType::BinaryExpr,
1048            "BinaryExpr",
1049        );
1050        let protobuf::PhysicalBinaryExprNode {
1051            l,
1052            r,
1053            op,
1054            operands,
1055            fail_on_overflow,
1056        } = node.as_ref();
1057        let op = Operator::from_proto_name(op).ok_or_else(|| {
1058            datafusion_common::DataFusionError::Internal(format!(
1059                "Unsupported binary operator '{op}'"
1060            ))
1061        })?;
1062
1063        if !operands.is_empty() {
1064            // New linearized format: reduce the flat operands list back into
1065            // a nested binary expression tree.
1066            let operands = ctx.decode_children_expressions(operands)?;
1067
1068            if operands.len() < 2 {
1069                return internal_err!(
1070                    "A binary expression must always have at least 2 operands"
1071                );
1072            }
1073
1074            Ok(operands
1075                .into_iter()
1076                .reduce(|left, right| {
1077                    Arc::new(
1078                        BinaryExpr::new(left, op, right)
1079                            .with_fail_on_overflow(*fail_on_overflow),
1080                    ) as Arc<dyn PhysicalExpr>
1081                })
1082                .expect("Binary expression could not be reduced to a single expression."))
1083        } else {
1084            // Legacy format with l/r fields.
1085            let left =
1086                ctx.decode_required_expression(l.as_deref(), "BinaryExpr", "left")?;
1087            let right =
1088                ctx.decode_required_expression(r.as_deref(), "BinaryExpr", "right")?;
1089            Ok(Arc::new(
1090                BinaryExpr::new(left, op, right).with_fail_on_overflow(*fail_on_overflow),
1091            ))
1092        }
1093    }
1094}
1095
1096/// Casts dictionary array to result type for binary numerical operators. Such operators
1097/// between array and scalar produce a dictionary array other than primitive array of the
1098/// same operators between array and array. This leads to inconsistent result types causing
1099/// errors in the following query execution. For such operators between array and scalar,
1100/// we cast the dictionary array to primitive array.
1101fn to_result_type_array(
1102    op: &Operator,
1103    array: ArrayRef,
1104    result_type: &DataType,
1105) -> Result<ArrayRef> {
1106    if array.data_type() == result_type {
1107        Ok(array)
1108    } else if op.is_numerical_operators() {
1109        match array.data_type() {
1110            DataType::Dictionary(_, value_type) => {
1111                if value_type.as_ref() == result_type {
1112                    Ok(cast(&array, result_type)?)
1113                } else {
1114                    internal_err!(
1115                        "Incompatible Dictionary value type {value_type} with result type {result_type} of Binary operator {op:?}"
1116                    )
1117                }
1118            }
1119            _ => Ok(array),
1120        }
1121    } else {
1122        Ok(array)
1123    }
1124}
1125
1126impl BinaryExpr {
1127    /// Evaluate the expression of the left input is an array and
1128    /// right is literal - use scalar operations
1129    fn evaluate_array_scalar(
1130        &self,
1131        array: &dyn Array,
1132        scalar: ScalarValue,
1133    ) -> Result<Option<Result<ArrayRef>>> {
1134        use Operator::*;
1135        let scalar_result = match &self.op {
1136            RegexMatch => regex_match_dyn_scalar(array, &scalar, false, false),
1137            RegexIMatch => regex_match_dyn_scalar(array, &scalar, false, true),
1138            RegexNotMatch => regex_match_dyn_scalar(array, &scalar, true, false),
1139            RegexNotIMatch => regex_match_dyn_scalar(array, &scalar, true, true),
1140            BitwiseAnd => bitwise_and_dyn_scalar(array, scalar),
1141            BitwiseOr => bitwise_or_dyn_scalar(array, scalar),
1142            BitwiseXor => bitwise_xor_dyn_scalar(array, scalar),
1143            BitwiseShiftRight => bitwise_shift_right_dyn_scalar(array, scalar),
1144            BitwiseShiftLeft => bitwise_shift_left_dyn_scalar(array, scalar),
1145            // if scalar operation is not supported - fallback to array implementation
1146            _ => None,
1147        };
1148
1149        Ok(scalar_result)
1150    }
1151
1152    fn evaluate_with_resolved_args(
1153        &self,
1154        left: Arc<dyn Array>,
1155        left_data_type: &DataType,
1156        right: Arc<dyn Array>,
1157        right_data_type: &DataType,
1158    ) -> Result<ArrayRef> {
1159        use Operator::*;
1160        match &self.op {
1161            IsDistinctFrom | IsNotDistinctFrom | Lt | LtEq | Gt | GtEq | Eq | NotEq
1162            | Plus | Minus | Multiply | Divide | Modulo | LikeMatch | ILikeMatch
1163            | NotLikeMatch | NotILikeMatch | And => unreachable!(),
1164            Or => {
1165                if left_data_type == &DataType::Boolean {
1166                    Ok(boolean_op(&left, &right, or_kleene)?)
1167                } else {
1168                    internal_err!(
1169                        "Cannot evaluate binary expression {:?} with types {:?} and {:?}",
1170                        self.op,
1171                        left_data_type,
1172                        right_data_type
1173                    )
1174                }
1175            }
1176            RegexMatch => regex_match_dyn(&left, &right, false, false),
1177            RegexIMatch => regex_match_dyn(&left, &right, false, true),
1178            RegexNotMatch => regex_match_dyn(&left, &right, true, false),
1179            RegexNotIMatch => regex_match_dyn(&left, &right, true, true),
1180            BitwiseAnd => bitwise_and_dyn(left, right),
1181            BitwiseOr => bitwise_or_dyn(left, right),
1182            BitwiseXor => bitwise_xor_dyn(left, right),
1183            BitwiseShiftRight => bitwise_shift_right_dyn(left, right),
1184            BitwiseShiftLeft => bitwise_shift_left_dyn(left, right),
1185            StringConcat => concat_elements_dyn(&left, &right).map_err(|e| e.into()),
1186            AtArrow | ArrowAt | Arrow | LongArrow | HashArrow | HashLongArrow | AtAt
1187            | HashMinus | AtQuestion | Question | QuestionAnd | QuestionPipe
1188            | IntegerDivide | Colon => {
1189                not_impl_err!(
1190                    "Binary operator '{:?}' is not supported in the physical expr",
1191                    self.op
1192                )
1193            }
1194        }
1195    }
1196
1197    /// Evaluates nested `AND`s together to avoid repeated filtering (#25035).
1198    ///
1199    /// When at most [`PRE_SELECTION_THRESHOLD`] of original rows remain,
1200    /// filters before conjuncts that may be costly or fail, so they never see
1201    /// rows nested evaluation would skip. `NULL` rows stay for a later `false`.
1202    fn evaluate_conjunction(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
1203        // Keep each filter mask for the final scatter.
1204        let mut selections = vec![];
1205        let mut input = Cow::Borrowed(batch);
1206        let mut result = ColumnarValue::Scalar(ScalarValue::Boolean(Some(true)));
1207
1208        // Returns whether to go on to the next conjunct.
1209        let mut evaluate = |conjunct: &Arc<dyn PhysicalExpr>| -> Result<bool> {
1210            if let Some(undecided) = rows_to_filter_before(
1211                conjunct,
1212                &result,
1213                batch.schema_ref(),
1214                batch.num_rows(),
1215            ) {
1216                let array = result.to_array(input.num_rows())?;
1217                // Every kept row is true when there are no NULLs.
1218                result = if array.null_count() == 0 {
1219                    ColumnarValue::Scalar(ScalarValue::Boolean(Some(true)))
1220                } else {
1221                    ColumnarValue::Array(filter(&array, &undecided)?)
1222                };
1223                input = Cow::Owned(filter_record_batch(&input, &undecided)?);
1224                selections.push(undecided);
1225            }
1226
1227            let value = conjunct.evaluate(&input)?;
1228            let so_far =
1229                std::mem::replace(&mut result, ColumnarValue::Scalar(ScalarValue::Null));
1230            result = and_kleene_columnar(so_far, value, input.num_rows())?;
1231            Ok(!is_all_false(&result))
1232        };
1233        if for_each_conjunct(&self.left, &mut evaluate)? {
1234            for_each_conjunct(&self.right, &mut evaluate)?;
1235        }
1236
1237        selections
1238            .into_iter()
1239            .rev()
1240            .try_fold(result, |result, selection| unfilter(selection, result))
1241    }
1242}
1243
1244enum ShortCircuitStrategy {
1245    None,
1246    ReturnLeft,
1247    ReturnRight,
1248    /// Evaluate the RHS where the LHS is `false`; fill other rows with `true`.
1249    PreSelection {
1250        mask: BooleanArray,
1251        fill_value: bool,
1252    },
1253}
1254
1255/// Maximum share of rows still needing evaluation before filtering.
1256const PRE_SELECTION_THRESHOLD: f32 = 0.2;
1257
1258/// Returns the short-circuit strategy for `OR` with a Boolean LHS.
1259/// All true returns the LHS; all false returns the RHS. Sparse false rows
1260/// trigger pre-selection at [`PRE_SELECTION_THRESHOLD`].
1261/// `AND` uses [`BinaryExpr::evaluate_conjunction`].
1262fn check_short_circuit(lhs: &ColumnarValue, op: &Operator) -> ShortCircuitStrategy {
1263    if *op != Operator::Or {
1264        return ShortCircuitStrategy::None;
1265    }
1266
1267    // Only Boolean values can short-circuit.
1268    if lhs.data_type() != DataType::Boolean {
1269        return ShortCircuitStrategy::None;
1270    }
1271
1272    match lhs {
1273        ColumnarValue::Array(array) => {
1274            // Check Boolean arrays directly.
1275            if let Ok(bool_array) = as_boolean_array(array) {
1276                // NULLs still need the RHS.
1277                if bool_array.null_count() > 0 {
1278                    return ShortCircuitStrategy::None;
1279                }
1280
1281                let len = bool_array.len();
1282                if len == 0 {
1283                    return ShortCircuitStrategy::None;
1284                }
1285
1286                let true_count = bool_array.values().count_set_bits();
1287                if true_count == len {
1288                    return ShortCircuitStrategy::ReturnLeft;
1289                }
1290
1291                if true_count == 0 {
1292                    return ShortCircuitStrategy::ReturnRight;
1293                }
1294
1295                let false_count = len - true_count;
1296                if false_count as f32 / len as f32 <= PRE_SELECTION_THRESHOLD {
1297                    // Only false rows need the RHS; the LHS has no NULLs here.
1298                    let mask = BooleanArray::new(!bool_array.values(), None);
1299                    return ShortCircuitStrategy::PreSelection {
1300                        mask,
1301                        fill_value: true,
1302                    };
1303                }
1304            }
1305        }
1306        ColumnarValue::Scalar(scalar) => {
1307            // Scalars need no mask.
1308            if let ScalarValue::Boolean(Some(is_true)) = scalar {
1309                return if *is_true {
1310                    ShortCircuitStrategy::ReturnLeft
1311                } else {
1312                    ShortCircuitStrategy::ReturnRight
1313                };
1314            }
1315        }
1316    }
1317
1318    // Evaluate both sides normally.
1319    ShortCircuitStrategy::None
1320}
1321
1322/// Avoids scattering when the selected RHS rows are uniform.
1323/// Returns a scalar if they match `fill_value`; otherwise returns the LHS.
1324fn uniform_pre_selection_result(
1325    rhs_value: bool,
1326    fill_value: bool,
1327    lhs: ColumnarValue,
1328) -> ColumnarValue {
1329    if rhs_value == fill_value {
1330        ColumnarValue::Scalar(ScalarValue::Boolean(Some(fill_value)))
1331    } else {
1332        lhs
1333    }
1334}
1335
1336/// Scatters compact RHS values where `mask` is true and fills other rows with
1337/// `fill_value`. If `right_result` is `None`, selected rows become NULL.
1338fn pre_selection_scatter(
1339    mask: &BooleanArray,
1340    right_result: Option<&BooleanArray>,
1341    fill_value: bool,
1342) -> Result<ColumnarValue> {
1343    let result_len = mask.len();
1344
1345    let mut result_array_builder = BooleanArray::builder(result_len);
1346
1347    let mut right_array_pos = 0;
1348    let mut last_end = 0;
1349    match right_result {
1350        Some(right_result) => {
1351            // Borrow the RHS buffers once. `BooleanArray::slice` clones and
1352            // drops an `Arc` for every run, which dominates this loop when the
1353            // mask selects many short runs.
1354            let right_values = right_result.values();
1355            let right_offset = right_values.offset();
1356            let right_bytes = right_values.values();
1357            let right_nulls = right_result.nulls();
1358
1359            let mut values = BooleanBufferBuilder::new(result_len);
1360            // Only build a validity bitmap when the RHS has nulls. Otherwise
1361            // every run pays a second pass to write an all-ones mask that is
1362            // then discarded.
1363            let mut validity = right_nulls.map(|_| BooleanBufferBuilder::new(result_len));
1364
1365            SlicesIterator::new(mask).for_each(|(start, end)| {
1366                if start > last_end {
1367                    let gap = start - last_end;
1368                    values.append_n(gap, fill_value);
1369                    if let Some(v) = validity.as_mut() {
1370                        v.append_n(gap, true);
1371                    }
1372                }
1373
1374                // Both sides are bit-packed, so copy the run a word at a
1375                // time. Iterating the RHS would yield one `Option<bool>` and
1376                // set one bit per row.
1377                let len = end - start;
1378                let from = right_offset + right_array_pos;
1379                values.append_packed_range(from..from + len, right_bytes);
1380                if let (Some(v), Some(nulls)) = (validity.as_mut(), right_nulls) {
1381                    let nb = nulls.inner();
1382                    let nfrom = nb.offset() + right_array_pos;
1383                    v.append_packed_range(nfrom..nfrom + len, nb.values());
1384                }
1385
1386                right_array_pos += len;
1387                last_end = end;
1388            });
1389
1390            if last_end < result_len {
1391                let gap = result_len - last_end;
1392                values.append_n(gap, fill_value);
1393                if let Some(v) = validity.as_mut() {
1394                    v.append_n(gap, true);
1395                }
1396            }
1397
1398            let nulls = validity.map(|mut v| NullBuffer::new(v.finish()));
1399            let boolean_result = BooleanArray::new(values.finish(), nulls);
1400            return Ok(ColumnarValue::Array(Arc::new(boolean_result)));
1401        }
1402        None => SlicesIterator::new(mask).for_each(|(start, end)| {
1403            if start > last_end {
1404                result_array_builder.append_n(start - last_end, fill_value);
1405            }
1406
1407            let len = end - start;
1408            result_array_builder.append_nulls(len);
1409
1410            last_end = end;
1411        }),
1412    }
1413
1414    // Fill the tail.
1415    if last_end < result_len {
1416        result_array_builder.append_n(result_len - last_end, fill_value);
1417    }
1418    let boolean_result = result_array_builder.finish();
1419
1420    Ok(ColumnarValue::Array(Arc::new(boolean_result)))
1421}
1422
1423/// Selects undecided rows when some are false, at most
1424/// [`PRE_SELECTION_THRESHOLD`] of the original batch remain, and evaluating
1425/// `conjunct` on all rows is not cheap and infallible.
1426fn rows_to_filter_before(
1427    conjunct: &Arc<dyn PhysicalExpr>,
1428    result: &ColumnarValue,
1429    schema: &Schema,
1430    num_rows: usize,
1431) -> Option<BooleanArray> {
1432    let ColumnarValue::Array(array) = result else {
1433        return None;
1434    };
1435    let undecided = not_false(array.as_boolean());
1436    let undecided_count = undecided.true_count();
1437    // Classify last: it walks the whole conjunct.
1438    (undecided_count < array.len()
1439        && undecided_count as f32 / num_rows as f32 <= PRE_SELECTION_THRESHOLD
1440        && !is_cheap_and_infallible(conjunct, schema))
1441    .then_some(undecided)
1442}
1443
1444/// Whether evaluating `expr` on all rows is cheap and cannot fail.
1445/// Inspired by `reorder_predicates`' cheap forms, with fallible forms excluded.
1446fn is_cheap_and_infallible(expr: &Arc<dyn PhysicalExpr>, schema: &Schema) -> bool {
1447    use crate::expressions::{
1448        CastExpr, Column, InListExpr, IsNotNullExpr, IsNullExpr, Literal, NotExpr,
1449    };
1450    use Operator::*;
1451
1452    let is_number = |expr: &Arc<dyn PhysicalExpr>| {
1453        expr.data_type(schema)
1454            .is_ok_and(|t| t.is_integer() || t.is_floating())
1455    };
1456    let is_cheap = if let Some(binary) = expr.downcast_ref::<BinaryExpr>() {
1457        match binary.op {
1458            Eq | NotEq | Lt | LtEq | Gt | GtEq | IsDistinctFrom | IsNotDistinctFrom
1459            | And | Or => true,
1460            // Wraps on overflow instead of failing.
1461            Plus | Minus | Multiply => {
1462                !binary.fail_on_overflow
1463                    && is_number(&binary.left)
1464                    && is_number(&binary.right)
1465            }
1466            _ => false,
1467        }
1468    } else if let Some(cast) = expr.downcast_ref::<CastExpr>() {
1469        cast.expr()
1470            .data_type(schema)
1471            .is_ok_and(|from| cast.is_bigger_cast(&from))
1472    } else {
1473        expr.is::<Column>()
1474            || expr.is::<Literal>()
1475            || expr.is::<InListExpr>()
1476            || expr.is::<NotExpr>()
1477            || expr.is::<IsNullExpr>()
1478            || expr.is::<IsNotNullExpr>()
1479    };
1480    is_cheap
1481        && expr
1482            .children()
1483            .into_iter()
1484            .all(|child| is_cheap_and_infallible(child, schema))
1485}
1486
1487/// Calls `f` on each conjunct of the `AND` chain under `expr`, left to right,
1488/// until it returns `false`. Walks the tree in place, so it doesn't allocate.
1489fn for_each_conjunct(
1490    expr: &Arc<dyn PhysicalExpr>,
1491    f: &mut impl FnMut(&Arc<dyn PhysicalExpr>) -> Result<bool>,
1492) -> Result<bool> {
1493    match expr.downcast_ref::<BinaryExpr>() {
1494        Some(binary) if binary.op == Operator::And => {
1495            Ok(for_each_conjunct(&binary.left, f)?
1496                && for_each_conjunct(&binary.right, f)?)
1497        }
1498        _ => f(expr),
1499    }
1500}
1501
1502/// Whether every row is already `false`.
1503fn is_all_false(value: &ColumnarValue) -> bool {
1504    match value {
1505        ColumnarValue::Array(array) => {
1506            let array = array.as_boolean();
1507            array.null_count() == 0 && !array.has_true()
1508        }
1509        ColumnarValue::Scalar(scalar) => *scalar == ScalarValue::Boolean(Some(false)),
1510    }
1511}
1512
1513/// Scatters `result` back to all rows of `selection`; dropped rows are `false`.
1514fn unfilter(selection: BooleanArray, result: ColumnarValue) -> Result<ColumnarValue> {
1515    let result = result.into_array(selection.true_count())?;
1516    let result = result.as_boolean();
1517    if result.null_count() == 0 {
1518        if !result.has_false() {
1519            return Ok(ColumnarValue::Array(Arc::new(selection)));
1520        }
1521        if !result.has_true() {
1522            return Ok(ColumnarValue::Scalar(ScalarValue::Boolean(Some(false))));
1523        }
1524    }
1525    pre_selection_scatter(&selection, Some(result), false)
1526}
1527
1528/// A null-free mask of the rows of `array` that are `true` or `NULL`.
1529fn not_false(array: &BooleanArray) -> BooleanArray {
1530    let values = match array.nulls() {
1531        Some(nulls) => array.values() | &!nulls.inner(),
1532        None => array.values().clone(),
1533    };
1534    BooleanArray::new(values, None)
1535}
1536
1537/// Kleene `AND` of `lhs` and `rhs` over `num_rows` rows.
1538fn and_kleene_columnar(
1539    lhs: ColumnarValue,
1540    rhs: ColumnarValue,
1541    num_rows: usize,
1542) -> Result<ColumnarValue> {
1543    use ColumnarValue::Scalar;
1544    use ScalarValue::Boolean;
1545
1546    if rhs.data_type() != DataType::Boolean {
1547        return internal_err!("Cannot evaluate AND with a {} operand", rhs.data_type());
1548    }
1549    Ok(match (lhs, rhs) {
1550        (Scalar(Boolean(Some(true))), other) | (other, Scalar(Boolean(Some(true)))) => {
1551            other
1552        }
1553        (Scalar(Boolean(Some(false))), _) | (_, Scalar(Boolean(Some(false)))) => {
1554            Scalar(Boolean(Some(false)))
1555        }
1556        (lhs, rhs) => {
1557            let lhs = lhs.into_array(num_rows)?;
1558            let rhs = rhs.into_array(num_rows)?;
1559            ColumnarValue::Array(Arc::new(and_kleene(
1560                lhs.as_boolean(),
1561                rhs.as_boolean(),
1562            )?))
1563        }
1564    })
1565}
1566
1567/// Create a binary expression whose arguments are correctly coerced.
1568/// This function errors if it is not possible to coerce the arguments
1569/// to computational types supported by the operator.
1570pub fn binary(
1571    lhs: Arc<dyn PhysicalExpr>,
1572    op: Operator,
1573    rhs: Arc<dyn PhysicalExpr>,
1574    _input_schema: &Schema,
1575) -> Result<Arc<dyn PhysicalExpr>> {
1576    Ok(Arc::new(BinaryExpr::new(lhs, op, rhs)))
1577}
1578
1579/// Create a similar to expression
1580pub fn similar_to(
1581    negated: bool,
1582    case_insensitive: bool,
1583    expr: Arc<dyn PhysicalExpr>,
1584    pattern: Arc<dyn PhysicalExpr>,
1585) -> Result<Arc<dyn PhysicalExpr>> {
1586    let binary_op = match (negated, case_insensitive) {
1587        (false, false) => Operator::RegexMatch,
1588        (false, true) => Operator::RegexIMatch,
1589        (true, false) => Operator::RegexNotMatch,
1590        (true, true) => Operator::RegexNotIMatch,
1591    };
1592
1593    let translated_pattern = match pattern.downcast_ref::<crate::expressions::Literal>() {
1594        Some(literal) => Arc::new(crate::expressions::Literal::new(translate_scalar(
1595            literal.value(),
1596        )?)) as Arc<dyn PhysicalExpr>,
1597        None => Arc::new(SqlSimilarToPattern::new(pattern)) as Arc<dyn PhysicalExpr>,
1598    };
1599
1600    Ok(Arc::new(BinaryExpr::new(
1601        expr,
1602        binary_op,
1603        translated_pattern,
1604    )))
1605}
1606
1607#[cfg(test)]
1608mod tests {
1609    use super::*;
1610    use crate::expressions::{Column, Literal, col, lit, try_cast};
1611    use datafusion_expr::lit as expr_lit;
1612
1613    use datafusion_common::{assert_contains, plan_datafusion_err};
1614    use datafusion_physical_expr_common::physical_expr::fmt_sql;
1615
1616    use crate::planner::logical2physical;
1617    use arrow::array::BooleanArray;
1618    use arrow::compute::SortOptions;
1619    use datafusion_expr::col as logical_col;
1620
1621    #[test]
1622    fn test_arithmetic_ordering_overflow() -> Result<()> {
1623        let asc = SortProperties::Ordered(Default::default());
1624        let ordered = |range: Interval| ExprProperties {
1625            sort_properties: asc,
1626            range,
1627            preserves_lex_ordering: false,
1628            strictly_order_preserving: false,
1629        };
1630
1631        let schema = Schema::new(vec![
1632            Field::new("a", DataType::Int32, false),
1633            Field::new("b", DataType::Int32, false),
1634        ]);
1635        let a_plus_b =
1636            BinaryExpr::new(col("a", &schema)?, Operator::Plus, col("b", &schema)?);
1637        let unbounded = [
1638            ordered(Interval::make_unbounded(&DataType::Int32)?),
1639            ordered(Interval::make_unbounded(&DataType::Int32)?),
1640        ];
1641        let bounded = [
1642            ordered(Interval::make(Some(0), Some(10))?),
1643            ordered(Interval::make(Some(0), Some(10))?),
1644        ];
1645
1646        // Unknown ranges: the sum may overflow and wrap, so it is unordered.
1647        assert_eq!(
1648            a_plus_b.get_properties(&unbounded)?.sort_properties,
1649            SortProperties::Unordered
1650        );
1651        // Bounded ranges that cannot overflow keep the ordering, as does
1652        // checked arithmetic, which errors instead of wrapping.
1653        assert_eq!(a_plus_b.get_properties(&bounded)?.sort_properties, asc);
1654        let checked = a_plus_b.with_fail_on_overflow(true);
1655        assert_eq!(checked.get_properties(&unbounded)?.sort_properties, asc);
1656
1657        // `time + interval` wraps around the 24-hour clock even in checked
1658        // mode, so it never preserves ordering.
1659        let time = DataType::Time64(TimeUnit::Nanosecond);
1660        let interval = DataType::Interval(IntervalUnit::MonthDayNano);
1661        let schema = Schema::new(vec![
1662            Field::new("t", time.clone(), false),
1663            Field::new("i", interval.clone(), false),
1664        ]);
1665        let time_plus_interval =
1666            BinaryExpr::new(col("t", &schema)?, Operator::Plus, col("i", &schema)?)
1667                .with_fail_on_overflow(true);
1668        let time_props = [
1669            ordered(Interval::make_unbounded(&time)?),
1670            ordered(Interval::make_unbounded(&interval)?),
1671        ];
1672        assert_eq!(
1673            time_plus_interval
1674                .get_properties(&time_props)?
1675                .sort_properties,
1676            SortProperties::Unordered
1677        );
1678
1679        Ok(())
1680    }
1681
1682    /// `a - b` only derives an ordering when `a` and `b` are ordered in
1683    /// opposite directions, so every case below pairs an ascending left-hand
1684    /// side with a descending right-hand side.
1685    #[test]
1686    fn test_subtraction_ordering_overflow() -> Result<()> {
1687        let asc = SortProperties::Ordered(SortOptions {
1688            descending: false,
1689            nulls_first: true,
1690        });
1691        let desc = SortProperties::Ordered(SortOptions {
1692            descending: true,
1693            nulls_first: true,
1694        });
1695        let props = |sort_properties, range| ExprProperties {
1696            sort_properties,
1697            range,
1698            preserves_lex_ordering: false,
1699            strictly_order_preserving: false,
1700        };
1701
1702        let schema = Schema::new(vec![
1703            Field::new("a", DataType::Int32, false),
1704            Field::new("b", DataType::Int32, false),
1705        ]);
1706        let a_minus_b =
1707            BinaryExpr::new(col("a", &schema)?, Operator::Minus, col("b", &schema)?);
1708
1709        // Signed minimum: the difference can underflow past `i32::MIN` and
1710        // wrap around to large positive values.
1711        let signed_underflow = [
1712            props(asc, Interval::make(Some(i32::MIN), Some(0))?),
1713            props(desc, Interval::make(Some(0), Some(i32::MAX))?),
1714        ];
1715        assert_eq!(
1716            a_minus_b.get_properties(&signed_underflow)?.sort_properties,
1717            SortProperties::Unordered
1718        );
1719        // The very same ranges keep the ordering under checked arithmetic,
1720        // which errors instead of wrapping.
1721        let checked = a_minus_b.clone().with_fail_on_overflow(true);
1722        assert_eq!(
1723            checked.get_properties(&signed_underflow)?.sort_properties,
1724            asc
1725        );
1726        // Ranges whose difference stays inside `Int32` are safe.
1727        let signed_safe = [
1728            props(asc, Interval::make(Some(0), Some(10))?),
1729            props(desc, Interval::make(Some(0), Some(10))?),
1730        ];
1731        assert_eq!(a_minus_b.get_properties(&signed_safe)?.sort_properties, asc);
1732
1733        let schema = Schema::new(vec![
1734            Field::new("a", DataType::UInt32, false),
1735            Field::new("b", DataType::UInt32, false),
1736        ]);
1737        let a_minus_b =
1738            BinaryExpr::new(col("a", &schema)?, Operator::Minus, col("b", &schema)?);
1739
1740        // Unsigned underflow: the ranges overlap, so `0 - 1` wraps to
1741        // `u32::MAX` even though both operands are bounded.
1742        let unsigned_underflow = [
1743            props(asc, Interval::make(Some(0_u32), Some(10_u32))?),
1744            props(desc, Interval::make(Some(0_u32), Some(10_u32))?),
1745        ];
1746        assert_eq!(
1747            a_minus_b
1748                .get_properties(&unsigned_underflow)?
1749                .sort_properties,
1750            SortProperties::Unordered
1751        );
1752        // A left-hand range that always dominates the right-hand one cannot
1753        // underflow.
1754        let unsigned_safe = [
1755            props(asc, Interval::make(Some(10_u32), Some(20_u32))?),
1756            props(desc, Interval::make(Some(0_u32), Some(5_u32))?),
1757        ];
1758        assert_eq!(
1759            a_minus_b.get_properties(&unsigned_safe)?.sort_properties,
1760            asc
1761        );
1762
1763        // `time - interval` wraps around the 24-hour clock even in checked
1764        // mode, so it never preserves ordering.
1765        let time = DataType::Time64(TimeUnit::Nanosecond);
1766        let interval = DataType::Interval(IntervalUnit::MonthDayNano);
1767        let schema = Schema::new(vec![
1768            Field::new("t", time.clone(), false),
1769            Field::new("i", interval.clone(), false),
1770        ]);
1771        let time_minus_interval =
1772            BinaryExpr::new(col("t", &schema)?, Operator::Minus, col("i", &schema)?)
1773                .with_fail_on_overflow(true);
1774        let time_props = [
1775            props(asc, Interval::make_unbounded(&time)?),
1776            props(desc, Interval::make_unbounded(&interval)?),
1777        ];
1778        assert_eq!(
1779            time_minus_interval
1780                .get_properties(&time_props)?
1781                .sort_properties,
1782            SortProperties::Unordered
1783        );
1784
1785        Ok(())
1786    }
1787
1788    /// Performs a binary operation, applying any type coercion necessary
1789    fn binary_op(
1790        left: Arc<dyn PhysicalExpr>,
1791        op: Operator,
1792        right: Arc<dyn PhysicalExpr>,
1793        schema: &Schema,
1794    ) -> Result<Arc<dyn PhysicalExpr>> {
1795        let left_type = left.data_type(schema)?;
1796        let right_type = right.data_type(schema)?;
1797        let (lhs, rhs) =
1798            BinaryTypeCoercer::new(&left_type, &op, &right_type).get_input_types()?;
1799
1800        let left_expr = try_cast(left, schema, lhs)?;
1801        let right_expr = try_cast(right, schema, rhs)?;
1802        binary(left_expr, op, right_expr, schema)
1803    }
1804
1805    #[test]
1806    fn binary_comparison() -> Result<()> {
1807        let schema = Schema::new(vec![
1808            Field::new("a", DataType::Int32, false),
1809            Field::new("b", DataType::Int32, false),
1810        ]);
1811        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
1812        let b = Int32Array::from(vec![1, 2, 4, 8, 16]);
1813
1814        // expression: "a < b"
1815        let lt = binary(
1816            col("a", &schema)?,
1817            Operator::Lt,
1818            col("b", &schema)?,
1819            &schema,
1820        )?;
1821        let batch =
1822            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)])?;
1823
1824        let result = lt
1825            .evaluate(&batch)?
1826            .into_array(batch.num_rows())
1827            .expect("Failed to convert to array");
1828        assert_eq!(result.len(), 5);
1829
1830        let expected = [false, false, true, true, true];
1831        let result =
1832            as_boolean_array(&result).expect("failed to downcast to BooleanArray");
1833        for (i, &expected_item) in expected.iter().enumerate().take(5) {
1834            assert_eq!(result.value(i), expected_item);
1835        }
1836
1837        Ok(())
1838    }
1839
1840    #[test]
1841    fn binary_nested() -> Result<()> {
1842        let schema = Schema::new(vec![
1843            Field::new("a", DataType::Int32, false),
1844            Field::new("b", DataType::Int32, false),
1845        ]);
1846        let a = Int32Array::from(vec![2, 4, 6, 8, 10]);
1847        let b = Int32Array::from(vec![2, 5, 4, 8, 8]);
1848
1849        // expression: "a < b OR a == b"
1850        let expr = binary(
1851            binary(
1852                col("a", &schema)?,
1853                Operator::Lt,
1854                col("b", &schema)?,
1855                &schema,
1856            )?,
1857            Operator::Or,
1858            binary(
1859                col("a", &schema)?,
1860                Operator::Eq,
1861                col("b", &schema)?,
1862                &schema,
1863            )?,
1864            &schema,
1865        )?;
1866        let batch =
1867            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)])?;
1868
1869        assert_eq!("a@0 < b@1 OR a@0 = b@1", format!("{expr}"));
1870
1871        let result = expr
1872            .evaluate(&batch)?
1873            .into_array(batch.num_rows())
1874            .expect("Failed to convert to array");
1875        assert_eq!(result.len(), 5);
1876
1877        let expected = [true, true, false, true, false];
1878        let result =
1879            as_boolean_array(&result).expect("failed to downcast to BooleanArray");
1880        for (i, &expected_item) in expected.iter().enumerate().take(5) {
1881            assert_eq!(result.value(i), expected_item);
1882        }
1883
1884        Ok(())
1885    }
1886
1887    // runs an end-to-end test of physical type coercion:
1888    // 1. construct a record batch with two columns of type A and B
1889    //  (*_ARRAY is the Rust Arrow array type, and *_TYPE is the DataType of the elements)
1890    // 2. construct a physical expression of A OP B
1891    // 3. evaluate the expression
1892    // 4. verify that the resulting expression is of type C
1893    // 5. verify that the results of evaluation are $VEC
1894    macro_rules! test_coercion {
1895        ($A_ARRAY:ident, $A_TYPE:expr, $A_VEC:expr, $B_ARRAY:ident, $B_TYPE:expr, $B_VEC:expr, $OP:expr, $C_ARRAY:ident, $C_TYPE:expr, $VEC:expr,) => {{
1896            let schema = Schema::new(vec![
1897                Field::new("a", $A_TYPE, false),
1898                Field::new("b", $B_TYPE, false),
1899            ]);
1900            let a = $A_ARRAY::from($A_VEC);
1901            let b = $B_ARRAY::from($B_VEC);
1902            let (lhs, rhs) =
1903                BinaryTypeCoercer::new(&$A_TYPE, &$OP, &$B_TYPE).get_input_types()?;
1904
1905            let left = try_cast(col("a", &schema)?, &schema, lhs)?;
1906            let right = try_cast(col("b", &schema)?, &schema, rhs)?;
1907
1908            // verify that we can construct the expression
1909            let expression = binary(left, $OP, right, &schema)?;
1910            let batch = RecordBatch::try_new(
1911                Arc::new(schema.clone()),
1912                vec![Arc::new(a), Arc::new(b)],
1913            )?;
1914
1915            // verify that the expression's type is correct
1916            assert_eq!(expression.data_type(&schema)?, $C_TYPE);
1917
1918            // compute
1919            let result = expression
1920                .evaluate(&batch)?
1921                .into_array(batch.num_rows())
1922                .expect("Failed to convert to array");
1923
1924            // verify that the array's data_type is correct
1925            assert_eq!(*result.data_type(), $C_TYPE);
1926
1927            // verify that the data itself is downcastable
1928            let result = result
1929                .as_any()
1930                .downcast_ref::<$C_ARRAY>()
1931                .expect("failed to downcast");
1932            // verify that the result itself is correct
1933            for (i, x) in $VEC.iter().enumerate() {
1934                let v = result.value(i);
1935                assert_eq!(
1936                    v, *x,
1937                    "Unexpected output at position {i}:\n\nActual:\n{v}\n\nExpected:\n{x}"
1938                );
1939            }
1940        }};
1941    }
1942
1943    #[test]
1944    fn test_type_coercion() -> Result<()> {
1945        test_coercion!(
1946            Int32Array,
1947            DataType::Int32,
1948            vec![1i32, 2i32],
1949            UInt32Array,
1950            DataType::UInt32,
1951            vec![1u32, 2u32],
1952            Operator::Plus,
1953            Int64Array,
1954            DataType::Int64,
1955            [2i64, 4i64],
1956        );
1957        test_coercion!(
1958            Int32Array,
1959            DataType::Int32,
1960            vec![1i32],
1961            UInt16Array,
1962            DataType::UInt16,
1963            vec![1u16],
1964            Operator::Plus,
1965            Int32Array,
1966            DataType::Int32,
1967            [2i32],
1968        );
1969        test_coercion!(
1970            Float32Array,
1971            DataType::Float32,
1972            vec![1f32],
1973            UInt16Array,
1974            DataType::UInt16,
1975            vec![1u16],
1976            Operator::Plus,
1977            Float32Array,
1978            DataType::Float32,
1979            [2f32],
1980        );
1981        test_coercion!(
1982            Float32Array,
1983            DataType::Float32,
1984            vec![2f32],
1985            UInt16Array,
1986            DataType::UInt16,
1987            vec![1u16],
1988            Operator::Multiply,
1989            Float32Array,
1990            DataType::Float32,
1991            [2f32],
1992        );
1993        test_coercion!(
1994            StringArray,
1995            DataType::Utf8,
1996            vec!["1994-12-13", "1995-01-26"],
1997            Date32Array,
1998            DataType::Date32,
1999            vec![9112, 9156],
2000            Operator::Eq,
2001            BooleanArray,
2002            DataType::Boolean,
2003            [true, true],
2004        );
2005        test_coercion!(
2006            StringArray,
2007            DataType::Utf8,
2008            vec!["1994-12-13", "1995-01-26"],
2009            Date32Array,
2010            DataType::Date32,
2011            vec![9113, 9154],
2012            Operator::Lt,
2013            BooleanArray,
2014            DataType::Boolean,
2015            [true, false],
2016        );
2017        test_coercion!(
2018            StringArray,
2019            DataType::Utf8,
2020            vec!["1994-12-13T12:34:56", "1995-01-26T01:23:45"],
2021            Date64Array,
2022            DataType::Date64,
2023            vec![787322096000, 791083425000],
2024            Operator::Eq,
2025            BooleanArray,
2026            DataType::Boolean,
2027            [true, true],
2028        );
2029        test_coercion!(
2030            StringArray,
2031            DataType::Utf8,
2032            vec!["1994-12-13T12:34:56", "1995-01-26T01:23:45"],
2033            Date64Array,
2034            DataType::Date64,
2035            vec![787322096001, 791083424999],
2036            Operator::Lt,
2037            BooleanArray,
2038            DataType::Boolean,
2039            [true, false],
2040        );
2041        test_coercion!(
2042            StringViewArray,
2043            DataType::Utf8View,
2044            vec!["abc"; 5],
2045            StringArray,
2046            DataType::Utf8,
2047            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2048            Operator::RegexMatch,
2049            BooleanArray,
2050            DataType::Boolean,
2051            [true, false, true, false, false],
2052        );
2053        test_coercion!(
2054            StringViewArray,
2055            DataType::Utf8View,
2056            vec!["abc"; 5],
2057            StringArray,
2058            DataType::Utf8,
2059            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2060            Operator::RegexIMatch,
2061            BooleanArray,
2062            DataType::Boolean,
2063            [true, true, true, true, false],
2064        );
2065        test_coercion!(
2066            StringArray,
2067            DataType::Utf8,
2068            vec!["abc"; 5],
2069            StringViewArray,
2070            DataType::Utf8View,
2071            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2072            Operator::RegexNotMatch,
2073            BooleanArray,
2074            DataType::Boolean,
2075            [false, true, false, true, true],
2076        );
2077        test_coercion!(
2078            StringArray,
2079            DataType::Utf8,
2080            vec!["abc"; 5],
2081            StringViewArray,
2082            DataType::Utf8View,
2083            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2084            Operator::RegexNotIMatch,
2085            BooleanArray,
2086            DataType::Boolean,
2087            [false, false, false, false, true],
2088        );
2089        test_coercion!(
2090            StringArray,
2091            DataType::Utf8,
2092            vec!["abc"; 5],
2093            StringArray,
2094            DataType::Utf8,
2095            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2096            Operator::RegexMatch,
2097            BooleanArray,
2098            DataType::Boolean,
2099            [true, false, true, false, false],
2100        );
2101        test_coercion!(
2102            StringArray,
2103            DataType::Utf8,
2104            vec!["abc"; 5],
2105            StringArray,
2106            DataType::Utf8,
2107            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2108            Operator::RegexIMatch,
2109            BooleanArray,
2110            DataType::Boolean,
2111            [true, true, true, true, false],
2112        );
2113        test_coercion!(
2114            StringArray,
2115            DataType::Utf8,
2116            vec!["abc"; 5],
2117            StringArray,
2118            DataType::Utf8,
2119            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2120            Operator::RegexNotMatch,
2121            BooleanArray,
2122            DataType::Boolean,
2123            [false, true, false, true, true],
2124        );
2125        test_coercion!(
2126            StringArray,
2127            DataType::Utf8,
2128            vec!["abc"; 5],
2129            StringArray,
2130            DataType::Utf8,
2131            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2132            Operator::RegexNotIMatch,
2133            BooleanArray,
2134            DataType::Boolean,
2135            [false, false, false, false, true],
2136        );
2137        test_coercion!(
2138            LargeStringArray,
2139            DataType::LargeUtf8,
2140            vec!["abc"; 5],
2141            LargeStringArray,
2142            DataType::LargeUtf8,
2143            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2144            Operator::RegexMatch,
2145            BooleanArray,
2146            DataType::Boolean,
2147            [true, false, true, false, false],
2148        );
2149        test_coercion!(
2150            LargeStringArray,
2151            DataType::LargeUtf8,
2152            vec!["abc"; 5],
2153            LargeStringArray,
2154            DataType::LargeUtf8,
2155            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2156            Operator::RegexIMatch,
2157            BooleanArray,
2158            DataType::Boolean,
2159            [true, true, true, true, false],
2160        );
2161        test_coercion!(
2162            LargeStringArray,
2163            DataType::LargeUtf8,
2164            vec!["abc"; 5],
2165            LargeStringArray,
2166            DataType::LargeUtf8,
2167            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2168            Operator::RegexNotMatch,
2169            BooleanArray,
2170            DataType::Boolean,
2171            [false, true, false, true, true],
2172        );
2173        test_coercion!(
2174            LargeStringArray,
2175            DataType::LargeUtf8,
2176            vec!["abc"; 5],
2177            LargeStringArray,
2178            DataType::LargeUtf8,
2179            vec!["^a", "^A", "(b|d)", "(B|D)", "^(b|c)"],
2180            Operator::RegexNotIMatch,
2181            BooleanArray,
2182            DataType::Boolean,
2183            [false, false, false, false, true],
2184        );
2185        test_coercion!(
2186            StringArray,
2187            DataType::Utf8,
2188            vec!["abc"; 5],
2189            StringArray,
2190            DataType::Utf8,
2191            vec!["a__", "A%BC", "A_BC", "abc", "a%C"],
2192            Operator::LikeMatch,
2193            BooleanArray,
2194            DataType::Boolean,
2195            [true, false, false, true, false],
2196        );
2197        test_coercion!(
2198            StringArray,
2199            DataType::Utf8,
2200            vec!["abc"; 5],
2201            StringArray,
2202            DataType::Utf8,
2203            vec!["a__", "A%BC", "A_BC", "abc", "a%C"],
2204            Operator::ILikeMatch,
2205            BooleanArray,
2206            DataType::Boolean,
2207            [true, true, false, true, true],
2208        );
2209        test_coercion!(
2210            StringArray,
2211            DataType::Utf8,
2212            vec!["abc"; 5],
2213            StringArray,
2214            DataType::Utf8,
2215            vec!["a__", "A%BC", "A_BC", "abc", "a%C"],
2216            Operator::NotLikeMatch,
2217            BooleanArray,
2218            DataType::Boolean,
2219            [false, true, true, false, true],
2220        );
2221        test_coercion!(
2222            StringArray,
2223            DataType::Utf8,
2224            vec!["abc"; 5],
2225            StringArray,
2226            DataType::Utf8,
2227            vec!["a__", "A%BC", "A_BC", "abc", "a%C"],
2228            Operator::NotILikeMatch,
2229            BooleanArray,
2230            DataType::Boolean,
2231            [false, false, true, false, false],
2232        );
2233        test_coercion!(
2234            LargeStringArray,
2235            DataType::LargeUtf8,
2236            vec!["abc"; 5],
2237            LargeStringArray,
2238            DataType::LargeUtf8,
2239            vec!["a__", "A%BC", "A_BC", "abc", "a%C"],
2240            Operator::LikeMatch,
2241            BooleanArray,
2242            DataType::Boolean,
2243            [true, false, false, true, false],
2244        );
2245        test_coercion!(
2246            LargeStringArray,
2247            DataType::LargeUtf8,
2248            vec!["abc"; 5],
2249            LargeStringArray,
2250            DataType::LargeUtf8,
2251            vec!["a__", "A%BC", "A_BC", "abc", "a%C"],
2252            Operator::ILikeMatch,
2253            BooleanArray,
2254            DataType::Boolean,
2255            [true, true, false, true, true],
2256        );
2257        test_coercion!(
2258            LargeStringArray,
2259            DataType::LargeUtf8,
2260            vec!["abc"; 5],
2261            LargeStringArray,
2262            DataType::LargeUtf8,
2263            vec!["a__", "A%BC", "A_BC", "abc", "a%C"],
2264            Operator::NotLikeMatch,
2265            BooleanArray,
2266            DataType::Boolean,
2267            [false, true, true, false, true],
2268        );
2269        test_coercion!(
2270            LargeStringArray,
2271            DataType::LargeUtf8,
2272            vec!["abc"; 5],
2273            LargeStringArray,
2274            DataType::LargeUtf8,
2275            vec!["a__", "A%BC", "A_BC", "abc", "a%C"],
2276            Operator::NotILikeMatch,
2277            BooleanArray,
2278            DataType::Boolean,
2279            [false, false, true, false, false],
2280        );
2281        test_coercion!(
2282            Int16Array,
2283            DataType::Int16,
2284            vec![1i16, 2i16, 3i16],
2285            Int64Array,
2286            DataType::Int64,
2287            vec![10i64, 4i64, 5i64],
2288            Operator::BitwiseAnd,
2289            Int64Array,
2290            DataType::Int64,
2291            [0i64, 0i64, 1i64],
2292        );
2293        test_coercion!(
2294            UInt16Array,
2295            DataType::UInt16,
2296            vec![1u16, 2u16, 3u16],
2297            UInt64Array,
2298            DataType::UInt64,
2299            vec![10u64, 4u64, 5u64],
2300            Operator::BitwiseAnd,
2301            UInt64Array,
2302            DataType::UInt64,
2303            [0u64, 0u64, 1u64],
2304        );
2305        test_coercion!(
2306            Int16Array,
2307            DataType::Int16,
2308            vec![3i16, 2i16, 3i16],
2309            Int64Array,
2310            DataType::Int64,
2311            vec![10i64, 6i64, 5i64],
2312            Operator::BitwiseOr,
2313            Int64Array,
2314            DataType::Int64,
2315            [11i64, 6i64, 7i64],
2316        );
2317        test_coercion!(
2318            UInt16Array,
2319            DataType::UInt16,
2320            vec![1u16, 2u16, 3u16],
2321            UInt64Array,
2322            DataType::UInt64,
2323            vec![10u64, 4u64, 5u64],
2324            Operator::BitwiseOr,
2325            UInt64Array,
2326            DataType::UInt64,
2327            [11u64, 6u64, 7u64],
2328        );
2329        test_coercion!(
2330            Int16Array,
2331            DataType::Int16,
2332            vec![3i16, 2i16, 3i16],
2333            Int64Array,
2334            DataType::Int64,
2335            vec![10i64, 6i64, 5i64],
2336            Operator::BitwiseXor,
2337            Int64Array,
2338            DataType::Int64,
2339            [9i64, 4i64, 6i64],
2340        );
2341        test_coercion!(
2342            UInt16Array,
2343            DataType::UInt16,
2344            vec![3u16, 2u16, 3u16],
2345            UInt64Array,
2346            DataType::UInt64,
2347            vec![10u64, 6u64, 5u64],
2348            Operator::BitwiseXor,
2349            UInt64Array,
2350            DataType::UInt64,
2351            [9u64, 4u64, 6u64],
2352        );
2353        test_coercion!(
2354            Int16Array,
2355            DataType::Int16,
2356            vec![4i16, 27i16, 35i16],
2357            Int64Array,
2358            DataType::Int64,
2359            vec![2i64, 3i64, 4i64],
2360            Operator::BitwiseShiftRight,
2361            Int64Array,
2362            DataType::Int64,
2363            [1i64, 3i64, 2i64],
2364        );
2365        test_coercion!(
2366            UInt16Array,
2367            DataType::UInt16,
2368            vec![4u16, 27u16, 35u16],
2369            UInt64Array,
2370            DataType::UInt64,
2371            vec![2u64, 3u64, 4u64],
2372            Operator::BitwiseShiftRight,
2373            UInt64Array,
2374            DataType::UInt64,
2375            [1u64, 3u64, 2u64],
2376        );
2377        test_coercion!(
2378            Int16Array,
2379            DataType::Int16,
2380            vec![2i16, 3i16, 4i16],
2381            Int64Array,
2382            DataType::Int64,
2383            vec![4i64, 12i64, 7i64],
2384            Operator::BitwiseShiftLeft,
2385            Int64Array,
2386            DataType::Int64,
2387            [32i64, 12288i64, 512i64],
2388        );
2389        test_coercion!(
2390            UInt16Array,
2391            DataType::UInt16,
2392            vec![2u16, 3u16, 4u16],
2393            UInt64Array,
2394            DataType::UInt64,
2395            vec![4u64, 12u64, 7u64],
2396            Operator::BitwiseShiftLeft,
2397            UInt64Array,
2398            DataType::UInt64,
2399            [32u64, 12288u64, 512u64],
2400        );
2401        Ok(())
2402    }
2403
2404    // Note it would be nice to use the same test_coercion macro as
2405    // above, but sadly the type of the values of the dictionary are
2406    // not encoded in the rust type of the DictionaryArray. Thus there
2407    // is no way at the time of this writing to create a dictionary
2408    // array using the `From` trait
2409    #[test]
2410    fn test_dictionary_type_to_array_coercion() -> Result<()> {
2411        // Test string  a string dictionary
2412        let dict_type =
2413            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
2414        let string_type = DataType::Utf8;
2415
2416        // build dictionary
2417        let mut dict_builder = StringDictionaryBuilder::<Int32Type>::new();
2418
2419        dict_builder.append("one")?;
2420        dict_builder.append_null();
2421        dict_builder.append("three")?;
2422        dict_builder.append("four")?;
2423        let dict_array = Arc::new(dict_builder.finish()) as ArrayRef;
2424
2425        let str_array = Arc::new(StringArray::from(vec![
2426            Some("not one"),
2427            Some("two"),
2428            None,
2429            Some("four"),
2430        ])) as ArrayRef;
2431
2432        let schema = Arc::new(Schema::new(vec![
2433            Field::new("a", dict_type.clone(), true),
2434            Field::new("b", string_type.clone(), true),
2435        ]));
2436
2437        // Test 1: a = b
2438        let result = BooleanArray::from(vec![Some(false), None, None, Some(true)]);
2439        apply_logic_op(&schema, &dict_array, &str_array, Operator::Eq, result)?;
2440
2441        // Test 2: now test the other direction
2442        // b = a
2443        let schema = Arc::new(Schema::new(vec![
2444            Field::new("a", string_type, true),
2445            Field::new("b", dict_type, true),
2446        ]));
2447        let result = BooleanArray::from(vec![Some(false), None, None, Some(true)]);
2448        apply_logic_op(&schema, &str_array, &dict_array, Operator::Eq, result)?;
2449
2450        Ok(())
2451    }
2452
2453    #[test]
2454    fn plus_op() -> Result<()> {
2455        let schema = Schema::new(vec![
2456            Field::new("a", DataType::Int32, false),
2457            Field::new("b", DataType::Int32, false),
2458        ]);
2459        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2460        let b = Int32Array::from(vec![1, 2, 4, 8, 16]);
2461
2462        apply_arithmetic::<Int32Type>(
2463            Arc::new(schema),
2464            vec![Arc::new(a), Arc::new(b)],
2465            Operator::Plus,
2466            Int32Array::from(vec![2, 4, 7, 12, 21]),
2467        )?;
2468
2469        Ok(())
2470    }
2471
2472    #[test]
2473    fn plus_op_dict() -> Result<()> {
2474        let schema = Schema::new(vec![
2475            Field::new(
2476                "a",
2477                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
2478                true,
2479            ),
2480            Field::new(
2481                "b",
2482                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
2483                true,
2484            ),
2485        ]);
2486
2487        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2488        let keys = Int8Array::from(vec![Some(0), None, Some(1), Some(3), None]);
2489        let a = DictionaryArray::try_new(keys, Arc::new(a))?;
2490
2491        let b = Int32Array::from(vec![1, 2, 4, 8, 16]);
2492        let keys = Int8Array::from(vec![0, 1, 1, 2, 1]);
2493        let b = DictionaryArray::try_new(keys, Arc::new(b))?;
2494
2495        apply_arithmetic::<Int32Type>(
2496            Arc::new(schema),
2497            vec![Arc::new(a), Arc::new(b)],
2498            Operator::Plus,
2499            Int32Array::from(vec![Some(2), None, Some(4), Some(8), None]),
2500        )?;
2501
2502        Ok(())
2503    }
2504
2505    #[test]
2506    fn plus_op_dict_decimal() -> Result<()> {
2507        let schema = Schema::new(vec![
2508            Field::new(
2509                "a",
2510                DataType::Dictionary(
2511                    Box::new(DataType::Int8),
2512                    Box::new(DataType::Decimal128(10, 0)),
2513                ),
2514                true,
2515            ),
2516            Field::new(
2517                "b",
2518                DataType::Dictionary(
2519                    Box::new(DataType::Int8),
2520                    Box::new(DataType::Decimal128(10, 0)),
2521                ),
2522                true,
2523            ),
2524        ]);
2525
2526        let value = 123;
2527        let decimal_array = Arc::new(create_decimal_array(
2528            &[
2529                Some(value),
2530                Some(value + 2),
2531                Some(value - 1),
2532                Some(value + 1),
2533            ],
2534            10,
2535            0,
2536        ));
2537
2538        let keys = Int8Array::from(vec![Some(0), Some(2), None, Some(3), Some(0)]);
2539        let a = DictionaryArray::try_new(keys, decimal_array)?;
2540
2541        let keys = Int8Array::from(vec![Some(0), None, Some(3), Some(2), Some(2)]);
2542        let decimal_array = Arc::new(create_decimal_array(
2543            &[
2544                Some(value + 1),
2545                Some(value + 3),
2546                Some(value),
2547                Some(value + 2),
2548            ],
2549            10,
2550            0,
2551        ));
2552        let b = DictionaryArray::try_new(keys, decimal_array)?;
2553
2554        apply_arithmetic(
2555            Arc::new(schema),
2556            vec![Arc::new(a), Arc::new(b)],
2557            Operator::Plus,
2558            create_decimal_array(&[Some(247), None, None, Some(247), Some(246)], 11, 0),
2559        )?;
2560
2561        Ok(())
2562    }
2563
2564    #[test]
2565    fn plus_op_scalar() -> Result<()> {
2566        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
2567        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2568
2569        apply_arithmetic_scalar(
2570            Arc::new(schema),
2571            vec![Arc::new(a)],
2572            Operator::Plus,
2573            ScalarValue::Int32(Some(1)),
2574            Arc::new(Int32Array::from(vec![2, 3, 4, 5, 6])),
2575        )?;
2576
2577        Ok(())
2578    }
2579
2580    #[test]
2581    fn plus_op_dict_scalar() -> Result<()> {
2582        let schema = Schema::new(vec![Field::new(
2583            "a",
2584            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
2585            true,
2586        )]);
2587
2588        let mut dict_builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
2589
2590        dict_builder.append(1)?;
2591        dict_builder.append_null();
2592        dict_builder.append(2)?;
2593        dict_builder.append(5)?;
2594
2595        let a = dict_builder.finish();
2596
2597        let expected: PrimitiveArray<Int32Type> =
2598            PrimitiveArray::from(vec![Some(2), None, Some(3), Some(6)]);
2599
2600        apply_arithmetic_scalar(
2601            Arc::new(schema),
2602            vec![Arc::new(a)],
2603            Operator::Plus,
2604            ScalarValue::Dictionary(
2605                Box::new(DataType::Int8),
2606                Box::new(ScalarValue::Int32(Some(1))),
2607            ),
2608            Arc::new(expected),
2609        )?;
2610
2611        Ok(())
2612    }
2613
2614    #[test]
2615    fn plus_op_dict_scalar_decimal() -> Result<()> {
2616        let schema = Schema::new(vec![Field::new(
2617            "a",
2618            DataType::Dictionary(
2619                Box::new(DataType::Int8),
2620                Box::new(DataType::Decimal128(10, 0)),
2621            ),
2622            true,
2623        )]);
2624
2625        let value = 123;
2626        let decimal_array = Arc::new(create_decimal_array(
2627            &[Some(value), None, Some(value - 1), Some(value + 1)],
2628            10,
2629            0,
2630        ));
2631
2632        let keys = Int8Array::from(vec![0, 2, 1, 3, 0]);
2633        let a = DictionaryArray::try_new(keys, decimal_array)?;
2634
2635        let decimal_array = Arc::new(create_decimal_array(
2636            &[
2637                Some(value + 1),
2638                Some(value),
2639                None,
2640                Some(value + 2),
2641                Some(value + 1),
2642            ],
2643            11,
2644            0,
2645        ));
2646
2647        apply_arithmetic_scalar(
2648            Arc::new(schema),
2649            vec![Arc::new(a)],
2650            Operator::Plus,
2651            ScalarValue::Dictionary(
2652                Box::new(DataType::Int8),
2653                Box::new(ScalarValue::Decimal128(Some(1), 10, 0)),
2654            ),
2655            decimal_array,
2656        )?;
2657
2658        Ok(())
2659    }
2660
2661    #[test]
2662    fn minus_op() -> Result<()> {
2663        let schema = Arc::new(Schema::new(vec![
2664            Field::new("a", DataType::Int32, false),
2665            Field::new("b", DataType::Int32, false),
2666        ]));
2667        let a = Arc::new(Int32Array::from(vec![1, 2, 4, 8, 16]));
2668        let b = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5]));
2669
2670        apply_arithmetic::<Int32Type>(
2671            Arc::clone(&schema),
2672            vec![
2673                Arc::clone(&a) as Arc<dyn Array>,
2674                Arc::clone(&b) as Arc<dyn Array>,
2675            ],
2676            Operator::Minus,
2677            Int32Array::from(vec![0, 0, 1, 4, 11]),
2678        )?;
2679
2680        // should handle have negative values in result (for signed)
2681        apply_arithmetic::<Int32Type>(
2682            schema,
2683            vec![b, a],
2684            Operator::Minus,
2685            Int32Array::from(vec![0, 0, -1, -4, -11]),
2686        )?;
2687
2688        Ok(())
2689    }
2690
2691    #[test]
2692    fn date32_minus_date32_returns_int64_days() -> Result<()> {
2693        let schema = Arc::new(Schema::new(vec![
2694            Field::new("a", DataType::Date32, true),
2695            Field::new("b", DataType::Date32, true),
2696        ]));
2697        let a = Arc::new(Date32Array::from(vec![
2698            Some(18_901),
2699            Some(18_901),
2700            None,
2701            Some(18_900),
2702        ]));
2703        let b = Arc::new(Date32Array::from(vec![
2704            Some(18_898),
2705            Some(18_904),
2706            Some(18_900),
2707            None,
2708        ]));
2709
2710        apply_arithmetic::<Int64Type>(
2711            schema,
2712            vec![a, b],
2713            Operator::Minus,
2714            Int64Array::from(vec![Some(3), Some(-3), None, None]),
2715        )?;
2716
2717        Ok(())
2718    }
2719
2720    #[test]
2721    fn date64_minus_date64_returns_int64_days() -> Result<()> {
2722        let schema = Arc::new(Schema::new(vec![
2723            Field::new("a", DataType::Date64, true),
2724            Field::new("b", DataType::Date64, true),
2725        ]));
2726        let a = Arc::new(Date64Array::from(vec![
2727            Some(18_901 * MILLIS_PER_DAY),
2728            Some(18_901 * MILLIS_PER_DAY),
2729            None,
2730            Some(18_900 * MILLIS_PER_DAY),
2731        ]));
2732        let b = Arc::new(Date64Array::from(vec![
2733            Some(18_898 * MILLIS_PER_DAY),
2734            Some(18_904 * MILLIS_PER_DAY),
2735            Some(18_900 * MILLIS_PER_DAY),
2736            None,
2737        ]));
2738
2739        apply_arithmetic::<Int64Type>(
2740            schema,
2741            vec![a, b],
2742            Operator::Minus,
2743            Int64Array::from(vec![Some(3), Some(-3), None, None]),
2744        )?;
2745
2746        Ok(())
2747    }
2748
2749    #[test]
2750    fn date32_minus_null_scalar_returns_int64_null_scalar() -> Result<()> {
2751        let result = apply_date_subtraction(
2752            &ColumnarValue::Array(Arc::new(Date32Array::from(vec![
2753                Some(18_901),
2754                Some(18_900),
2755            ]))),
2756            &ColumnarValue::Scalar(ScalarValue::Date32(None)),
2757        )?;
2758
2759        assert!(matches!(
2760            result,
2761            ColumnarValue::Scalar(ScalarValue::Int64(None))
2762        ));
2763
2764        Ok(())
2765    }
2766
2767    #[test]
2768    fn minus_op_dict() -> Result<()> {
2769        let schema = Schema::new(vec![
2770            Field::new(
2771                "a",
2772                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
2773                true,
2774            ),
2775            Field::new(
2776                "b",
2777                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
2778                true,
2779            ),
2780        ]);
2781
2782        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2783        let keys = Int8Array::from(vec![Some(0), None, Some(1), Some(3), None]);
2784        let a = DictionaryArray::try_new(keys, Arc::new(a))?;
2785
2786        let b = Int32Array::from(vec![1, 2, 4, 8, 16]);
2787        let keys = Int8Array::from(vec![0, 1, 1, 2, 1]);
2788        let b = DictionaryArray::try_new(keys, Arc::new(b))?;
2789
2790        apply_arithmetic::<Int32Type>(
2791            Arc::new(schema),
2792            vec![Arc::new(a), Arc::new(b)],
2793            Operator::Minus,
2794            Int32Array::from(vec![Some(0), None, Some(0), Some(0), None]),
2795        )?;
2796
2797        Ok(())
2798    }
2799
2800    #[test]
2801    fn minus_op_dict_decimal() -> Result<()> {
2802        let schema = Schema::new(vec![
2803            Field::new(
2804                "a",
2805                DataType::Dictionary(
2806                    Box::new(DataType::Int8),
2807                    Box::new(DataType::Decimal128(10, 0)),
2808                ),
2809                true,
2810            ),
2811            Field::new(
2812                "b",
2813                DataType::Dictionary(
2814                    Box::new(DataType::Int8),
2815                    Box::new(DataType::Decimal128(10, 0)),
2816                ),
2817                true,
2818            ),
2819        ]);
2820
2821        let value = 123;
2822        let decimal_array = Arc::new(create_decimal_array(
2823            &[
2824                Some(value),
2825                Some(value + 2),
2826                Some(value - 1),
2827                Some(value + 1),
2828            ],
2829            10,
2830            0,
2831        ));
2832
2833        let keys = Int8Array::from(vec![Some(0), Some(2), None, Some(3), Some(0)]);
2834        let a = DictionaryArray::try_new(keys, decimal_array)?;
2835
2836        let keys = Int8Array::from(vec![Some(0), None, Some(3), Some(2), Some(2)]);
2837        let decimal_array = Arc::new(create_decimal_array(
2838            &[
2839                Some(value + 1),
2840                Some(value + 3),
2841                Some(value),
2842                Some(value + 2),
2843            ],
2844            10,
2845            0,
2846        ));
2847        let b = DictionaryArray::try_new(keys, decimal_array)?;
2848
2849        apply_arithmetic(
2850            Arc::new(schema),
2851            vec![Arc::new(a), Arc::new(b)],
2852            Operator::Minus,
2853            create_decimal_array(&[Some(-1), None, None, Some(1), Some(0)], 11, 0),
2854        )?;
2855
2856        Ok(())
2857    }
2858
2859    #[test]
2860    fn minus_op_scalar() -> Result<()> {
2861        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
2862        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2863
2864        apply_arithmetic_scalar(
2865            Arc::new(schema),
2866            vec![Arc::new(a)],
2867            Operator::Minus,
2868            ScalarValue::Int32(Some(1)),
2869            Arc::new(Int32Array::from(vec![0, 1, 2, 3, 4])),
2870        )?;
2871
2872        Ok(())
2873    }
2874
2875    #[test]
2876    fn minus_op_dict_scalar() -> Result<()> {
2877        let schema = Schema::new(vec![Field::new(
2878            "a",
2879            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
2880            true,
2881        )]);
2882
2883        let mut dict_builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
2884
2885        dict_builder.append(1)?;
2886        dict_builder.append_null();
2887        dict_builder.append(2)?;
2888        dict_builder.append(5)?;
2889
2890        let a = dict_builder.finish();
2891
2892        let expected: PrimitiveArray<Int32Type> =
2893            PrimitiveArray::from(vec![Some(0), None, Some(1), Some(4)]);
2894
2895        apply_arithmetic_scalar(
2896            Arc::new(schema),
2897            vec![Arc::new(a)],
2898            Operator::Minus,
2899            ScalarValue::Dictionary(
2900                Box::new(DataType::Int8),
2901                Box::new(ScalarValue::Int32(Some(1))),
2902            ),
2903            Arc::new(expected),
2904        )?;
2905
2906        Ok(())
2907    }
2908
2909    #[test]
2910    fn minus_op_dict_scalar_decimal() -> Result<()> {
2911        let schema = Schema::new(vec![Field::new(
2912            "a",
2913            DataType::Dictionary(
2914                Box::new(DataType::Int8),
2915                Box::new(DataType::Decimal128(10, 0)),
2916            ),
2917            true,
2918        )]);
2919
2920        let value = 123;
2921        let decimal_array = Arc::new(create_decimal_array(
2922            &[Some(value), None, Some(value - 1), Some(value + 1)],
2923            10,
2924            0,
2925        ));
2926
2927        let keys = Int8Array::from(vec![0, 2, 1, 3, 0]);
2928        let a = DictionaryArray::try_new(keys, decimal_array)?;
2929
2930        let decimal_array = Arc::new(create_decimal_array(
2931            &[
2932                Some(value - 1),
2933                Some(value - 2),
2934                None,
2935                Some(value),
2936                Some(value - 1),
2937            ],
2938            11,
2939            0,
2940        ));
2941
2942        apply_arithmetic_scalar(
2943            Arc::new(schema),
2944            vec![Arc::new(a)],
2945            Operator::Minus,
2946            ScalarValue::Dictionary(
2947                Box::new(DataType::Int8),
2948                Box::new(ScalarValue::Decimal128(Some(1), 10, 0)),
2949            ),
2950            decimal_array,
2951        )?;
2952
2953        Ok(())
2954    }
2955
2956    #[test]
2957    fn multiply_op() -> Result<()> {
2958        let schema = Arc::new(Schema::new(vec![
2959            Field::new("a", DataType::Int32, false),
2960            Field::new("b", DataType::Int32, false),
2961        ]));
2962        let a = Arc::new(Int32Array::from(vec![4, 8, 16, 32, 64]));
2963        let b = Arc::new(Int32Array::from(vec![2, 4, 8, 16, 32]));
2964
2965        apply_arithmetic::<Int32Type>(
2966            schema,
2967            vec![a, b],
2968            Operator::Multiply,
2969            Int32Array::from(vec![8, 32, 128, 512, 2048]),
2970        )?;
2971
2972        Ok(())
2973    }
2974
2975    #[test]
2976    fn multiply_op_dict() -> Result<()> {
2977        let schema = Schema::new(vec![
2978            Field::new(
2979                "a",
2980                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
2981                true,
2982            ),
2983            Field::new(
2984                "b",
2985                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
2986                true,
2987            ),
2988        ]);
2989
2990        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
2991        let keys = Int8Array::from(vec![Some(0), None, Some(1), Some(3), None]);
2992        let a = DictionaryArray::try_new(keys, Arc::new(a))?;
2993
2994        let b = Int32Array::from(vec![1, 2, 4, 8, 16]);
2995        let keys = Int8Array::from(vec![0, 1, 1, 2, 1]);
2996        let b = DictionaryArray::try_new(keys, Arc::new(b))?;
2997
2998        apply_arithmetic::<Int32Type>(
2999            Arc::new(schema),
3000            vec![Arc::new(a), Arc::new(b)],
3001            Operator::Multiply,
3002            Int32Array::from(vec![Some(1), None, Some(4), Some(16), None]),
3003        )?;
3004
3005        Ok(())
3006    }
3007
3008    #[test]
3009    fn multiply_op_dict_decimal() -> Result<()> {
3010        let schema = Schema::new(vec![
3011            Field::new(
3012                "a",
3013                DataType::Dictionary(
3014                    Box::new(DataType::Int8),
3015                    Box::new(DataType::Decimal128(10, 0)),
3016                ),
3017                true,
3018            ),
3019            Field::new(
3020                "b",
3021                DataType::Dictionary(
3022                    Box::new(DataType::Int8),
3023                    Box::new(DataType::Decimal128(10, 0)),
3024                ),
3025                true,
3026            ),
3027        ]);
3028
3029        let value = 123;
3030        let decimal_array = Arc::new(create_decimal_array(
3031            &[
3032                Some(value),
3033                Some(value + 2),
3034                Some(value - 1),
3035                Some(value + 1),
3036            ],
3037            10,
3038            0,
3039        )) as ArrayRef;
3040
3041        let keys = Int8Array::from(vec![Some(0), Some(2), None, Some(3), Some(0)]);
3042        let a = DictionaryArray::try_new(keys, decimal_array)?;
3043
3044        let keys = Int8Array::from(vec![Some(0), None, Some(3), Some(2), Some(2)]);
3045        let decimal_array = Arc::new(create_decimal_array(
3046            &[
3047                Some(value + 1),
3048                Some(value + 3),
3049                Some(value),
3050                Some(value + 2),
3051            ],
3052            10,
3053            0,
3054        ));
3055        let b = DictionaryArray::try_new(keys, decimal_array)?;
3056
3057        apply_arithmetic(
3058            Arc::new(schema),
3059            vec![Arc::new(a), Arc::new(b)],
3060            Operator::Multiply,
3061            create_decimal_array(
3062                &[Some(15252), None, None, Some(15252), Some(15129)],
3063                21,
3064                0,
3065            ),
3066        )?;
3067
3068        Ok(())
3069    }
3070
3071    #[test]
3072    fn multiply_op_scalar() -> Result<()> {
3073        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3074        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
3075
3076        apply_arithmetic_scalar(
3077            Arc::new(schema),
3078            vec![Arc::new(a)],
3079            Operator::Multiply,
3080            ScalarValue::Int32(Some(2)),
3081            Arc::new(Int32Array::from(vec![2, 4, 6, 8, 10])),
3082        )?;
3083
3084        Ok(())
3085    }
3086
3087    #[test]
3088    fn multiply_op_dict_scalar() -> Result<()> {
3089        let schema = Schema::new(vec![Field::new(
3090            "a",
3091            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
3092            true,
3093        )]);
3094
3095        let mut dict_builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
3096
3097        dict_builder.append(1)?;
3098        dict_builder.append_null();
3099        dict_builder.append(2)?;
3100        dict_builder.append(5)?;
3101
3102        let a = dict_builder.finish();
3103
3104        let expected: PrimitiveArray<Int32Type> =
3105            PrimitiveArray::from(vec![Some(2), None, Some(4), Some(10)]);
3106
3107        apply_arithmetic_scalar(
3108            Arc::new(schema),
3109            vec![Arc::new(a)],
3110            Operator::Multiply,
3111            ScalarValue::Dictionary(
3112                Box::new(DataType::Int8),
3113                Box::new(ScalarValue::Int32(Some(2))),
3114            ),
3115            Arc::new(expected),
3116        )?;
3117
3118        Ok(())
3119    }
3120
3121    #[test]
3122    fn multiply_op_dict_scalar_decimal() -> Result<()> {
3123        let schema = Schema::new(vec![Field::new(
3124            "a",
3125            DataType::Dictionary(
3126                Box::new(DataType::Int8),
3127                Box::new(DataType::Decimal128(10, 0)),
3128            ),
3129            true,
3130        )]);
3131
3132        let value = 123;
3133        let decimal_array = Arc::new(create_decimal_array(
3134            &[Some(value), None, Some(value - 1), Some(value + 1)],
3135            10,
3136            0,
3137        ));
3138
3139        let keys = Int8Array::from(vec![0, 2, 1, 3, 0]);
3140        let a = DictionaryArray::try_new(keys, decimal_array)?;
3141
3142        let decimal_array = Arc::new(create_decimal_array(
3143            &[Some(246), Some(244), None, Some(248), Some(246)],
3144            21,
3145            0,
3146        ));
3147
3148        apply_arithmetic_scalar(
3149            Arc::new(schema),
3150            vec![Arc::new(a)],
3151            Operator::Multiply,
3152            ScalarValue::Dictionary(
3153                Box::new(DataType::Int8),
3154                Box::new(ScalarValue::Decimal128(Some(2), 10, 0)),
3155            ),
3156            decimal_array,
3157        )?;
3158
3159        Ok(())
3160    }
3161
3162    #[test]
3163    fn divide_op() -> Result<()> {
3164        let schema = Arc::new(Schema::new(vec![
3165            Field::new("a", DataType::Int32, false),
3166            Field::new("b", DataType::Int32, false),
3167        ]));
3168        let a = Arc::new(Int32Array::from(vec![8, 32, 128, 512, 2048]));
3169        let b = Arc::new(Int32Array::from(vec![2, 4, 8, 16, 32]));
3170
3171        apply_arithmetic::<Int32Type>(
3172            schema,
3173            vec![a, b],
3174            Operator::Divide,
3175            Int32Array::from(vec![4, 8, 16, 32, 64]),
3176        )?;
3177
3178        Ok(())
3179    }
3180
3181    #[test]
3182    fn divide_op_dict() -> Result<()> {
3183        let schema = Schema::new(vec![
3184            Field::new(
3185                "a",
3186                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
3187                true,
3188            ),
3189            Field::new(
3190                "b",
3191                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
3192                true,
3193            ),
3194        ]);
3195
3196        let mut dict_builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
3197
3198        dict_builder.append(1)?;
3199        dict_builder.append_null();
3200        dict_builder.append(2)?;
3201        dict_builder.append(5)?;
3202        dict_builder.append(0)?;
3203
3204        let a = dict_builder.finish();
3205
3206        let b = Int32Array::from(vec![1, 2, 4, 8, 16]);
3207        let keys = Int8Array::from(vec![0, 1, 1, 2, 1]);
3208        let b = DictionaryArray::try_new(keys, Arc::new(b))?;
3209
3210        apply_arithmetic::<Int32Type>(
3211            Arc::new(schema),
3212            vec![Arc::new(a), Arc::new(b)],
3213            Operator::Divide,
3214            Int32Array::from(vec![Some(1), None, Some(1), Some(1), Some(0)]),
3215        )?;
3216
3217        Ok(())
3218    }
3219
3220    #[test]
3221    fn divide_op_dict_decimal() -> Result<()> {
3222        let schema = Schema::new(vec![
3223            Field::new(
3224                "a",
3225                DataType::Dictionary(
3226                    Box::new(DataType::Int8),
3227                    Box::new(DataType::Decimal128(10, 0)),
3228                ),
3229                true,
3230            ),
3231            Field::new(
3232                "b",
3233                DataType::Dictionary(
3234                    Box::new(DataType::Int8),
3235                    Box::new(DataType::Decimal128(10, 0)),
3236                ),
3237                true,
3238            ),
3239        ]);
3240
3241        let value = 123;
3242        let decimal_array = Arc::new(create_decimal_array(
3243            &[
3244                Some(value),
3245                Some(value + 2),
3246                Some(value - 1),
3247                Some(value + 1),
3248            ],
3249            10,
3250            0,
3251        ));
3252
3253        let keys = Int8Array::from(vec![Some(0), Some(2), None, Some(3), Some(0)]);
3254        let a = DictionaryArray::try_new(keys, decimal_array)?;
3255
3256        let keys = Int8Array::from(vec![Some(0), None, Some(3), Some(2), Some(2)]);
3257        let decimal_array = Arc::new(create_decimal_array(
3258            &[
3259                Some(value + 1),
3260                Some(value + 3),
3261                Some(value),
3262                Some(value + 2),
3263            ],
3264            10,
3265            0,
3266        ));
3267        let b = DictionaryArray::try_new(keys, decimal_array)?;
3268
3269        apply_arithmetic(
3270            Arc::new(schema),
3271            vec![Arc::new(a), Arc::new(b)],
3272            Operator::Divide,
3273            create_decimal_array(
3274                &[
3275                    Some(9919), // 0.9919
3276                    None,
3277                    None,
3278                    Some(10081), // 1.0081
3279                    Some(10000), // 1.0
3280                ],
3281                14,
3282                4,
3283            ),
3284        )?;
3285
3286        Ok(())
3287    }
3288
3289    #[test]
3290    fn divide_op_scalar() -> Result<()> {
3291        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3292        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
3293
3294        apply_arithmetic_scalar(
3295            Arc::new(schema),
3296            vec![Arc::new(a)],
3297            Operator::Divide,
3298            ScalarValue::Int32(Some(2)),
3299            Arc::new(Int32Array::from(vec![0, 1, 1, 2, 2])),
3300        )?;
3301
3302        Ok(())
3303    }
3304
3305    #[test]
3306    fn divide_op_dict_scalar() -> Result<()> {
3307        let schema = Schema::new(vec![Field::new(
3308            "a",
3309            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
3310            true,
3311        )]);
3312
3313        let mut dict_builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
3314
3315        dict_builder.append(1)?;
3316        dict_builder.append_null();
3317        dict_builder.append(2)?;
3318        dict_builder.append(5)?;
3319
3320        let a = dict_builder.finish();
3321
3322        let expected: PrimitiveArray<Int32Type> =
3323            PrimitiveArray::from(vec![Some(0), None, Some(1), Some(2)]);
3324
3325        apply_arithmetic_scalar(
3326            Arc::new(schema),
3327            vec![Arc::new(a)],
3328            Operator::Divide,
3329            ScalarValue::Dictionary(
3330                Box::new(DataType::Int8),
3331                Box::new(ScalarValue::Int32(Some(2))),
3332            ),
3333            Arc::new(expected),
3334        )?;
3335
3336        Ok(())
3337    }
3338
3339    #[test]
3340    fn divide_op_dict_scalar_decimal() -> Result<()> {
3341        let schema = Schema::new(vec![Field::new(
3342            "a",
3343            DataType::Dictionary(
3344                Box::new(DataType::Int8),
3345                Box::new(DataType::Decimal128(10, 0)),
3346            ),
3347            true,
3348        )]);
3349
3350        let value = 123;
3351        let decimal_array = Arc::new(create_decimal_array(
3352            &[Some(value), None, Some(value - 1), Some(value + 1)],
3353            10,
3354            0,
3355        ));
3356
3357        let keys = Int8Array::from(vec![0, 2, 1, 3, 0]);
3358        let a = DictionaryArray::try_new(keys, decimal_array)?;
3359
3360        let decimal_array = Arc::new(create_decimal_array(
3361            &[Some(615000), Some(610000), None, Some(620000), Some(615000)],
3362            14,
3363            4,
3364        ));
3365
3366        apply_arithmetic_scalar(
3367            Arc::new(schema),
3368            vec![Arc::new(a)],
3369            Operator::Divide,
3370            ScalarValue::Dictionary(
3371                Box::new(DataType::Int8),
3372                Box::new(ScalarValue::Decimal128(Some(2), 10, 0)),
3373            ),
3374            decimal_array,
3375        )?;
3376
3377        Ok(())
3378    }
3379
3380    #[test]
3381    fn modulus_op() -> Result<()> {
3382        let schema = Arc::new(Schema::new(vec![
3383            Field::new("a", DataType::Int32, false),
3384            Field::new("b", DataType::Int32, false),
3385        ]));
3386        let a = Arc::new(Int32Array::from(vec![8, 32, 128, 512, 2048]));
3387        let b = Arc::new(Int32Array::from(vec![2, 4, 7, 14, 32]));
3388
3389        apply_arithmetic::<Int32Type>(
3390            schema,
3391            vec![a, b],
3392            Operator::Modulo,
3393            Int32Array::from(vec![0, 0, 2, 8, 0]),
3394        )?;
3395
3396        Ok(())
3397    }
3398
3399    #[test]
3400    fn modulus_op_dict() -> Result<()> {
3401        let schema = Schema::new(vec![
3402            Field::new(
3403                "a",
3404                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
3405                true,
3406            ),
3407            Field::new(
3408                "b",
3409                DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
3410                true,
3411            ),
3412        ]);
3413
3414        let mut dict_builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
3415
3416        dict_builder.append(1)?;
3417        dict_builder.append_null();
3418        dict_builder.append(2)?;
3419        dict_builder.append(5)?;
3420        dict_builder.append(0)?;
3421
3422        let a = dict_builder.finish();
3423
3424        let b = Int32Array::from(vec![1, 2, 4, 8, 16]);
3425        let keys = Int8Array::from(vec![0, 1, 1, 2, 1]);
3426        let b = DictionaryArray::try_new(keys, Arc::new(b))?;
3427
3428        apply_arithmetic::<Int32Type>(
3429            Arc::new(schema),
3430            vec![Arc::new(a), Arc::new(b)],
3431            Operator::Modulo,
3432            Int32Array::from(vec![Some(0), None, Some(0), Some(1), Some(0)]),
3433        )?;
3434
3435        Ok(())
3436    }
3437
3438    #[test]
3439    fn modulus_op_dict_decimal() -> Result<()> {
3440        let schema = Schema::new(vec![
3441            Field::new(
3442                "a",
3443                DataType::Dictionary(
3444                    Box::new(DataType::Int8),
3445                    Box::new(DataType::Decimal128(10, 0)),
3446                ),
3447                true,
3448            ),
3449            Field::new(
3450                "b",
3451                DataType::Dictionary(
3452                    Box::new(DataType::Int8),
3453                    Box::new(DataType::Decimal128(10, 0)),
3454                ),
3455                true,
3456            ),
3457        ]);
3458
3459        let value = 123;
3460        let decimal_array = Arc::new(create_decimal_array(
3461            &[
3462                Some(value),
3463                Some(value + 2),
3464                Some(value - 1),
3465                Some(value + 1),
3466            ],
3467            10,
3468            0,
3469        ));
3470
3471        let keys = Int8Array::from(vec![Some(0), Some(2), None, Some(3), Some(0)]);
3472        let a = DictionaryArray::try_new(keys, decimal_array)?;
3473
3474        let keys = Int8Array::from(vec![Some(0), None, Some(3), Some(2), Some(2)]);
3475        let decimal_array = Arc::new(create_decimal_array(
3476            &[
3477                Some(value + 1),
3478                Some(value + 3),
3479                Some(value),
3480                Some(value + 2),
3481            ],
3482            10,
3483            0,
3484        ));
3485        let b = DictionaryArray::try_new(keys, decimal_array)?;
3486
3487        apply_arithmetic(
3488            Arc::new(schema),
3489            vec![Arc::new(a), Arc::new(b)],
3490            Operator::Modulo,
3491            create_decimal_array(&[Some(123), None, None, Some(1), Some(0)], 10, 0),
3492        )?;
3493
3494        Ok(())
3495    }
3496
3497    #[test]
3498    fn modulus_op_scalar() -> Result<()> {
3499        let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3500        let a = Int32Array::from(vec![1, 2, 3, 4, 5]);
3501
3502        apply_arithmetic_scalar(
3503            Arc::new(schema),
3504            vec![Arc::new(a)],
3505            Operator::Modulo,
3506            ScalarValue::Int32(Some(2)),
3507            Arc::new(Int32Array::from(vec![1, 0, 1, 0, 1])),
3508        )?;
3509
3510        Ok(())
3511    }
3512
3513    #[test]
3514    fn modules_op_dict_scalar() -> Result<()> {
3515        let schema = Schema::new(vec![Field::new(
3516            "a",
3517            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Int32)),
3518            true,
3519        )]);
3520
3521        let mut dict_builder = PrimitiveDictionaryBuilder::<Int8Type, Int32Type>::new();
3522
3523        dict_builder.append(1)?;
3524        dict_builder.append_null();
3525        dict_builder.append(2)?;
3526        dict_builder.append(5)?;
3527
3528        let a = dict_builder.finish();
3529
3530        let expected: PrimitiveArray<Int32Type> =
3531            PrimitiveArray::from(vec![Some(1), None, Some(0), Some(1)]);
3532
3533        apply_arithmetic_scalar(
3534            Arc::new(schema),
3535            vec![Arc::new(a)],
3536            Operator::Modulo,
3537            ScalarValue::Dictionary(
3538                Box::new(DataType::Int8),
3539                Box::new(ScalarValue::Int32(Some(2))),
3540            ),
3541            Arc::new(expected),
3542        )?;
3543
3544        Ok(())
3545    }
3546
3547    #[test]
3548    fn modulus_op_dict_scalar_decimal() -> Result<()> {
3549        let schema = Schema::new(vec![Field::new(
3550            "a",
3551            DataType::Dictionary(
3552                Box::new(DataType::Int8),
3553                Box::new(DataType::Decimal128(10, 0)),
3554            ),
3555            true,
3556        )]);
3557
3558        let value = 123;
3559        let decimal_array = Arc::new(create_decimal_array(
3560            &[Some(value), None, Some(value - 1), Some(value + 1)],
3561            10,
3562            0,
3563        ));
3564
3565        let keys = Int8Array::from(vec![0, 2, 1, 3, 0]);
3566        let a = DictionaryArray::try_new(keys, decimal_array)?;
3567
3568        let decimal_array = Arc::new(create_decimal_array(
3569            &[Some(1), Some(0), None, Some(0), Some(1)],
3570            10,
3571            0,
3572        ));
3573
3574        apply_arithmetic_scalar(
3575            Arc::new(schema),
3576            vec![Arc::new(a)],
3577            Operator::Modulo,
3578            ScalarValue::Dictionary(
3579                Box::new(DataType::Int8),
3580                Box::new(ScalarValue::Decimal128(Some(2), 10, 0)),
3581            ),
3582            decimal_array,
3583        )?;
3584
3585        Ok(())
3586    }
3587
3588    fn apply_arithmetic<T: ArrowNumericType>(
3589        schema: SchemaRef,
3590        data: Vec<ArrayRef>,
3591        op: Operator,
3592        expected: PrimitiveArray<T>,
3593    ) -> Result<()> {
3594        let arithmetic_op =
3595            binary_op(col("a", &schema)?, op, col("b", &schema)?, &schema)?;
3596        let batch = RecordBatch::try_new(schema, data)?;
3597        let result = arithmetic_op
3598            .evaluate(&batch)?
3599            .into_array(batch.num_rows())
3600            .expect("Failed to convert to array");
3601
3602        assert_eq!(result.as_ref(), &expected);
3603        Ok(())
3604    }
3605
3606    fn apply_arithmetic_scalar(
3607        schema: SchemaRef,
3608        data: Vec<ArrayRef>,
3609        op: Operator,
3610        literal: ScalarValue,
3611        expected: ArrayRef,
3612    ) -> Result<()> {
3613        let lit = Arc::new(Literal::new(literal));
3614        let arithmetic_op = binary_op(col("a", &schema)?, op, lit, &schema)?;
3615        let batch = RecordBatch::try_new(schema, data)?;
3616        let result = arithmetic_op
3617            .evaluate(&batch)?
3618            .into_array(batch.num_rows())
3619            .expect("Failed to convert to array");
3620
3621        assert_eq!(&result, &expected);
3622        Ok(())
3623    }
3624
3625    fn apply_logic_op(
3626        schema: &SchemaRef,
3627        left: &ArrayRef,
3628        right: &ArrayRef,
3629        op: Operator,
3630        expected: BooleanArray,
3631    ) -> Result<()> {
3632        let op = binary_op(col("a", schema)?, op, col("b", schema)?, schema)?;
3633        let data: Vec<ArrayRef> = vec![Arc::clone(left), Arc::clone(right)];
3634        let batch = RecordBatch::try_new(Arc::clone(schema), data)?;
3635        let result = op
3636            .evaluate(&batch)?
3637            .into_array(batch.num_rows())
3638            .expect("Failed to convert to array");
3639
3640        assert_eq!(result.as_ref(), &expected);
3641        Ok(())
3642    }
3643
3644    // Test `scalar <op> arr` produces expected
3645    fn apply_logic_op_scalar_arr(
3646        schema: &SchemaRef,
3647        scalar: &ScalarValue,
3648        arr: &ArrayRef,
3649        op: Operator,
3650        expected: &BooleanArray,
3651    ) -> Result<()> {
3652        let scalar = lit(scalar.clone());
3653        let op = binary_op(scalar, op, col("a", schema)?, schema)?;
3654        let batch = RecordBatch::try_new(Arc::clone(schema), vec![Arc::clone(arr)])?;
3655        let result = op
3656            .evaluate(&batch)?
3657            .into_array(batch.num_rows())
3658            .expect("Failed to convert to array");
3659        assert_eq!(result.as_ref(), expected);
3660
3661        Ok(())
3662    }
3663
3664    // Test `arr <op> scalar` produces expected
3665    fn apply_logic_op_arr_scalar(
3666        schema: &SchemaRef,
3667        arr: &ArrayRef,
3668        scalar: &ScalarValue,
3669        op: Operator,
3670        expected: &BooleanArray,
3671    ) -> Result<()> {
3672        let scalar = lit(scalar.clone());
3673        let op = binary_op(col("a", schema)?, op, scalar, schema)?;
3674        let batch = RecordBatch::try_new(Arc::clone(schema), vec![Arc::clone(arr)])?;
3675        let result = op
3676            .evaluate(&batch)?
3677            .into_array(batch.num_rows())
3678            .expect("Failed to convert to array");
3679        assert_eq!(result.as_ref(), expected);
3680
3681        Ok(())
3682    }
3683
3684    #[test]
3685    fn and_with_nulls_op() -> Result<()> {
3686        let schema = Schema::new(vec![
3687            Field::new("a", DataType::Boolean, true),
3688            Field::new("b", DataType::Boolean, true),
3689        ]);
3690        let a = Arc::new(BooleanArray::from(vec![
3691            Some(true),
3692            Some(false),
3693            None,
3694            Some(true),
3695            Some(false),
3696            None,
3697            Some(true),
3698            Some(false),
3699            None,
3700        ])) as ArrayRef;
3701        let b = Arc::new(BooleanArray::from(vec![
3702            Some(true),
3703            Some(true),
3704            Some(true),
3705            Some(false),
3706            Some(false),
3707            Some(false),
3708            None,
3709            None,
3710            None,
3711        ])) as ArrayRef;
3712
3713        let expected = BooleanArray::from(vec![
3714            Some(true),
3715            Some(false),
3716            None,
3717            Some(false),
3718            Some(false),
3719            Some(false),
3720            None,
3721            Some(false),
3722            None,
3723        ]);
3724        apply_logic_op(&Arc::new(schema), &a, &b, Operator::And, expected)?;
3725
3726        Ok(())
3727    }
3728
3729    #[test]
3730    fn regex_with_nulls() -> Result<()> {
3731        let schema = Schema::new(vec![
3732            Field::new("a", DataType::Utf8, true),
3733            Field::new("b", DataType::Utf8, true),
3734        ]);
3735        let a = Arc::new(StringArray::from(vec![
3736            Some("abc"),
3737            None,
3738            Some("abc"),
3739            None,
3740            Some("abc"),
3741        ])) as ArrayRef;
3742        let b = Arc::new(StringArray::from(vec![
3743            Some("^a"),
3744            Some("^A"),
3745            None,
3746            None,
3747            Some("^(b|c)"),
3748        ])) as ArrayRef;
3749
3750        let regex_expected =
3751            BooleanArray::from(vec![Some(true), None, None, None, Some(false)]);
3752        let regex_not_expected =
3753            BooleanArray::from(vec![Some(false), None, None, None, Some(true)]);
3754        apply_logic_op(
3755            &Arc::new(schema.clone()),
3756            &a,
3757            &b,
3758            Operator::RegexMatch,
3759            regex_expected.clone(),
3760        )?;
3761        apply_logic_op(
3762            &Arc::new(schema.clone()),
3763            &a,
3764            &b,
3765            Operator::RegexIMatch,
3766            regex_expected.clone(),
3767        )?;
3768        apply_logic_op(
3769            &Arc::new(schema.clone()),
3770            &a,
3771            &b,
3772            Operator::RegexNotMatch,
3773            regex_not_expected.clone(),
3774        )?;
3775        apply_logic_op(
3776            &Arc::new(schema),
3777            &a,
3778            &b,
3779            Operator::RegexNotIMatch,
3780            regex_not_expected.clone(),
3781        )?;
3782
3783        let schema = Schema::new(vec![
3784            Field::new("a", DataType::LargeUtf8, true),
3785            Field::new("b", DataType::LargeUtf8, true),
3786        ]);
3787        let a = Arc::new(LargeStringArray::from(vec![
3788            Some("abc"),
3789            None,
3790            Some("abc"),
3791            None,
3792            Some("abc"),
3793        ])) as ArrayRef;
3794        let b = Arc::new(LargeStringArray::from(vec![
3795            Some("^a"),
3796            Some("^A"),
3797            None,
3798            None,
3799            Some("^(b|c)"),
3800        ])) as ArrayRef;
3801
3802        apply_logic_op(
3803            &Arc::new(schema.clone()),
3804            &a,
3805            &b,
3806            Operator::RegexMatch,
3807            regex_expected.clone(),
3808        )?;
3809        apply_logic_op(
3810            &Arc::new(schema.clone()),
3811            &a,
3812            &b,
3813            Operator::RegexIMatch,
3814            regex_expected,
3815        )?;
3816        apply_logic_op(
3817            &Arc::new(schema.clone()),
3818            &a,
3819            &b,
3820            Operator::RegexNotMatch,
3821            regex_not_expected.clone(),
3822        )?;
3823        apply_logic_op(
3824            &Arc::new(schema),
3825            &a,
3826            &b,
3827            Operator::RegexNotIMatch,
3828            regex_not_expected,
3829        )?;
3830
3831        Ok(())
3832    }
3833
3834    #[test]
3835    fn regex_scalar_with_dictionary_nulls() -> Result<()> {
3836        let dictionary_values = Arc::new(StringArray::from(vec![
3837            Some("abc"),
3838            None,
3839            Some("ABC"),
3840            Some("def"),
3841        ]));
3842        let keys = UInt32Array::from(vec![Some(0), None, Some(1), Some(2), Some(3)]);
3843        let dictionary =
3844            Arc::new(DictionaryArray::try_new(keys, dictionary_values)?) as ArrayRef;
3845        let utf8 = cast(&dictionary, &DataType::Utf8)?;
3846        let pattern = ScalarValue::Utf8(Some("^abc$".to_string()));
3847        let dictionary_schema = Arc::new(Schema::new(vec![Field::new(
3848            "a",
3849            dictionary.data_type().clone(),
3850            true,
3851        )]));
3852        let utf8_schema =
3853            Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, true)]));
3854
3855        let evaluate =
3856            |schema: &SchemaRef, array: &ArrayRef, op: Operator| -> Result<ArrayRef> {
3857                let expr = binary(col("a", schema)?, op, lit(pattern.clone()), schema)?;
3858                let batch =
3859                    RecordBatch::try_new(Arc::clone(schema), vec![Arc::clone(array)])?;
3860                Ok(expr
3861                    .evaluate(&batch)?
3862                    .into_array(batch.num_rows())
3863                    .expect("Failed to convert to array"))
3864            };
3865
3866        for (op, expected) in [
3867            (
3868                Operator::RegexMatch,
3869                BooleanArray::from(vec![
3870                    Some(true),
3871                    None,
3872                    None,
3873                    Some(false),
3874                    Some(false),
3875                ]),
3876            ),
3877            (
3878                Operator::RegexIMatch,
3879                BooleanArray::from(vec![Some(true), None, None, Some(true), Some(false)]),
3880            ),
3881            (
3882                Operator::RegexNotMatch,
3883                BooleanArray::from(vec![Some(false), None, None, Some(true), Some(true)]),
3884            ),
3885            (
3886                Operator::RegexNotIMatch,
3887                BooleanArray::from(vec![
3888                    Some(false),
3889                    None,
3890                    None,
3891                    Some(false),
3892                    Some(true),
3893                ]),
3894            ),
3895        ] {
3896            let dictionary_result = evaluate(&dictionary_schema, &dictionary, op)?;
3897            let utf8_result = evaluate(&utf8_schema, &utf8, op)?;
3898
3899            assert_eq!(dictionary_result.as_ref(), &expected);
3900            assert_eq!(&dictionary_result, &utf8_result);
3901        }
3902
3903        Ok(())
3904    }
3905
3906    #[test]
3907    fn regex_mismatched_array_types_error() -> Result<()> {
3908        // The analyzer coerces both operands of a regex operator to a common
3909        // string type, but an expression that bypasses it (e.g. constructed
3910        // directly) must return an error instead of panicking
3911        // (https://github.com/apache/datafusion/issues/22886)
3912        let schema = Schema::new(vec![
3913            Field::new("a", DataType::Utf8View, true),
3914            Field::new("b", DataType::Utf8, true),
3915        ]);
3916        let a = Arc::new(StringViewArray::from(vec!["user auth failed"])) as ArrayRef;
3917        let b = Arc::new(StringArray::from(vec!["(auth|login)"])) as ArrayRef;
3918
3919        // construct the expression directly, without coercion
3920        let expr = binary(
3921            col("a", &schema)?,
3922            Operator::RegexMatch,
3923            col("b", &schema)?,
3924            &schema,
3925        )?;
3926        let batch = RecordBatch::try_new(Arc::new(schema), vec![a, b])?;
3927        let err = expr.evaluate(&batch).unwrap_err();
3928        assert_contains!(err.to_string(), "failed to downcast array");
3929
3930        Ok(())
3931    }
3932
3933    #[test]
3934    fn or_with_nulls_op() -> Result<()> {
3935        let schema = Schema::new(vec![
3936            Field::new("a", DataType::Boolean, true),
3937            Field::new("b", DataType::Boolean, true),
3938        ]);
3939        let a = Arc::new(BooleanArray::from(vec![
3940            Some(true),
3941            Some(false),
3942            None,
3943            Some(true),
3944            Some(false),
3945            None,
3946            Some(true),
3947            Some(false),
3948            None,
3949        ])) as ArrayRef;
3950        let b = Arc::new(BooleanArray::from(vec![
3951            Some(true),
3952            Some(true),
3953            Some(true),
3954            Some(false),
3955            Some(false),
3956            Some(false),
3957            None,
3958            None,
3959            None,
3960        ])) as ArrayRef;
3961
3962        let expected = BooleanArray::from(vec![
3963            Some(true),
3964            Some(true),
3965            Some(true),
3966            Some(true),
3967            Some(false),
3968            None,
3969            Some(true),
3970            None,
3971            None,
3972        ]);
3973        apply_logic_op(&Arc::new(schema), &a, &b, Operator::Or, expected)?;
3974
3975        Ok(())
3976    }
3977
3978    /// Returns (schema, a: BooleanArray, b: BooleanArray) with all possible inputs
3979    ///
3980    /// a: [true, true, true,  NULL, NULL, NULL,  false, false, false]
3981    /// b: [true, NULL, false, true, NULL, false, true,  NULL,  false]
3982    fn bool_test_arrays() -> (SchemaRef, ArrayRef, ArrayRef) {
3983        let schema = Schema::new(vec![
3984            Field::new("a", DataType::Boolean, true),
3985            Field::new("b", DataType::Boolean, true),
3986        ]);
3987        let a: BooleanArray = [
3988            Some(true),
3989            Some(true),
3990            Some(true),
3991            None,
3992            None,
3993            None,
3994            Some(false),
3995            Some(false),
3996            Some(false),
3997        ]
3998        .iter()
3999        .collect();
4000        let b: BooleanArray = [
4001            Some(true),
4002            None,
4003            Some(false),
4004            Some(true),
4005            None,
4006            Some(false),
4007            Some(true),
4008            None,
4009            Some(false),
4010        ]
4011        .iter()
4012        .collect();
4013        (Arc::new(schema), Arc::new(a), Arc::new(b))
4014    }
4015
4016    /// Returns (schema, BooleanArray) with [true, NULL, false]
4017    fn scalar_bool_test_array() -> (SchemaRef, ArrayRef) {
4018        let schema = Schema::new(vec![Field::new("a", DataType::Boolean, true)]);
4019        let a: BooleanArray = [Some(true), None, Some(false)].iter().collect();
4020        (Arc::new(schema), Arc::new(a))
4021    }
4022
4023    #[test]
4024    fn eq_op_bool() {
4025        let (schema, a, b) = bool_test_arrays();
4026        let expected = [
4027            Some(true),
4028            None,
4029            Some(false),
4030            None,
4031            None,
4032            None,
4033            Some(false),
4034            None,
4035            Some(true),
4036        ]
4037        .iter()
4038        .collect();
4039        apply_logic_op(&schema, &a, &b, Operator::Eq, expected).unwrap();
4040    }
4041
4042    #[test]
4043    fn eq_op_bool_scalar() {
4044        let (schema, a) = scalar_bool_test_array();
4045        let expected = [Some(true), None, Some(false)].iter().collect();
4046        apply_logic_op_scalar_arr(
4047            &schema,
4048            &ScalarValue::from(true),
4049            &a,
4050            Operator::Eq,
4051            &expected,
4052        )
4053        .unwrap();
4054        apply_logic_op_arr_scalar(
4055            &schema,
4056            &a,
4057            &ScalarValue::from(true),
4058            Operator::Eq,
4059            &expected,
4060        )
4061        .unwrap();
4062
4063        let expected = [Some(false), None, Some(true)].iter().collect();
4064        apply_logic_op_scalar_arr(
4065            &schema,
4066            &ScalarValue::from(false),
4067            &a,
4068            Operator::Eq,
4069            &expected,
4070        )
4071        .unwrap();
4072        apply_logic_op_arr_scalar(
4073            &schema,
4074            &a,
4075            &ScalarValue::from(false),
4076            Operator::Eq,
4077            &expected,
4078        )
4079        .unwrap();
4080    }
4081
4082    #[test]
4083    fn neq_op_bool() {
4084        let (schema, a, b) = bool_test_arrays();
4085        let expected = [
4086            Some(false),
4087            None,
4088            Some(true),
4089            None,
4090            None,
4091            None,
4092            Some(true),
4093            None,
4094            Some(false),
4095        ]
4096        .iter()
4097        .collect();
4098        apply_logic_op(&schema, &a, &b, Operator::NotEq, expected).unwrap();
4099    }
4100
4101    #[test]
4102    fn neq_op_bool_scalar() {
4103        let (schema, a) = scalar_bool_test_array();
4104        let expected = [Some(false), None, Some(true)].iter().collect();
4105        apply_logic_op_scalar_arr(
4106            &schema,
4107            &ScalarValue::from(true),
4108            &a,
4109            Operator::NotEq,
4110            &expected,
4111        )
4112        .unwrap();
4113        apply_logic_op_arr_scalar(
4114            &schema,
4115            &a,
4116            &ScalarValue::from(true),
4117            Operator::NotEq,
4118            &expected,
4119        )
4120        .unwrap();
4121
4122        let expected = [Some(true), None, Some(false)].iter().collect();
4123        apply_logic_op_scalar_arr(
4124            &schema,
4125            &ScalarValue::from(false),
4126            &a,
4127            Operator::NotEq,
4128            &expected,
4129        )
4130        .unwrap();
4131        apply_logic_op_arr_scalar(
4132            &schema,
4133            &a,
4134            &ScalarValue::from(false),
4135            Operator::NotEq,
4136            &expected,
4137        )
4138        .unwrap();
4139    }
4140
4141    #[test]
4142    fn lt_op_bool() {
4143        let (schema, a, b) = bool_test_arrays();
4144        let expected = [
4145            Some(false),
4146            None,
4147            Some(false),
4148            None,
4149            None,
4150            None,
4151            Some(true),
4152            None,
4153            Some(false),
4154        ]
4155        .iter()
4156        .collect();
4157        apply_logic_op(&schema, &a, &b, Operator::Lt, expected).unwrap();
4158    }
4159
4160    #[test]
4161    fn lt_op_bool_scalar() {
4162        let (schema, a) = scalar_bool_test_array();
4163        let expected = [Some(false), None, Some(false)].iter().collect();
4164        apply_logic_op_scalar_arr(
4165            &schema,
4166            &ScalarValue::from(true),
4167            &a,
4168            Operator::Lt,
4169            &expected,
4170        )
4171        .unwrap();
4172
4173        let expected = [Some(false), None, Some(true)].iter().collect();
4174        apply_logic_op_arr_scalar(
4175            &schema,
4176            &a,
4177            &ScalarValue::from(true),
4178            Operator::Lt,
4179            &expected,
4180        )
4181        .unwrap();
4182
4183        let expected = [Some(true), None, Some(false)].iter().collect();
4184        apply_logic_op_scalar_arr(
4185            &schema,
4186            &ScalarValue::from(false),
4187            &a,
4188            Operator::Lt,
4189            &expected,
4190        )
4191        .unwrap();
4192
4193        let expected = [Some(false), None, Some(false)].iter().collect();
4194        apply_logic_op_arr_scalar(
4195            &schema,
4196            &a,
4197            &ScalarValue::from(false),
4198            Operator::Lt,
4199            &expected,
4200        )
4201        .unwrap();
4202    }
4203
4204    #[test]
4205    fn lt_eq_op_bool() {
4206        let (schema, a, b) = bool_test_arrays();
4207        let expected = [
4208            Some(true),
4209            None,
4210            Some(false),
4211            None,
4212            None,
4213            None,
4214            Some(true),
4215            None,
4216            Some(true),
4217        ]
4218        .iter()
4219        .collect();
4220        apply_logic_op(&schema, &a, &b, Operator::LtEq, expected).unwrap();
4221    }
4222
4223    #[test]
4224    fn lt_eq_op_bool_scalar() {
4225        let (schema, a) = scalar_bool_test_array();
4226        let expected = [Some(true), None, Some(false)].iter().collect();
4227        apply_logic_op_scalar_arr(
4228            &schema,
4229            &ScalarValue::from(true),
4230            &a,
4231            Operator::LtEq,
4232            &expected,
4233        )
4234        .unwrap();
4235
4236        let expected = [Some(true), None, Some(true)].iter().collect();
4237        apply_logic_op_arr_scalar(
4238            &schema,
4239            &a,
4240            &ScalarValue::from(true),
4241            Operator::LtEq,
4242            &expected,
4243        )
4244        .unwrap();
4245
4246        let expected = [Some(true), None, Some(true)].iter().collect();
4247        apply_logic_op_scalar_arr(
4248            &schema,
4249            &ScalarValue::from(false),
4250            &a,
4251            Operator::LtEq,
4252            &expected,
4253        )
4254        .unwrap();
4255
4256        let expected = [Some(false), None, Some(true)].iter().collect();
4257        apply_logic_op_arr_scalar(
4258            &schema,
4259            &a,
4260            &ScalarValue::from(false),
4261            Operator::LtEq,
4262            &expected,
4263        )
4264        .unwrap();
4265    }
4266
4267    #[test]
4268    fn gt_op_bool() {
4269        let (schema, a, b) = bool_test_arrays();
4270        let expected = [
4271            Some(false),
4272            None,
4273            Some(true),
4274            None,
4275            None,
4276            None,
4277            Some(false),
4278            None,
4279            Some(false),
4280        ]
4281        .iter()
4282        .collect();
4283        apply_logic_op(&schema, &a, &b, Operator::Gt, expected).unwrap();
4284    }
4285
4286    #[test]
4287    fn gt_op_bool_scalar() {
4288        let (schema, a) = scalar_bool_test_array();
4289        let expected = [Some(false), None, Some(true)].iter().collect();
4290        apply_logic_op_scalar_arr(
4291            &schema,
4292            &ScalarValue::from(true),
4293            &a,
4294            Operator::Gt,
4295            &expected,
4296        )
4297        .unwrap();
4298
4299        let expected = [Some(false), None, Some(false)].iter().collect();
4300        apply_logic_op_arr_scalar(
4301            &schema,
4302            &a,
4303            &ScalarValue::from(true),
4304            Operator::Gt,
4305            &expected,
4306        )
4307        .unwrap();
4308
4309        let expected = [Some(false), None, Some(false)].iter().collect();
4310        apply_logic_op_scalar_arr(
4311            &schema,
4312            &ScalarValue::from(false),
4313            &a,
4314            Operator::Gt,
4315            &expected,
4316        )
4317        .unwrap();
4318
4319        let expected = [Some(true), None, Some(false)].iter().collect();
4320        apply_logic_op_arr_scalar(
4321            &schema,
4322            &a,
4323            &ScalarValue::from(false),
4324            Operator::Gt,
4325            &expected,
4326        )
4327        .unwrap();
4328    }
4329
4330    #[test]
4331    fn gt_eq_op_bool() {
4332        let (schema, a, b) = bool_test_arrays();
4333        let expected = [
4334            Some(true),
4335            None,
4336            Some(true),
4337            None,
4338            None,
4339            None,
4340            Some(false),
4341            None,
4342            Some(true),
4343        ]
4344        .iter()
4345        .collect();
4346        apply_logic_op(&schema, &a, &b, Operator::GtEq, expected).unwrap();
4347    }
4348
4349    #[test]
4350    fn gt_eq_op_bool_scalar() {
4351        let (schema, a) = scalar_bool_test_array();
4352        let expected = [Some(true), None, Some(true)].iter().collect();
4353        apply_logic_op_scalar_arr(
4354            &schema,
4355            &ScalarValue::from(true),
4356            &a,
4357            Operator::GtEq,
4358            &expected,
4359        )
4360        .unwrap();
4361
4362        let expected = [Some(true), None, Some(false)].iter().collect();
4363        apply_logic_op_arr_scalar(
4364            &schema,
4365            &a,
4366            &ScalarValue::from(true),
4367            Operator::GtEq,
4368            &expected,
4369        )
4370        .unwrap();
4371
4372        let expected = [Some(false), None, Some(true)].iter().collect();
4373        apply_logic_op_scalar_arr(
4374            &schema,
4375            &ScalarValue::from(false),
4376            &a,
4377            Operator::GtEq,
4378            &expected,
4379        )
4380        .unwrap();
4381
4382        let expected = [Some(true), None, Some(true)].iter().collect();
4383        apply_logic_op_arr_scalar(
4384            &schema,
4385            &a,
4386            &ScalarValue::from(false),
4387            Operator::GtEq,
4388            &expected,
4389        )
4390        .unwrap();
4391    }
4392
4393    #[test]
4394    fn is_distinct_from_op_bool() {
4395        let (schema, a, b) = bool_test_arrays();
4396        let expected = [
4397            Some(false),
4398            Some(true),
4399            Some(true),
4400            Some(true),
4401            Some(false),
4402            Some(true),
4403            Some(true),
4404            Some(true),
4405            Some(false),
4406        ]
4407        .iter()
4408        .collect();
4409        apply_logic_op(&schema, &a, &b, Operator::IsDistinctFrom, expected).unwrap();
4410    }
4411
4412    #[test]
4413    fn distinct_from_op_nullability() -> Result<()> {
4414        let schema = Schema::new(vec![
4415            Field::new("nullable", DataType::Boolean, true),
4416            Field::new("non_nullable", DataType::Boolean, false),
4417        ]);
4418        let cases = [
4419            (Operator::IsDistinctFrom, "nullable", false),
4420            (Operator::IsNotDistinctFrom, "nullable", false),
4421            (Operator::Eq, "nullable", true),
4422            (Operator::Eq, "non_nullable", false),
4423        ];
4424
4425        for (op, column, expected) in cases {
4426            let expr = BinaryExpr::new(col(column, &schema)?, op, lit(true));
4427            assert_eq!(expr.nullable(&schema)?, expected, "{op} with {column}");
4428        }
4429
4430        Ok(())
4431    }
4432
4433    #[test]
4434    fn is_not_distinct_from_op_bool() {
4435        let (schema, a, b) = bool_test_arrays();
4436        let expected = [
4437            Some(true),
4438            Some(false),
4439            Some(false),
4440            Some(false),
4441            Some(true),
4442            Some(false),
4443            Some(false),
4444            Some(false),
4445            Some(true),
4446        ]
4447        .iter()
4448        .collect();
4449        apply_logic_op(&schema, &a, &b, Operator::IsNotDistinctFrom, expected).unwrap();
4450    }
4451
4452    #[test]
4453    fn relatively_deeply_nested() {
4454        // Reproducer for https://github.com/apache/datafusion/issues/419
4455
4456        // where even relatively shallow binary expressions overflowed
4457        // the stack in debug builds
4458
4459        let input: Vec<_> = vec![1, 2, 3, 4, 5].into_iter().map(Some).collect();
4460        let a: Int32Array = input.iter().collect();
4461
4462        let batch = RecordBatch::try_from_iter(vec![("a", Arc::new(a) as _)]).unwrap();
4463        let schema = batch.schema();
4464
4465        // build a left deep tree ((((a + a) + a) + a ....
4466        let tree_depth: i32 = 100;
4467        let expr = (0..tree_depth)
4468            .map(|_| col("a", schema.as_ref()).unwrap())
4469            .reduce(|l, r| binary(l, Operator::Plus, r, &schema).unwrap())
4470            .unwrap();
4471
4472        let result = expr
4473            .evaluate(&batch)
4474            .expect("evaluation")
4475            .into_array(batch.num_rows())
4476            .expect("Failed to convert to array");
4477
4478        let expected: Int32Array = input
4479            .into_iter()
4480            .map(|i| i.map(|i| i * tree_depth))
4481            .collect();
4482        assert_eq!(result.as_ref(), &expected);
4483    }
4484
4485    fn create_decimal_array(
4486        array: &[Option<i128>],
4487        precision: u8,
4488        scale: i8,
4489    ) -> Decimal128Array {
4490        let mut decimal_builder = Decimal128Builder::with_capacity(array.len());
4491        for value in array.iter().copied() {
4492            decimal_builder.append_option(value)
4493        }
4494        decimal_builder
4495            .finish()
4496            .with_precision_and_scale(precision, scale)
4497            .unwrap()
4498    }
4499
4500    #[test]
4501    fn comparison_dict_decimal_scalar_expr_test() -> Result<()> {
4502        // scalar of decimal compare with dictionary decimal array
4503        let value_i128 = 123;
4504        let decimal_scalar = ScalarValue::Dictionary(
4505            Box::new(DataType::Int8),
4506            Box::new(ScalarValue::Decimal128(Some(value_i128), 25, 3)),
4507        );
4508        let schema = Arc::new(Schema::new(vec![Field::new(
4509            "a",
4510            DataType::Dictionary(
4511                Box::new(DataType::Int8),
4512                Box::new(DataType::Decimal128(25, 3)),
4513            ),
4514            true,
4515        )]));
4516        let decimal_array = Arc::new(create_decimal_array(
4517            &[
4518                Some(value_i128),
4519                None,
4520                Some(value_i128 - 1),
4521                Some(value_i128 + 1),
4522            ],
4523            25,
4524            3,
4525        ));
4526
4527        let keys = Int8Array::from(vec![Some(0), None, Some(2), Some(3)]);
4528        let dictionary =
4529            Arc::new(DictionaryArray::try_new(keys, decimal_array)?) as ArrayRef;
4530
4531        // array = scalar
4532        apply_logic_op_arr_scalar(
4533            &schema,
4534            &dictionary,
4535            &decimal_scalar,
4536            Operator::Eq,
4537            &BooleanArray::from(vec![Some(true), None, Some(false), Some(false)]),
4538        )
4539        .unwrap();
4540        // array != scalar
4541        apply_logic_op_arr_scalar(
4542            &schema,
4543            &dictionary,
4544            &decimal_scalar,
4545            Operator::NotEq,
4546            &BooleanArray::from(vec![Some(false), None, Some(true), Some(true)]),
4547        )
4548        .unwrap();
4549        //  array < scalar
4550        apply_logic_op_arr_scalar(
4551            &schema,
4552            &dictionary,
4553            &decimal_scalar,
4554            Operator::Lt,
4555            &BooleanArray::from(vec![Some(false), None, Some(true), Some(false)]),
4556        )
4557        .unwrap();
4558
4559        //  array <= scalar
4560        apply_logic_op_arr_scalar(
4561            &schema,
4562            &dictionary,
4563            &decimal_scalar,
4564            Operator::LtEq,
4565            &BooleanArray::from(vec![Some(true), None, Some(true), Some(false)]),
4566        )
4567        .unwrap();
4568        // array > scalar
4569        apply_logic_op_arr_scalar(
4570            &schema,
4571            &dictionary,
4572            &decimal_scalar,
4573            Operator::Gt,
4574            &BooleanArray::from(vec![Some(false), None, Some(false), Some(true)]),
4575        )
4576        .unwrap();
4577
4578        // array >= scalar
4579        apply_logic_op_arr_scalar(
4580            &schema,
4581            &dictionary,
4582            &decimal_scalar,
4583            Operator::GtEq,
4584            &BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),
4585        )
4586        .unwrap();
4587
4588        Ok(())
4589    }
4590
4591    #[test]
4592    fn comparison_decimal_expr_test() -> Result<()> {
4593        // scalar of decimal compare with decimal array
4594        let value_i128 = 123;
4595        let decimal_scalar = ScalarValue::Decimal128(Some(value_i128), 25, 3);
4596        let schema = Arc::new(Schema::new(vec![Field::new(
4597            "a",
4598            DataType::Decimal128(25, 3),
4599            true,
4600        )]));
4601        let decimal_array = Arc::new(create_decimal_array(
4602            &[
4603                Some(value_i128),
4604                None,
4605                Some(value_i128 - 1),
4606                Some(value_i128 + 1),
4607            ],
4608            25,
4609            3,
4610        )) as ArrayRef;
4611        // array = scalar
4612        apply_logic_op_arr_scalar(
4613            &schema,
4614            &decimal_array,
4615            &decimal_scalar,
4616            Operator::Eq,
4617            &BooleanArray::from(vec![Some(true), None, Some(false), Some(false)]),
4618        )
4619        .unwrap();
4620        // array != scalar
4621        apply_logic_op_arr_scalar(
4622            &schema,
4623            &decimal_array,
4624            &decimal_scalar,
4625            Operator::NotEq,
4626            &BooleanArray::from(vec![Some(false), None, Some(true), Some(true)]),
4627        )
4628        .unwrap();
4629        //  array < scalar
4630        apply_logic_op_arr_scalar(
4631            &schema,
4632            &decimal_array,
4633            &decimal_scalar,
4634            Operator::Lt,
4635            &BooleanArray::from(vec![Some(false), None, Some(true), Some(false)]),
4636        )
4637        .unwrap();
4638
4639        //  array <= scalar
4640        apply_logic_op_arr_scalar(
4641            &schema,
4642            &decimal_array,
4643            &decimal_scalar,
4644            Operator::LtEq,
4645            &BooleanArray::from(vec![Some(true), None, Some(true), Some(false)]),
4646        )
4647        .unwrap();
4648        // array > scalar
4649        apply_logic_op_arr_scalar(
4650            &schema,
4651            &decimal_array,
4652            &decimal_scalar,
4653            Operator::Gt,
4654            &BooleanArray::from(vec![Some(false), None, Some(false), Some(true)]),
4655        )
4656        .unwrap();
4657
4658        // array >= scalar
4659        apply_logic_op_arr_scalar(
4660            &schema,
4661            &decimal_array,
4662            &decimal_scalar,
4663            Operator::GtEq,
4664            &BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),
4665        )
4666        .unwrap();
4667
4668        // scalar of different data type with decimal array
4669        let decimal_scalar = ScalarValue::Decimal128(Some(123_456), 10, 3);
4670        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int64, true)]));
4671        // scalar == array
4672        apply_logic_op_scalar_arr(
4673            &schema,
4674            &decimal_scalar,
4675            &(Arc::new(Int64Array::from(vec![Some(124), None])) as ArrayRef),
4676            Operator::Eq,
4677            &BooleanArray::from(vec![Some(false), None]),
4678        )
4679        .unwrap();
4680
4681        // array != scalar
4682        apply_logic_op_arr_scalar(
4683            &schema,
4684            &(Arc::new(Int64Array::from(vec![Some(123), None, Some(1)])) as ArrayRef),
4685            &decimal_scalar,
4686            Operator::NotEq,
4687            &BooleanArray::from(vec![Some(true), None, Some(true)]),
4688        )
4689        .unwrap();
4690
4691        // array < scalar
4692        apply_logic_op_arr_scalar(
4693            &schema,
4694            &(Arc::new(Int64Array::from(vec![Some(123), None, Some(124)])) as ArrayRef),
4695            &decimal_scalar,
4696            Operator::Lt,
4697            &BooleanArray::from(vec![Some(true), None, Some(false)]),
4698        )
4699        .unwrap();
4700
4701        // array > scalar
4702        apply_logic_op_arr_scalar(
4703            &schema,
4704            &(Arc::new(Int64Array::from(vec![Some(123), None, Some(124)])) as ArrayRef),
4705            &decimal_scalar,
4706            Operator::Gt,
4707            &BooleanArray::from(vec![Some(false), None, Some(true)]),
4708        )
4709        .unwrap();
4710
4711        let schema =
4712            Arc::new(Schema::new(vec![Field::new("a", DataType::Float64, true)]));
4713        // array == scalar
4714        apply_logic_op_arr_scalar(
4715            &schema,
4716            &(Arc::new(Float64Array::from(vec![Some(123.456), None, Some(123.457)]))
4717                as ArrayRef),
4718            &decimal_scalar,
4719            Operator::Eq,
4720            &BooleanArray::from(vec![Some(true), None, Some(false)]),
4721        )
4722        .unwrap();
4723
4724        // array <= scalar
4725        apply_logic_op_arr_scalar(
4726            &schema,
4727            &(Arc::new(Float64Array::from(vec![
4728                Some(123.456),
4729                None,
4730                Some(123.457),
4731                Some(123.45),
4732            ])) as ArrayRef),
4733            &decimal_scalar,
4734            Operator::LtEq,
4735            &BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),
4736        )
4737        .unwrap();
4738        // array >= scalar
4739        apply_logic_op_arr_scalar(
4740            &schema,
4741            &(Arc::new(Float64Array::from(vec![
4742                Some(123.456),
4743                None,
4744                Some(123.457),
4745                Some(123.45),
4746            ])) as ArrayRef),
4747            &decimal_scalar,
4748            Operator::GtEq,
4749            &BooleanArray::from(vec![Some(true), None, Some(true), Some(false)]),
4750        )
4751        .unwrap();
4752
4753        let value: i128 = 123;
4754        let decimal_array = Arc::new(create_decimal_array(
4755            &[Some(value), None, Some(value - 1), Some(value + 1)],
4756            10,
4757            0,
4758        )) as ArrayRef;
4759
4760        // comparison array op for decimal array
4761        let schema = Arc::new(Schema::new(vec![
4762            Field::new("a", DataType::Decimal128(10, 0), true),
4763            Field::new("b", DataType::Decimal128(10, 0), true),
4764        ]));
4765        let right_decimal_array = Arc::new(create_decimal_array(
4766            &[
4767                Some(value - 1),
4768                Some(value),
4769                Some(value + 1),
4770                Some(value + 1),
4771            ],
4772            10,
4773            0,
4774        )) as ArrayRef;
4775
4776        apply_logic_op(
4777            &schema,
4778            &decimal_array,
4779            &right_decimal_array,
4780            Operator::Eq,
4781            BooleanArray::from(vec![Some(false), None, Some(false), Some(true)]),
4782        )
4783        .unwrap();
4784
4785        apply_logic_op(
4786            &schema,
4787            &decimal_array,
4788            &right_decimal_array,
4789            Operator::NotEq,
4790            BooleanArray::from(vec![Some(true), None, Some(true), Some(false)]),
4791        )
4792        .unwrap();
4793
4794        apply_logic_op(
4795            &schema,
4796            &decimal_array,
4797            &right_decimal_array,
4798            Operator::Lt,
4799            BooleanArray::from(vec![Some(false), None, Some(true), Some(false)]),
4800        )
4801        .unwrap();
4802
4803        apply_logic_op(
4804            &schema,
4805            &decimal_array,
4806            &right_decimal_array,
4807            Operator::LtEq,
4808            BooleanArray::from(vec![Some(false), None, Some(true), Some(true)]),
4809        )
4810        .unwrap();
4811
4812        apply_logic_op(
4813            &schema,
4814            &decimal_array,
4815            &right_decimal_array,
4816            Operator::Gt,
4817            BooleanArray::from(vec![Some(true), None, Some(false), Some(false)]),
4818        )
4819        .unwrap();
4820
4821        apply_logic_op(
4822            &schema,
4823            &decimal_array,
4824            &right_decimal_array,
4825            Operator::GtEq,
4826            BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),
4827        )
4828        .unwrap();
4829
4830        // compare decimal array with other array type
4831        let value: i64 = 123;
4832        let schema = Arc::new(Schema::new(vec![
4833            Field::new("a", DataType::Int64, true),
4834            Field::new("b", DataType::Decimal128(10, 0), true),
4835        ]));
4836
4837        let int64_array = Arc::new(Int64Array::from(vec![
4838            Some(value),
4839            Some(value - 1),
4840            Some(value),
4841            Some(value + 1),
4842        ])) as ArrayRef;
4843
4844        // eq: int64array == decimal array
4845        apply_logic_op(
4846            &schema,
4847            &int64_array,
4848            &decimal_array,
4849            Operator::Eq,
4850            BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),
4851        )
4852        .unwrap();
4853        // neq: int64array != decimal array
4854        apply_logic_op(
4855            &schema,
4856            &int64_array,
4857            &decimal_array,
4858            Operator::NotEq,
4859            BooleanArray::from(vec![Some(false), None, Some(true), Some(false)]),
4860        )
4861        .unwrap();
4862
4863        let schema = Arc::new(Schema::new(vec![
4864            Field::new("a", DataType::Float64, true),
4865            Field::new("b", DataType::Decimal128(10, 2), true),
4866        ]));
4867
4868        let value: i128 = 123;
4869        let decimal_array = Arc::new(create_decimal_array(
4870            &[
4871                Some(value), // 1.23
4872                None,
4873                Some(value - 1), // 1.22
4874                Some(value + 1), // 1.24
4875            ],
4876            10,
4877            2,
4878        )) as ArrayRef;
4879        let float64_array = Arc::new(Float64Array::from(vec![
4880            Some(1.23),
4881            Some(1.22),
4882            Some(1.23),
4883            Some(1.24),
4884        ])) as ArrayRef;
4885        // lt: float64array < decimal array
4886        apply_logic_op(
4887            &schema,
4888            &float64_array,
4889            &decimal_array,
4890            Operator::Lt,
4891            BooleanArray::from(vec![Some(false), None, Some(false), Some(false)]),
4892        )
4893        .unwrap();
4894        // lt_eq: float64array <= decimal array
4895        apply_logic_op(
4896            &schema,
4897            &float64_array,
4898            &decimal_array,
4899            Operator::LtEq,
4900            BooleanArray::from(vec![Some(true), None, Some(false), Some(true)]),
4901        )
4902        .unwrap();
4903        // gt: float64array > decimal array
4904        apply_logic_op(
4905            &schema,
4906            &float64_array,
4907            &decimal_array,
4908            Operator::Gt,
4909            BooleanArray::from(vec![Some(false), None, Some(true), Some(false)]),
4910        )
4911        .unwrap();
4912        apply_logic_op(
4913            &schema,
4914            &float64_array,
4915            &decimal_array,
4916            Operator::GtEq,
4917            BooleanArray::from(vec![Some(true), None, Some(true), Some(true)]),
4918        )
4919        .unwrap();
4920        // is distinct: float64array is distinct decimal array
4921        // TODO: now we do not refactor the `is distinct or is not distinct` rule of coercion.
4922        // traced by https://github.com/apache/datafusion/issues/1590
4923        // the decimal array will be casted to float64array
4924        apply_logic_op(
4925            &schema,
4926            &float64_array,
4927            &decimal_array,
4928            Operator::IsDistinctFrom,
4929            BooleanArray::from(vec![Some(false), Some(true), Some(true), Some(false)]),
4930        )
4931        .unwrap();
4932        // is not distinct
4933        apply_logic_op(
4934            &schema,
4935            &float64_array,
4936            &decimal_array,
4937            Operator::IsNotDistinctFrom,
4938            BooleanArray::from(vec![Some(true), Some(false), Some(false), Some(true)]),
4939        )
4940        .unwrap();
4941
4942        Ok(())
4943    }
4944
4945    fn apply_decimal_arithmetic_op(
4946        schema: &SchemaRef,
4947        left: &ArrayRef,
4948        right: &ArrayRef,
4949        op: Operator,
4950        expected: ArrayRef,
4951    ) -> Result<()> {
4952        let arithmetic_op = binary_op(col("a", schema)?, op, col("b", schema)?, schema)?;
4953        let data: Vec<ArrayRef> = vec![Arc::clone(left), Arc::clone(right)];
4954        let batch = RecordBatch::try_new(Arc::clone(schema), data)?;
4955        let result = arithmetic_op
4956            .evaluate(&batch)?
4957            .into_array(batch.num_rows())
4958            .expect("Failed to convert to array");
4959
4960        assert_eq!(result.as_ref(), expected.as_ref());
4961        Ok(())
4962    }
4963
4964    #[test]
4965    fn arithmetic_decimal_expr_test() -> Result<()> {
4966        let schema = Arc::new(Schema::new(vec![
4967            Field::new("a", DataType::Int32, true),
4968            Field::new("b", DataType::Decimal128(10, 2), true),
4969        ]));
4970        let value: i128 = 123;
4971        let decimal_array = Arc::new(create_decimal_array(
4972            &[
4973                Some(value), // 1.23
4974                None,
4975                Some(value - 1), // 1.22
4976                Some(value + 1), // 1.24
4977            ],
4978            10,
4979            2,
4980        )) as ArrayRef;
4981        let int32_array = Arc::new(Int32Array::from(vec![
4982            Some(123),
4983            Some(122),
4984            Some(123),
4985            Some(124),
4986        ])) as ArrayRef;
4987
4988        // add: Int32array add decimal array
4989        let expect = Arc::new(create_decimal_array(
4990            &[Some(12423), None, Some(12422), Some(12524)],
4991            13,
4992            2,
4993        )) as ArrayRef;
4994        apply_decimal_arithmetic_op(
4995            &schema,
4996            &int32_array,
4997            &decimal_array,
4998            Operator::Plus,
4999            expect,
5000        )
5001        .unwrap();
5002
5003        // subtract: decimal array subtract int32 array
5004        let schema = Arc::new(Schema::new(vec![
5005            Field::new("a", DataType::Decimal128(10, 2), true),
5006            Field::new("b", DataType::Int32, true),
5007        ]));
5008        let expect = Arc::new(create_decimal_array(
5009            &[Some(-12177), None, Some(-12178), Some(-12276)],
5010            13,
5011            2,
5012        )) as ArrayRef;
5013        apply_decimal_arithmetic_op(
5014            &schema,
5015            &decimal_array,
5016            &int32_array,
5017            Operator::Minus,
5018            expect,
5019        )
5020        .unwrap();
5021
5022        // multiply: decimal array multiply int32 array
5023        let expect = Arc::new(create_decimal_array(
5024            &[Some(15129), None, Some(15006), Some(15376)],
5025            21,
5026            2,
5027        )) as ArrayRef;
5028        apply_decimal_arithmetic_op(
5029            &schema,
5030            &decimal_array,
5031            &int32_array,
5032            Operator::Multiply,
5033            expect,
5034        )
5035        .unwrap();
5036
5037        // divide: int32 array divide decimal array
5038        let schema = Arc::new(Schema::new(vec![
5039            Field::new("a", DataType::Int32, true),
5040            Field::new("b", DataType::Decimal128(10, 2), true),
5041        ]));
5042        let expect = Arc::new(create_decimal_array(
5043            &[Some(1000000), None, Some(1008196), Some(1000000)],
5044            16,
5045            4,
5046        )) as ArrayRef;
5047        apply_decimal_arithmetic_op(
5048            &schema,
5049            &int32_array,
5050            &decimal_array,
5051            Operator::Divide,
5052            expect,
5053        )
5054        .unwrap();
5055
5056        // modulus: int32 array modulus decimal array
5057        let schema = Arc::new(Schema::new(vec![
5058            Field::new("a", DataType::Int32, true),
5059            Field::new("b", DataType::Decimal128(10, 2), true),
5060        ]));
5061        let expect = Arc::new(create_decimal_array(
5062            &[Some(000), None, Some(100), Some(000)],
5063            10,
5064            2,
5065        )) as ArrayRef;
5066        apply_decimal_arithmetic_op(
5067            &schema,
5068            &int32_array,
5069            &decimal_array,
5070            Operator::Modulo,
5071            expect,
5072        )
5073        .unwrap();
5074
5075        Ok(())
5076    }
5077
5078    #[test]
5079    fn arithmetic_decimal_float_expr_test() -> Result<()> {
5080        let schema = Arc::new(Schema::new(vec![
5081            Field::new("a", DataType::Float64, true),
5082            Field::new("b", DataType::Decimal128(10, 2), true),
5083        ]));
5084        let value: i128 = 123;
5085        let decimal_array = Arc::new(create_decimal_array(
5086            &[
5087                Some(value), // 1.23
5088                None,
5089                Some(value - 1), // 1.22
5090                Some(value + 1), // 1.24
5091            ],
5092            10,
5093            2,
5094        )) as ArrayRef;
5095        let float64_array = Arc::new(Float64Array::from(vec![
5096            Some(123.0),
5097            Some(122.0),
5098            Some(123.0),
5099            Some(124.0),
5100        ])) as ArrayRef;
5101
5102        // add: float64 array add decimal array
5103        let expect = Arc::new(Float64Array::from(vec![
5104            Some(124.23),
5105            None,
5106            Some(124.22),
5107            Some(125.24),
5108        ])) as ArrayRef;
5109        apply_decimal_arithmetic_op(
5110            &schema,
5111            &float64_array,
5112            &decimal_array,
5113            Operator::Plus,
5114            expect,
5115        )
5116        .unwrap();
5117
5118        // subtract: decimal array subtract float64 array
5119        let schema = Arc::new(Schema::new(vec![
5120            Field::new("a", DataType::Float64, true),
5121            Field::new("b", DataType::Decimal128(10, 2), true),
5122        ]));
5123        let expect = Arc::new(Float64Array::from(vec![
5124            Some(121.77),
5125            None,
5126            Some(121.78),
5127            Some(122.76),
5128        ])) as ArrayRef;
5129        apply_decimal_arithmetic_op(
5130            &schema,
5131            &float64_array,
5132            &decimal_array,
5133            Operator::Minus,
5134            expect,
5135        )
5136        .unwrap();
5137
5138        // multiply: decimal array multiply float64 array
5139        let expect = Arc::new(Float64Array::from(vec![
5140            Some(151.29),
5141            None,
5142            Some(150.06),
5143            Some(153.76),
5144        ])) as ArrayRef;
5145        apply_decimal_arithmetic_op(
5146            &schema,
5147            &float64_array,
5148            &decimal_array,
5149            Operator::Multiply,
5150            expect,
5151        )
5152        .unwrap();
5153
5154        // divide: float64 array divide decimal array
5155        let schema = Arc::new(Schema::new(vec![
5156            Field::new("a", DataType::Float64, true),
5157            Field::new("b", DataType::Decimal128(10, 2), true),
5158        ]));
5159        let expect = Arc::new(Float64Array::from(vec![
5160            Some(100.0),
5161            None,
5162            Some(100.81967213114754),
5163            Some(100.0),
5164        ])) as ArrayRef;
5165        apply_decimal_arithmetic_op(
5166            &schema,
5167            &float64_array,
5168            &decimal_array,
5169            Operator::Divide,
5170            expect,
5171        )
5172        .unwrap();
5173
5174        // modulus: float64 array modulus decimal array
5175        let schema = Arc::new(Schema::new(vec![
5176            Field::new("a", DataType::Float64, true),
5177            Field::new("b", DataType::Decimal128(10, 2), true),
5178        ]));
5179        let expect = Arc::new(Float64Array::from(vec![
5180            Some(1.7763568394002505e-15),
5181            None,
5182            Some(1.0000000000000027),
5183            Some(8.881784197001252e-16),
5184        ])) as ArrayRef;
5185        apply_decimal_arithmetic_op(
5186            &schema,
5187            &float64_array,
5188            &decimal_array,
5189            Operator::Modulo,
5190            expect,
5191        )
5192        .unwrap();
5193
5194        Ok(())
5195    }
5196
5197    #[test]
5198    fn arithmetic_divide_zero() -> Result<()> {
5199        // other data type
5200        let schema = Arc::new(Schema::new(vec![
5201            Field::new("a", DataType::Int32, true),
5202            Field::new("b", DataType::Int32, true),
5203        ]));
5204        let a = Arc::new(Int32Array::from(vec![100]));
5205        let b = Arc::new(Int32Array::from(vec![0]));
5206
5207        let err = apply_arithmetic::<Int32Type>(
5208            schema,
5209            vec![a, b],
5210            Operator::Divide,
5211            Int32Array::from(vec![Some(4), Some(8), Some(16), Some(32), Some(64)]),
5212        )
5213        .unwrap_err();
5214
5215        let _expected = plan_datafusion_err!("Divide by zero");
5216
5217        assert!(matches!(err, ref _expected), "{err}");
5218
5219        // decimal
5220        let schema = Arc::new(Schema::new(vec![
5221            Field::new("a", DataType::Decimal128(25, 3), true),
5222            Field::new("b", DataType::Decimal128(25, 3), true),
5223        ]));
5224        let left_decimal_array = Arc::new(create_decimal_array(&[Some(1234567)], 25, 3));
5225        let right_decimal_array = Arc::new(create_decimal_array(&[Some(0)], 25, 3));
5226
5227        let err = apply_arithmetic::<Decimal128Type>(
5228            schema,
5229            vec![left_decimal_array, right_decimal_array],
5230            Operator::Divide,
5231            create_decimal_array(
5232                &[Some(12345670000000000000000000000000000), None],
5233                38,
5234                29,
5235            ),
5236        )
5237        .unwrap_err();
5238
5239        assert!(matches!(err, ref _expected), "{err}");
5240
5241        Ok(())
5242    }
5243
5244    #[test]
5245    fn bitwise_array_test() -> Result<()> {
5246        let left = Arc::new(Int32Array::from(vec![Some(12), None, Some(11)])) as ArrayRef;
5247        let right =
5248            Arc::new(Int32Array::from(vec![Some(1), Some(3), Some(7)])) as ArrayRef;
5249        let mut result = bitwise_and_dyn(Arc::clone(&left), Arc::clone(&right))?;
5250        let expected = Int32Array::from(vec![Some(0), None, Some(3)]);
5251        assert_eq!(result.as_ref(), &expected);
5252
5253        result = bitwise_or_dyn(Arc::clone(&left), Arc::clone(&right))?;
5254        let expected = Int32Array::from(vec![Some(13), None, Some(15)]);
5255        assert_eq!(result.as_ref(), &expected);
5256
5257        result = bitwise_xor_dyn(Arc::clone(&left), Arc::clone(&right))?;
5258        let expected = Int32Array::from(vec![Some(13), None, Some(12)]);
5259        assert_eq!(result.as_ref(), &expected);
5260
5261        let left =
5262            Arc::new(UInt32Array::from(vec![Some(12), None, Some(11)])) as ArrayRef;
5263        let right =
5264            Arc::new(UInt32Array::from(vec![Some(1), Some(3), Some(7)])) as ArrayRef;
5265        let mut result = bitwise_and_dyn(Arc::clone(&left), Arc::clone(&right))?;
5266        let expected = UInt32Array::from(vec![Some(0), None, Some(3)]);
5267        assert_eq!(result.as_ref(), &expected);
5268
5269        result = bitwise_or_dyn(Arc::clone(&left), Arc::clone(&right))?;
5270        let expected = UInt32Array::from(vec![Some(13), None, Some(15)]);
5271        assert_eq!(result.as_ref(), &expected);
5272
5273        result = bitwise_xor_dyn(Arc::clone(&left), Arc::clone(&right))?;
5274        let expected = UInt32Array::from(vec![Some(13), None, Some(12)]);
5275        assert_eq!(result.as_ref(), &expected);
5276
5277        Ok(())
5278    }
5279
5280    #[test]
5281    fn bitwise_shift_array_test() -> Result<()> {
5282        let input = Arc::new(Int32Array::from(vec![Some(2), None, Some(10)])) as ArrayRef;
5283        let modules =
5284            Arc::new(Int32Array::from(vec![Some(2), Some(4), Some(8)])) as ArrayRef;
5285        let mut result =
5286            bitwise_shift_left_dyn(Arc::clone(&input), Arc::clone(&modules))?;
5287
5288        let expected = Int32Array::from(vec![Some(8), None, Some(2560)]);
5289        assert_eq!(result.as_ref(), &expected);
5290
5291        result = bitwise_shift_right_dyn(Arc::clone(&result), Arc::clone(&modules))?;
5292        assert_eq!(result.as_ref(), &input);
5293
5294        let input =
5295            Arc::new(UInt32Array::from(vec![Some(2), None, Some(10)])) as ArrayRef;
5296        let modules =
5297            Arc::new(UInt32Array::from(vec![Some(2), Some(4), Some(8)])) as ArrayRef;
5298        let mut result =
5299            bitwise_shift_left_dyn(Arc::clone(&input), Arc::clone(&modules))?;
5300
5301        let expected = UInt32Array::from(vec![Some(8), None, Some(2560)]);
5302        assert_eq!(result.as_ref(), &expected);
5303
5304        result = bitwise_shift_right_dyn(Arc::clone(&result), Arc::clone(&modules))?;
5305        assert_eq!(result.as_ref(), &input);
5306        Ok(())
5307    }
5308
5309    #[test]
5310    fn bitwise_shift_array_overflow_test() -> Result<()> {
5311        let input = Arc::new(Int32Array::from(vec![Some(2)])) as ArrayRef;
5312        let modules = Arc::new(Int32Array::from(vec![Some(100)])) as ArrayRef;
5313        let result = bitwise_shift_left_dyn(Arc::clone(&input), Arc::clone(&modules))?;
5314
5315        let expected = Int32Array::from(vec![Some(32)]);
5316        assert_eq!(result.as_ref(), &expected);
5317
5318        let input = Arc::new(UInt32Array::from(vec![Some(2)])) as ArrayRef;
5319        let modules = Arc::new(UInt32Array::from(vec![Some(100)])) as ArrayRef;
5320        let result = bitwise_shift_left_dyn(Arc::clone(&input), Arc::clone(&modules))?;
5321
5322        let expected = UInt32Array::from(vec![Some(32)]);
5323        assert_eq!(result.as_ref(), &expected);
5324        Ok(())
5325    }
5326
5327    #[test]
5328    fn bitwise_scalar_test() -> Result<()> {
5329        let left = Arc::new(Int32Array::from(vec![Some(12), None, Some(11)])) as ArrayRef;
5330        let right = ScalarValue::from(3i32);
5331        let mut result = bitwise_and_dyn_scalar(&left, right.clone()).unwrap()?;
5332        let expected = Int32Array::from(vec![Some(0), None, Some(3)]);
5333        assert_eq!(result.as_ref(), &expected);
5334
5335        result = bitwise_or_dyn_scalar(&left, right.clone()).unwrap()?;
5336        let expected = Int32Array::from(vec![Some(15), None, Some(11)]);
5337        assert_eq!(result.as_ref(), &expected);
5338
5339        result = bitwise_xor_dyn_scalar(&left, right).unwrap()?;
5340        let expected = Int32Array::from(vec![Some(15), None, Some(8)]);
5341        assert_eq!(result.as_ref(), &expected);
5342
5343        let left =
5344            Arc::new(UInt32Array::from(vec![Some(12), None, Some(11)])) as ArrayRef;
5345        let right = ScalarValue::from(3u32);
5346        let mut result = bitwise_and_dyn_scalar(&left, right.clone()).unwrap()?;
5347        let expected = UInt32Array::from(vec![Some(0), None, Some(3)]);
5348        assert_eq!(result.as_ref(), &expected);
5349
5350        result = bitwise_or_dyn_scalar(&left, right.clone()).unwrap()?;
5351        let expected = UInt32Array::from(vec![Some(15), None, Some(11)]);
5352        assert_eq!(result.as_ref(), &expected);
5353
5354        result = bitwise_xor_dyn_scalar(&left, right).unwrap()?;
5355        let expected = UInt32Array::from(vec![Some(15), None, Some(8)]);
5356        assert_eq!(result.as_ref(), &expected);
5357        Ok(())
5358    }
5359
5360    #[test]
5361    fn bitwise_shift_scalar_test() -> Result<()> {
5362        let input = Arc::new(Int32Array::from(vec![Some(2), None, Some(4)])) as ArrayRef;
5363        let module = ScalarValue::from(10i32);
5364        let mut result =
5365            bitwise_shift_left_dyn_scalar(&input, module.clone()).unwrap()?;
5366
5367        let expected = Int32Array::from(vec![Some(2048), None, Some(4096)]);
5368        assert_eq!(result.as_ref(), &expected);
5369
5370        result = bitwise_shift_right_dyn_scalar(&result, module).unwrap()?;
5371        assert_eq!(result.as_ref(), &input);
5372
5373        let input = Arc::new(UInt32Array::from(vec![Some(2), None, Some(4)])) as ArrayRef;
5374        let module = ScalarValue::from(10u32);
5375        let mut result =
5376            bitwise_shift_left_dyn_scalar(&input, module.clone()).unwrap()?;
5377
5378        let expected = UInt32Array::from(vec![Some(2048), None, Some(4096)]);
5379        assert_eq!(result.as_ref(), &expected);
5380
5381        result = bitwise_shift_right_dyn_scalar(&result, module).unwrap()?;
5382        assert_eq!(result.as_ref(), &input);
5383        Ok(())
5384    }
5385
5386    #[test]
5387    fn test_display_and_or_combo() {
5388        let expr = BinaryExpr::new(
5389            Arc::new(BinaryExpr::new(
5390                lit(ScalarValue::from(1)),
5391                Operator::And,
5392                lit(ScalarValue::from(2)),
5393            )),
5394            Operator::And,
5395            Arc::new(BinaryExpr::new(
5396                lit(ScalarValue::from(3)),
5397                Operator::And,
5398                lit(ScalarValue::from(4)),
5399            )),
5400        );
5401        assert_eq!(expr.to_string(), "1 AND 2 AND 3 AND 4");
5402
5403        let expr = BinaryExpr::new(
5404            Arc::new(BinaryExpr::new(
5405                lit(ScalarValue::from(1)),
5406                Operator::Or,
5407                lit(ScalarValue::from(2)),
5408            )),
5409            Operator::Or,
5410            Arc::new(BinaryExpr::new(
5411                lit(ScalarValue::from(3)),
5412                Operator::Or,
5413                lit(ScalarValue::from(4)),
5414            )),
5415        );
5416        assert_eq!(expr.to_string(), "1 OR 2 OR 3 OR 4");
5417
5418        let expr = BinaryExpr::new(
5419            Arc::new(BinaryExpr::new(
5420                lit(ScalarValue::from(1)),
5421                Operator::And,
5422                lit(ScalarValue::from(2)),
5423            )),
5424            Operator::Or,
5425            Arc::new(BinaryExpr::new(
5426                lit(ScalarValue::from(3)),
5427                Operator::And,
5428                lit(ScalarValue::from(4)),
5429            )),
5430        );
5431        assert_eq!(expr.to_string(), "1 AND 2 OR 3 AND 4");
5432
5433        let expr = BinaryExpr::new(
5434            Arc::new(BinaryExpr::new(
5435                lit(ScalarValue::from(1)),
5436                Operator::Or,
5437                lit(ScalarValue::from(2)),
5438            )),
5439            Operator::And,
5440            Arc::new(BinaryExpr::new(
5441                lit(ScalarValue::from(3)),
5442                Operator::Or,
5443                lit(ScalarValue::from(4)),
5444            )),
5445        );
5446        assert_eq!(expr.to_string(), "(1 OR 2) AND (3 OR 4)");
5447    }
5448
5449    #[test]
5450    fn test_to_result_type_array() {
5451        let values = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
5452        let keys = Int8Array::from(vec![Some(0), None, Some(2), Some(3)]);
5453        let dictionary =
5454            Arc::new(DictionaryArray::try_new(keys, values).unwrap()) as ArrayRef;
5455
5456        // Casting Dictionary to Int32
5457        let casted = to_result_type_array(
5458            &Operator::Plus,
5459            Arc::clone(&dictionary),
5460            &DataType::Int32,
5461        )
5462        .unwrap();
5463        assert_eq!(
5464            &casted,
5465            &(Arc::new(Int32Array::from(vec![Some(1), None, Some(3), Some(4)]))
5466                as ArrayRef)
5467        );
5468
5469        // Array has same datatype as result type, no casting
5470        let casted = to_result_type_array(
5471            &Operator::Plus,
5472            Arc::clone(&dictionary),
5473            dictionary.data_type(),
5474        )
5475        .unwrap();
5476        assert_eq!(&casted, &dictionary);
5477
5478        // Not numerical operator, no casting
5479        let casted = to_result_type_array(
5480            &Operator::Eq,
5481            Arc::clone(&dictionary),
5482            &DataType::Int32,
5483        )
5484        .unwrap();
5485        assert_eq!(&casted, &dictionary);
5486    }
5487
5488    #[test]
5489    fn test_add_with_overflow() -> Result<()> {
5490        // create test data
5491        let l = Arc::new(Int32Array::from(vec![1, i32::MAX]));
5492        let r = Arc::new(Int32Array::from(vec![2, 1]));
5493        let schema = Arc::new(Schema::new(vec![
5494            Field::new("l", DataType::Int32, false),
5495            Field::new("r", DataType::Int32, false),
5496        ]));
5497        let batch = RecordBatch::try_new(schema, vec![l, r])?;
5498
5499        // create expression
5500        let expr = BinaryExpr::new(
5501            Arc::new(Column::new("l", 0)),
5502            Operator::Plus,
5503            Arc::new(Column::new("r", 1)),
5504        )
5505        .with_fail_on_overflow(true);
5506
5507        // evaluate expression
5508        let result = expr.evaluate(&batch);
5509        assert!(
5510            result
5511                .err()
5512                .unwrap()
5513                .to_string()
5514                .contains("Overflow happened on: 2147483647 + 1")
5515        );
5516        Ok(())
5517    }
5518
5519    #[test]
5520    fn test_subtract_with_overflow() -> Result<()> {
5521        // create test data
5522        let l = Arc::new(Int32Array::from(vec![1, i32::MIN]));
5523        let r = Arc::new(Int32Array::from(vec![2, 1]));
5524        let schema = Arc::new(Schema::new(vec![
5525            Field::new("l", DataType::Int32, false),
5526            Field::new("r", DataType::Int32, false),
5527        ]));
5528        let batch = RecordBatch::try_new(schema, vec![l, r])?;
5529
5530        // create expression
5531        let expr = BinaryExpr::new(
5532            Arc::new(Column::new("l", 0)),
5533            Operator::Minus,
5534            Arc::new(Column::new("r", 1)),
5535        )
5536        .with_fail_on_overflow(true);
5537
5538        // evaluate expression
5539        let result = expr.evaluate(&batch);
5540        assert!(
5541            result
5542                .err()
5543                .unwrap()
5544                .to_string()
5545                .contains("Overflow happened on: -2147483648 - 1")
5546        );
5547        Ok(())
5548    }
5549
5550    #[test]
5551    fn test_mul_with_overflow() -> Result<()> {
5552        // create test data
5553        let l = Arc::new(Int32Array::from(vec![1, i32::MAX]));
5554        let r = Arc::new(Int32Array::from(vec![2, 2]));
5555        let schema = Arc::new(Schema::new(vec![
5556            Field::new("l", DataType::Int32, false),
5557            Field::new("r", DataType::Int32, false),
5558        ]));
5559        let batch = RecordBatch::try_new(schema, vec![l, r])?;
5560
5561        // create expression
5562        let expr = BinaryExpr::new(
5563            Arc::new(Column::new("l", 0)),
5564            Operator::Multiply,
5565            Arc::new(Column::new("r", 1)),
5566        )
5567        .with_fail_on_overflow(true);
5568
5569        // evaluate expression
5570        let result = expr.evaluate(&batch);
5571        assert!(
5572            result
5573                .err()
5574                .unwrap()
5575                .to_string()
5576                .contains("Overflow happened on: 2147483647 * 2")
5577        );
5578        Ok(())
5579    }
5580
5581    fn apply_similar_to(
5582        schema: &SchemaRef,
5583        va: Vec<&str>,
5584        pattern: &str,
5585        negated: bool,
5586        case_insensitive: bool,
5587        expected: &BooleanArray,
5588    ) -> Result<()> {
5589        let a = StringArray::from(va);
5590        let op = similar_to(negated, case_insensitive, col("a", schema)?, lit(pattern))?;
5591        let batch = RecordBatch::try_new(Arc::clone(schema), vec![Arc::new(a)])?;
5592        let result = op
5593            .evaluate(&batch)?
5594            .into_array(batch.num_rows())
5595            .expect("Failed to convert to array");
5596        assert_eq!(result.as_ref(), expected);
5597
5598        Ok(())
5599    }
5600
5601    #[test]
5602    fn test_similar_to() {
5603        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, false)]));
5604
5605        // `%` matches any sequence; case-sensitive
5606        let expected = [Some(true), Some(false)].iter().collect();
5607        apply_similar_to(
5608            &schema,
5609            vec!["hello world", "Hello World"],
5610            "hello%",
5611            false,
5612            false,
5613            &expected,
5614        )
5615        .unwrap();
5616
5617        // `%` matches any sequence; case-insensitive
5618        let expected = [Some(true), Some(false)].iter().collect();
5619        apply_similar_to(
5620            &schema,
5621            vec!["hello world", "bye"],
5622            "hello%",
5623            false,
5624            true,
5625            &expected,
5626        )
5627        .unwrap();
5628
5629        // `_` matches exactly one character
5630        let expected = [Some(true), Some(false), Some(false)].iter().collect();
5631        apply_similar_to(&schema, vec!["x", "xy", ""], "_", false, false, &expected)
5632            .unwrap();
5633
5634        // Match must cover the entire string (no implicit substring match)
5635        let expected = [Some(false), Some(true)].iter().collect();
5636        apply_similar_to(&schema, vec!["abc", "a"], "a", false, false, &expected)
5637            .unwrap();
5638
5639        // `%` matches zero or more, so the empty string matches.
5640        let expected = [Some(true), Some(true)].iter().collect();
5641        apply_similar_to(&schema, vec!["", "anything"], "%", false, false, &expected)
5642            .unwrap();
5643
5644        // `_` requires exactly one character, so the empty string does not
5645        // match.
5646        let expected = [Some(false), Some(true)].iter().collect();
5647        apply_similar_to(&schema, vec!["", "x"], "_", false, false, &expected).unwrap();
5648
5649        // `%` at the start of the pattern is still anchored: the string
5650        // must end where the trailing literal begins.
5651        let expected = [Some(true), Some(false)].iter().collect();
5652        apply_similar_to(&schema, vec!["abc", "abd"], "%c", false, false, &expected)
5653            .unwrap();
5654
5655        // `%` and `_` together: `%` matches zero or more (including the
5656        // empty string), `_` matches exactly one character.
5657        let expected = [Some(true), Some(true)].iter().collect();
5658        apply_similar_to(&schema, vec!["a", "abc"], "a%", false, false, &expected)
5659            .unwrap();
5660        let expected = [Some(true), Some(false)].iter().collect();
5661        apply_similar_to(&schema, vec!["axb", "abc"], "a_b", false, false, &expected)
5662            .unwrap();
5663    }
5664
5665    // Regression: regex metacharacters that are NOT SIMILAR TO metacharacters
5666    // (`. ^ $ \`) must be treated as SQL literals. Without escaping, `a.`
5667    // would match any `a` followed by any character (`ab`, `a1`, ...).
5668    #[test]
5669    fn test_similar_to_sql_literal_metachars() {
5670        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, false)]));
5671
5672        // `.` is a literal, not the regex "any character" operator.
5673        let expected = [Some(true), Some(false), Some(false)].iter().collect();
5674        apply_similar_to(
5675            &schema,
5676            vec!["a.", "ab", "a"],
5677            "a.",
5678            false,
5679            false,
5680            &expected,
5681        )
5682        .unwrap();
5683
5684        // `^` and `$` are literals and only match the literal `^` and `$`.
5685        let expected = [Some(true), Some(false)].iter().collect();
5686        apply_similar_to(&schema, vec!["^x$", "x"], r"^x$", false, false, &expected)
5687            .unwrap();
5688
5689        // `\` is a literal backslash (we don't support the ESCAPE clause).
5690        let expected = [Some(true), Some(false)].iter().collect();
5691        apply_similar_to(&schema, vec![r"a\b", "ab"], r"a\b", false, false, &expected)
5692            .unwrap();
5693    }
5694
5695    // SIMILAR TO borrows POSIX metacharacters from regular expressions:
5696    // `| * + ? ( ) { } [ ]`. The translator passes them through to the
5697    // underlying regex engine.
5698    #[test]
5699    fn test_similar_to_posix_metachars() {
5700        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, false)]));
5701
5702        // `|` alternation.
5703        let expected = [Some(true), Some(false), Some(true)].iter().collect();
5704        apply_similar_to(&schema, vec!["a", "c", "b"], "a|b", false, false, &expected)
5705            .unwrap();
5706
5707        // `*` zero or more.
5708        let expected = [Some(true), Some(true), Some(false)].iter().collect();
5709        apply_similar_to(&schema, vec!["", "aa", "ab"], "a*", false, false, &expected)
5710            .unwrap();
5711
5712        // `+` one or more.
5713        let expected = [Some(false), Some(true)].iter().collect();
5714        apply_similar_to(&schema, vec!["", "aa"], "a+", false, false, &expected).unwrap();
5715
5716        // `?` zero or one.
5717        let expected = [Some(true), Some(true), Some(false)].iter().collect();
5718        apply_similar_to(&schema, vec!["", "a", "aa"], "a?", false, false, &expected)
5719            .unwrap();
5720
5721        // `()` grouping.
5722        let expected = [Some(true), Some(true), Some(false)].iter().collect();
5723        apply_similar_to(
5724            &schema,
5725            vec!["ab", "abc", "ac"],
5726            "(ab)c?",
5727            false,
5728            false,
5729            &expected,
5730        )
5731        .unwrap();
5732
5733        // `{m}` exact count.
5734        let expected = [Some(true), Some(false)].iter().collect();
5735        apply_similar_to(&schema, vec!["aaa", "aa"], "a{3}", false, false, &expected)
5736            .unwrap();
5737
5738        // `[...]` character class.
5739        let expected = [Some(true), Some(false)].iter().collect();
5740        apply_similar_to(&schema, vec!["a", "c"], "[ab]", false, false, &expected)
5741            .unwrap();
5742
5743        // `[^...]` negated character class.
5744        let expected = [Some(true), Some(false)].iter().collect();
5745        apply_similar_to(&schema, vec!["c", "a"], "[^ab]", false, false, &expected)
5746            .unwrap();
5747
5748        // `[a-z]` range inside a character class.
5749        let expected = [Some(true), Some(false)].iter().collect();
5750        apply_similar_to(&schema, vec!["m", "1"], "[a-z]", false, false, &expected)
5751            .unwrap();
5752    }
5753
5754    // Regression: `%` and `_` must match newlines, matching SQL semantics
5755    // where these wildcards match "any character".
5756    #[test]
5757    fn test_similar_to_wildcards_match_newlines() {
5758        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, false)]));
5759
5760        // `%` crosses a newline. (`%` also matches zero characters, so `ab`
5761        // matches `a%b` as well.)
5762        let expected = [Some(true), Some(true)].iter().collect();
5763        apply_similar_to(&schema, vec!["a\nb", "ab"], "a%b", false, false, &expected)
5764            .unwrap();
5765
5766        // `_` matches a single newline. (`_` requires exactly one character,
5767        // so `ab` does not match `a_b`.)
5768        let expected = [Some(true), Some(false)].iter().collect();
5769        apply_similar_to(&schema, vec!["a\nb", "ab"], "a_b", false, false, &expected)
5770            .unwrap();
5771    }
5772
5773    #[test]
5774    fn test_similar_to_non_literal_pattern_errors() {
5775        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, false)]));
5776        // Non-string literal patterns still error.
5777        let err = similar_to(false, false, col("a", &schema).unwrap(), lit(1i32))
5778            .expect_err("non-string literal pattern should error");
5779        assert!(
5780            err.to_string()
5781                .contains("SIMILAR TO pattern must be a string type, got Int32(1)"),
5782            "unexpected error message: {err}"
5783        );
5784    }
5785
5786    #[test]
5787    fn test_similar_to_dynamic_pattern() {
5788        let schema = Arc::new(Schema::new(vec![
5789            Field::new("text", DataType::Utf8, false),
5790            Field::new("pattern", DataType::Utf8, false),
5791        ]));
5792        let text = StringArray::from(vec!["abc", "ab", "x"]);
5793        let pattern = StringArray::from(vec!["a%", "a.", "_"]);
5794        let batch = RecordBatch::try_new(
5795            Arc::clone(&schema),
5796            vec![Arc::new(text), Arc::new(pattern)],
5797        )
5798        .unwrap();
5799
5800        let op = similar_to(
5801            false,
5802            false,
5803            col("text", &schema).unwrap(),
5804            col("pattern", &schema).unwrap(),
5805        )
5806        .unwrap();
5807        let result = op.evaluate(&batch).unwrap();
5808        let result_array = result.into_array(batch.num_rows()).unwrap();
5809        let result = as_boolean_array(&result_array).unwrap();
5810        assert!(result.value(0)); // "abc" ~ ^(?:a(?s:.*))$
5811        assert!(!result.value(1)); // "ab"  ~ ^(?:a\.)$
5812        assert!(result.value(2)); // "x"   ~ ^(?:(?s:.))$
5813    }
5814
5815    #[test]
5816    fn test_similar_to_null_pattern() {
5817        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, false)]));
5818        let a = StringArray::from(vec!["hello"]);
5819        let op = similar_to(
5820            false,
5821            false,
5822            col("a", &schema).unwrap(),
5823            lit(ScalarValue::Utf8(None)),
5824        )
5825        .unwrap();
5826        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(a)]).unwrap();
5827        let result = op
5828            .evaluate(&batch)
5829            .unwrap()
5830            .into_array(batch.num_rows())
5831            .unwrap();
5832        let expected: BooleanArray = std::iter::once(&None).collect();
5833        assert_eq!(result.as_ref(), &expected);
5834    }
5835
5836    pub fn binary_expr(
5837        left: Arc<dyn PhysicalExpr>,
5838        op: Operator,
5839        right: Arc<dyn PhysicalExpr>,
5840        schema: &Schema,
5841    ) -> Result<BinaryExpr> {
5842        Ok(binary_op(left, op, right, schema)?
5843            .downcast_ref::<BinaryExpr>()
5844            .unwrap()
5845            .clone())
5846    }
5847
5848    /// Test for Uniform-Uniform, Unknown-Uniform, Uniform-Unknown and Unknown-Unknown evaluation.
5849    #[test]
5850    #[expect(deprecated)]
5851    fn test_evaluate_statistics_combination_of_range_holders() -> Result<()> {
5852        let schema = &Schema::new(vec![Field::new("a", DataType::Float64, false)]);
5853        let a = Arc::new(Column::new("a", 0)) as _;
5854        let b = lit(ScalarValue::from(12.0));
5855
5856        let left_interval = Interval::make(Some(0.0), Some(12.0))?;
5857        let right_interval = Interval::make(Some(12.0), Some(36.0))?;
5858        let (left_mean, right_mean) = (ScalarValue::from(6.0), ScalarValue::from(24.0));
5859        let (left_med, right_med) = (ScalarValue::from(6.0), ScalarValue::from(24.0));
5860
5861        for children in [
5862            vec![
5863                &Distribution::new_uniform(left_interval.clone())?,
5864                &Distribution::new_uniform(right_interval.clone())?,
5865            ],
5866            vec![
5867                &Distribution::new_generic(
5868                    left_mean.clone(),
5869                    left_med.clone(),
5870                    ScalarValue::Float64(None),
5871                    left_interval.clone(),
5872                )?,
5873                &Distribution::new_uniform(right_interval.clone())?,
5874            ],
5875            vec![
5876                &Distribution::new_uniform(right_interval.clone())?,
5877                &Distribution::new_generic(
5878                    right_mean.clone(),
5879                    right_med.clone(),
5880                    ScalarValue::Float64(None),
5881                    right_interval.clone(),
5882                )?,
5883            ],
5884            vec![
5885                &Distribution::new_generic(
5886                    left_mean.clone(),
5887                    left_med.clone(),
5888                    ScalarValue::Float64(None),
5889                    left_interval.clone(),
5890                )?,
5891                &Distribution::new_generic(
5892                    right_mean.clone(),
5893                    right_med.clone(),
5894                    ScalarValue::Float64(None),
5895                    right_interval.clone(),
5896                )?,
5897            ],
5898        ] {
5899            let ops = vec![
5900                Operator::Plus,
5901                Operator::Minus,
5902                Operator::Multiply,
5903                Operator::Divide,
5904            ];
5905
5906            for op in ops {
5907                let expr = binary_expr(Arc::clone(&a), op, Arc::clone(&b), schema)?;
5908                assert_eq!(
5909                    expr.evaluate_statistics(&children)?,
5910                    new_generic_from_binary_op(&op, children[0], children[1])?
5911                );
5912            }
5913        }
5914        Ok(())
5915    }
5916
5917    #[test]
5918    #[expect(deprecated)]
5919    fn test_evaluate_statistics_bernoulli() -> Result<()> {
5920        let schema = &Schema::new(vec![
5921            Field::new("a", DataType::Int64, false),
5922            Field::new("b", DataType::Int64, false),
5923        ]);
5924        let a = Arc::new(Column::new("a", 0)) as _;
5925        let b = Arc::new(Column::new("b", 1)) as _;
5926        let eq = Arc::new(binary_expr(
5927            Arc::clone(&a),
5928            Operator::Eq,
5929            Arc::clone(&b),
5930            schema,
5931        )?);
5932        let neq = Arc::new(binary_expr(a, Operator::NotEq, b, schema)?);
5933
5934        let left_stat = &Distribution::new_uniform(Interval::make(Some(0), Some(7))?)?;
5935        let right_stat = &Distribution::new_uniform(Interval::make(Some(4), Some(11))?)?;
5936
5937        // Intervals: [0, 7], [4, 11].
5938        // The intersection is [4, 7], so the probability of equality is 4 / 64 = 1 / 16.
5939        assert_eq!(
5940            eq.evaluate_statistics(&[left_stat, right_stat])?,
5941            Distribution::new_bernoulli(ScalarValue::from(1.0 / 16.0))?
5942        );
5943
5944        // The probability of being distinct is 1 - 1 / 16 = 15 / 16.
5945        assert_eq!(
5946            neq.evaluate_statistics(&[left_stat, right_stat])?,
5947            Distribution::new_bernoulli(ScalarValue::from(15.0 / 16.0))?
5948        );
5949
5950        Ok(())
5951    }
5952
5953    #[test]
5954    #[expect(deprecated)]
5955    fn test_propagate_statistics_combination_of_range_holders_arithmetic() -> Result<()> {
5956        let schema = &Schema::new(vec![Field::new("a", DataType::Float64, false)]);
5957        let a = Arc::new(Column::new("a", 0)) as _;
5958        let b = lit(ScalarValue::from(12.0));
5959
5960        let left_interval = Interval::make(Some(0.0), Some(12.0))?;
5961        let right_interval = Interval::make(Some(12.0), Some(36.0))?;
5962
5963        let parent = Distribution::new_uniform(Interval::make(Some(-432.), Some(432.))?)?;
5964        let children = vec![
5965            vec![
5966                Distribution::new_uniform(left_interval.clone())?,
5967                Distribution::new_uniform(right_interval.clone())?,
5968            ],
5969            vec![
5970                Distribution::new_generic(
5971                    ScalarValue::from(6.),
5972                    ScalarValue::from(6.),
5973                    ScalarValue::Float64(None),
5974                    left_interval.clone(),
5975                )?,
5976                Distribution::new_uniform(right_interval.clone())?,
5977            ],
5978            vec![
5979                Distribution::new_uniform(left_interval.clone())?,
5980                Distribution::new_generic(
5981                    ScalarValue::from(12.),
5982                    ScalarValue::from(12.),
5983                    ScalarValue::Float64(None),
5984                    right_interval.clone(),
5985                )?,
5986            ],
5987            vec![
5988                Distribution::new_generic(
5989                    ScalarValue::from(6.),
5990                    ScalarValue::from(6.),
5991                    ScalarValue::Float64(None),
5992                    left_interval.clone(),
5993                )?,
5994                Distribution::new_generic(
5995                    ScalarValue::from(12.),
5996                    ScalarValue::from(12.),
5997                    ScalarValue::Float64(None),
5998                    right_interval.clone(),
5999                )?,
6000            ],
6001        ];
6002
6003        let ops = vec![
6004            Operator::Plus,
6005            Operator::Minus,
6006            Operator::Multiply,
6007            Operator::Divide,
6008        ];
6009
6010        for child_view in children {
6011            let child_refs = child_view.iter().collect::<Vec<_>>();
6012            for op in &ops {
6013                let expr = binary_expr(Arc::clone(&a), *op, Arc::clone(&b), schema)?;
6014                assert_eq!(
6015                    expr.propagate_statistics(&parent, child_refs.as_slice())?,
6016                    Some(child_view.clone())
6017                );
6018            }
6019        }
6020        Ok(())
6021    }
6022
6023    #[test]
6024    #[expect(deprecated)]
6025    fn test_propagate_statistics_combination_of_range_holders_comparison() -> Result<()> {
6026        let schema = &Schema::new(vec![Field::new("a", DataType::Float64, false)]);
6027        let a = Arc::new(Column::new("a", 0)) as _;
6028        let b = lit(ScalarValue::from(12.0));
6029
6030        let left_interval = Interval::make(Some(0.0), Some(12.0))?;
6031        let right_interval = Interval::make(Some(6.0), Some(18.0))?;
6032
6033        let one = ScalarValue::from(1.0);
6034        let parent = Distribution::new_bernoulli(one)?;
6035        let children = vec![
6036            vec![
6037                Distribution::new_uniform(left_interval.clone())?,
6038                Distribution::new_uniform(right_interval.clone())?,
6039            ],
6040            vec![
6041                Distribution::new_generic(
6042                    ScalarValue::from(6.),
6043                    ScalarValue::from(6.),
6044                    ScalarValue::Float64(None),
6045                    left_interval.clone(),
6046                )?,
6047                Distribution::new_uniform(right_interval.clone())?,
6048            ],
6049            vec![
6050                Distribution::new_uniform(left_interval.clone())?,
6051                Distribution::new_generic(
6052                    ScalarValue::from(12.),
6053                    ScalarValue::from(12.),
6054                    ScalarValue::Float64(None),
6055                    right_interval.clone(),
6056                )?,
6057            ],
6058            vec![
6059                Distribution::new_generic(
6060                    ScalarValue::from(6.),
6061                    ScalarValue::from(6.),
6062                    ScalarValue::Float64(None),
6063                    left_interval.clone(),
6064                )?,
6065                Distribution::new_generic(
6066                    ScalarValue::from(12.),
6067                    ScalarValue::from(12.),
6068                    ScalarValue::Float64(None),
6069                    right_interval.clone(),
6070                )?,
6071            ],
6072        ];
6073
6074        let ops = vec![
6075            Operator::Eq,
6076            Operator::Gt,
6077            Operator::GtEq,
6078            Operator::Lt,
6079            Operator::LtEq,
6080        ];
6081
6082        for child_view in children {
6083            let child_refs = child_view.iter().collect::<Vec<_>>();
6084            for op in &ops {
6085                let expr = binary_expr(Arc::clone(&a), *op, Arc::clone(&b), schema)?;
6086                assert!(
6087                    expr.propagate_statistics(&parent, child_refs.as_slice())?
6088                        .is_some()
6089                );
6090            }
6091        }
6092
6093        Ok(())
6094    }
6095
6096    #[test]
6097    fn test_fmt_sql() -> Result<()> {
6098        let schema = Schema::new(vec![
6099            Field::new("a", DataType::Int32, false),
6100            Field::new("b", DataType::Int32, false),
6101        ]);
6102
6103        // Test basic binary expressions
6104        let simple_expr = binary_expr(
6105            col("a", &schema)?,
6106            Operator::Plus,
6107            col("b", &schema)?,
6108            &schema,
6109        )?;
6110        let display_string = simple_expr.to_string();
6111        assert_eq!(display_string, "a@0 + b@1");
6112        let sql_string = fmt_sql(&simple_expr).to_string();
6113        assert_eq!(sql_string, "a + b");
6114
6115        // Test nested expressions with different operator precedence
6116        let nested_expr = binary_expr(
6117            Arc::new(binary_expr(
6118                col("a", &schema)?,
6119                Operator::Plus,
6120                col("b", &schema)?,
6121                &schema,
6122            )?),
6123            Operator::Multiply,
6124            col("b", &schema)?,
6125            &schema,
6126        )?;
6127        let display_string = nested_expr.to_string();
6128        assert_eq!(display_string, "(a@0 + b@1) * b@1");
6129        let sql_string = fmt_sql(&nested_expr).to_string();
6130        assert_eq!(sql_string, "(a + b) * b");
6131
6132        // Test nested expressions with same operator precedence
6133        let nested_same_prec = binary_expr(
6134            Arc::new(binary_expr(
6135                col("a", &schema)?,
6136                Operator::Plus,
6137                col("b", &schema)?,
6138                &schema,
6139            )?),
6140            Operator::Plus,
6141            col("b", &schema)?,
6142            &schema,
6143        )?;
6144        let display_string = nested_same_prec.to_string();
6145        assert_eq!(display_string, "a@0 + b@1 + b@1");
6146        let sql_string = fmt_sql(&nested_same_prec).to_string();
6147        assert_eq!(sql_string, "a + b + b");
6148
6149        // Test with literals
6150        let lit_expr = binary_expr(
6151            col("a", &schema)?,
6152            Operator::Eq,
6153            lit(ScalarValue::Int32(Some(42))),
6154            &schema,
6155        )?;
6156        let display_string = lit_expr.to_string();
6157        assert_eq!(display_string, "a@0 = 42");
6158        let sql_string = fmt_sql(&lit_expr).to_string();
6159        assert_eq!(sql_string, "a = 42");
6160
6161        Ok(())
6162    }
6163
6164    #[test]
6165    fn test_check_short_circuit() {
6166        // Test with non-nullable arrays
6167        let schema = Arc::new(Schema::new(vec![
6168            Field::new("a", DataType::Int32, false),
6169            Field::new("b", DataType::Int32, false),
6170        ]));
6171        let a_array = Int32Array::from(vec![1, 3, 4, 5, 6]);
6172        let b_array = Int32Array::from(vec![1, 2, 3, 4, 5]);
6173        let batch = RecordBatch::try_new(
6174            Arc::clone(&schema),
6175            vec![Arc::new(a_array), Arc::new(b_array)],
6176        )
6177        .unwrap();
6178
6179        // `AND` uses `evaluate_conjunction` instead.
6180        let left_expr = logical2physical(&logical_col("a").eq(expr_lit(2)), &schema);
6181        let left_value = left_expr.evaluate(&batch).unwrap();
6182        assert!(matches!(
6183            check_short_circuit(&left_value, &Operator::And),
6184            ShortCircuitStrategy::None
6185        ));
6186
6187        // op: OR left: all true
6188        let left_expr = logical2physical(&logical_col("a").gt(expr_lit(0)), &schema);
6189        let left_value = left_expr.evaluate(&batch).unwrap();
6190        assert!(matches!(
6191            check_short_circuit(&left_value, &Operator::Or),
6192            ShortCircuitStrategy::ReturnLeft
6193        ));
6194
6195        // 20% false: OR can pre-select the false rows.
6196        let left_expr: Arc<dyn PhysicalExpr> =
6197            logical2physical(&logical_col("a").gt(expr_lit(2)), &schema);
6198        let left_value = left_expr.evaluate(&batch).unwrap();
6199        let ColumnarValue::Array(array) = &left_value else {
6200            panic!("Expected ColumnarValue::Array");
6201        };
6202        let ShortCircuitStrategy::PreSelection { mask, fill_value } =
6203            check_short_circuit(&left_value, &Operator::Or)
6204        else {
6205            panic!("Expected ShortCircuitStrategy::PreSelection");
6206        };
6207        // For OR, the mask selects the rows where the LHS is false (the negation
6208        // of the LHS) and the unselected rows are filled with `true`.
6209        assert!(fill_value);
6210        let negated_lhs: Vec<_> = as_boolean_array(array)
6211            .unwrap()
6212            .iter()
6213            .map(|v| v.map(|b| !b))
6214            .collect();
6215        let boolean_arr: Vec<_> = mask.iter().collect();
6216        assert_eq!(negated_lhs, boolean_arr);
6217
6218        // 60% false: OR falls back to normal evaluation.
6219        let left_expr: Arc<dyn PhysicalExpr> =
6220            logical2physical(&logical_col("a").gt(expr_lit(4)), &schema);
6221        let left_value = left_expr.evaluate(&batch).unwrap();
6222        assert!(matches!(
6223            check_short_circuit(&left_value, &Operator::Or),
6224            ShortCircuitStrategy::None
6225        ));
6226
6227        // Test with nullable arrays and null values
6228        let schema_nullable = Arc::new(Schema::new(vec![
6229            Field::new("c", DataType::Boolean, true),
6230            Field::new("d", DataType::Boolean, true),
6231        ]));
6232
6233        // Create arrays with null values
6234        let c_array = Arc::new(BooleanArray::from(vec![
6235            Some(true),
6236            Some(false),
6237            None,
6238            Some(true),
6239            None,
6240        ])) as ArrayRef;
6241        let d_array = Arc::new(BooleanArray::from(vec![
6242            Some(false),
6243            Some(true),
6244            Some(false),
6245            None,
6246            Some(true),
6247        ])) as ArrayRef;
6248
6249        let batch_nullable = RecordBatch::try_new(
6250            Arc::clone(&schema_nullable),
6251            vec![Arc::clone(&c_array), Arc::clone(&d_array)],
6252        )
6253        .unwrap();
6254
6255        // Case: Mixed values with nulls - shouldn't short-circuit for OR
6256        let mixed_nulls = logical2physical(&logical_col("c"), &schema_nullable);
6257        let mixed_nulls_value = mixed_nulls.evaluate(&batch_nullable).unwrap();
6258        assert!(matches!(
6259            check_short_circuit(&mixed_nulls_value, &Operator::Or),
6260            ShortCircuitStrategy::None
6261        ));
6262
6263        // Test with all nulls
6264        let all_nulls = Arc::new(BooleanArray::from(vec![None, None, None])) as ArrayRef;
6265        let null_batch = RecordBatch::try_new(
6266            Arc::new(Schema::new(vec![Field::new("e", DataType::Boolean, true)])),
6267            vec![all_nulls],
6268        )
6269        .unwrap();
6270
6271        let null_expr = logical2physical(&logical_col("e"), &null_batch.schema());
6272        let null_value = null_expr.evaluate(&null_batch).unwrap();
6273
6274        // All nulls shouldn't short-circuit for OR
6275        assert!(matches!(
6276            check_short_circuit(&null_value, &Operator::Or),
6277            ShortCircuitStrategy::None
6278        ));
6279
6280        // Test with scalar values
6281        // Scalar true
6282        let scalar_true = ColumnarValue::Scalar(ScalarValue::Boolean(Some(true)));
6283        assert!(matches!(
6284            check_short_circuit(&scalar_true, &Operator::Or),
6285            ShortCircuitStrategy::ReturnLeft
6286        )); // Should short-circuit OR
6287
6288        // Scalar false
6289        let scalar_false = ColumnarValue::Scalar(ScalarValue::Boolean(Some(false)));
6290        assert!(matches!(
6291            check_short_circuit(&scalar_false, &Operator::Or),
6292            ShortCircuitStrategy::ReturnRight
6293        )); // Should return the RHS for OR
6294
6295        // Scalar null
6296        let scalar_null = ColumnarValue::Scalar(ScalarValue::Boolean(None));
6297        assert!(matches!(
6298            check_short_circuit(&scalar_null, &Operator::Or),
6299            ShortCircuitStrategy::None
6300        ));
6301    }
6302
6303    /// Tests [`pre_selection_scatter`] with non-empty, null-free, mixed masks.
6304    #[test]
6305    fn test_pre_selection_scatter() {
6306        fn create_bool_array(bools: Vec<bool>) -> BooleanArray {
6307            BooleanArray::from(bools.into_iter().map(Some).collect::<Vec<_>>())
6308        }
6309        // Test sparse left with interleaved true/false
6310        {
6311            // Left: [T, F, T, F, T]
6312            // Right: [F, T, F] (values for 3 true positions)
6313            let left = create_bool_array(vec![true, false, true, false, true]);
6314            let right = create_bool_array(vec![false, true, false]);
6315
6316            let result = pre_selection_scatter(&left, Some(&right), false).unwrap();
6317            let result_arr = result.into_array(left.len()).unwrap();
6318
6319            let expected = create_bool_array(vec![false, false, true, false, false]);
6320            assert_eq!(&expected, result_arr.as_boolean());
6321        }
6322        // Test multiple consecutive true blocks
6323        {
6324            // Left: [F, T, T, F, T, T, T]
6325            // Right: [T, F, F, T, F]
6326            let left =
6327                create_bool_array(vec![false, true, true, false, true, true, true]);
6328            let right = create_bool_array(vec![true, false, false, true, false]);
6329
6330            let result = pre_selection_scatter(&left, Some(&right), false).unwrap();
6331            let result_arr = result.into_array(left.len()).unwrap();
6332
6333            let expected =
6334                create_bool_array(vec![false, true, false, false, false, true, false]);
6335            assert_eq!(&expected, result_arr.as_boolean());
6336        }
6337        // Test single true at first position
6338        {
6339            // Left: [T, F, F]
6340            // Right: [F]
6341            let left = create_bool_array(vec![true, false, false]);
6342            let right = create_bool_array(vec![false]);
6343
6344            let result = pre_selection_scatter(&left, Some(&right), false).unwrap();
6345            let result_arr = result.into_array(left.len()).unwrap();
6346
6347            let expected = create_bool_array(vec![false, false, false]);
6348            assert_eq!(&expected, result_arr.as_boolean());
6349        }
6350        // Test single true at last position
6351        {
6352            // Left: [F, F, T]
6353            // Right: [F]
6354            let left = create_bool_array(vec![false, false, true]);
6355            let right = create_bool_array(vec![false]);
6356
6357            let result = pre_selection_scatter(&left, Some(&right), false).unwrap();
6358            let result_arr = result.into_array(left.len()).unwrap();
6359
6360            let expected = create_bool_array(vec![false, false, false]);
6361            assert_eq!(&expected, result_arr.as_boolean());
6362        }
6363        // Test nulls in right array
6364        {
6365            // Left: [F, T, F, T]
6366            // Right: [None, Some(false)] (with null at first position)
6367            let left = create_bool_array(vec![false, true, false, true]);
6368            let right = BooleanArray::from(vec![None, Some(false)]);
6369
6370            let result = pre_selection_scatter(&left, Some(&right), false).unwrap();
6371            let result_arr = result.into_array(left.len()).unwrap();
6372
6373            let expected = BooleanArray::from(vec![
6374                Some(false),
6375                None, // null from right
6376                Some(false),
6377                Some(false),
6378            ]);
6379            assert_eq!(&expected, result_arr.as_boolean());
6380        }
6381        // OR semantics: selected rows take the RHS, unselected rows become true.
6382        {
6383            // Selection (LHS false rows): [T, F, T, F, T]
6384            // Right (RHS on those rows): [F, T, F]
6385            let left = create_bool_array(vec![true, false, true, false, true]);
6386            let right = create_bool_array(vec![false, true, false]);
6387
6388            let result = pre_selection_scatter(&left, Some(&right), true).unwrap();
6389            let result_arr = result.into_array(left.len()).unwrap();
6390
6391            // selected rows take the RHS value; unselected rows are `true`
6392            let expected = create_bool_array(vec![false, true, true, true, false]);
6393            assert_eq!(&expected, result_arr.as_boolean());
6394        }
6395        // OR semantics with nulls in the right array.
6396        {
6397            // Selection (LHS false rows): [F, T, F, T]
6398            // Right: [None, Some(false)]
6399            let left = create_bool_array(vec![false, true, false, true]);
6400            let right = BooleanArray::from(vec![None, Some(false)]);
6401
6402            let result = pre_selection_scatter(&left, Some(&right), true).unwrap();
6403            let result_arr = result.into_array(left.len()).unwrap();
6404
6405            let expected = BooleanArray::from(vec![
6406                Some(true), // unselected => true
6407                None,       // null from right
6408                Some(true), // unselected => true
6409                Some(false),
6410            ]);
6411            assert_eq!(&expected, result_arr.as_boolean());
6412        }
6413    }
6414
6415    #[test]
6416    fn test_and_true_preselection_returns_lhs() {
6417        let schema =
6418            Arc::new(Schema::new(vec![Field::new("c", DataType::Boolean, false)]));
6419        let c_array = Arc::new(BooleanArray::from(vec![false, true, false, false, false]))
6420            as ArrayRef;
6421        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::clone(&c_array)])
6422            .unwrap();
6423
6424        let expr = logical2physical(&logical_col("c").and(expr_lit(true)), &schema);
6425
6426        let result = expr.evaluate(&batch).unwrap();
6427        let ColumnarValue::Array(result_arr) = result else {
6428            panic!("Expected ColumnarValue::Array");
6429        };
6430
6431        let expected: Vec<_> = c_array.as_boolean().iter().collect();
6432        let actual: Vec<_> = result_arr.as_boolean().iter().collect();
6433        assert_eq!(
6434            expected, actual,
6435            "AND with TRUE must equal LHS even with PreSelection"
6436        );
6437    }
6438
6439    #[test]
6440    fn test_or_false_preselection_returns_lhs() {
6441        // `c OR false` over a mostly-true `c` triggers OR pre-selection; the
6442        // result must equal `c`.
6443        let schema =
6444            Arc::new(Schema::new(vec![Field::new("c", DataType::Boolean, false)]));
6445        let c_array =
6446            Arc::new(BooleanArray::from(vec![true, false, true, true, true])) as ArrayRef;
6447        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::clone(&c_array)])
6448            .unwrap();
6449
6450        let expr = logical2physical(&logical_col("c").or(expr_lit(false)), &schema);
6451
6452        let result = expr.evaluate(&batch).unwrap();
6453        let ColumnarValue::Array(result_arr) = result else {
6454            panic!("Expected ColumnarValue::Array");
6455        };
6456
6457        let expected: Vec<_> = c_array.as_boolean().iter().collect();
6458        let actual: Vec<_> = result_arr.as_boolean().iter().collect();
6459        assert_eq!(
6460            expected, actual,
6461            "OR with FALSE must equal LHS even with PreSelection"
6462        );
6463    }
6464
6465    #[test]
6466    fn test_or_preselection_matches_kleene() {
6467        // The OR pre-selection path must match full-batch Kleene OR.
6468        use arrow::compute::kernels::boolean::or_kleene;
6469
6470        let schema = Arc::new(Schema::new(vec![
6471            Field::new("c", DataType::Boolean, true),
6472            Field::new("d", DataType::Boolean, true),
6473        ]));
6474
6475        // `c` is mostly true (2/10 false => 20% <= threshold) so OR pre-selects.
6476        let c = BooleanArray::from(vec![
6477            true, true, false, true, true, true, true, false, true, true,
6478        ]);
6479
6480        let d_cases = vec![
6481            // Mixed RHS with nulls exercises scatter and null copy.
6482            BooleanArray::from(vec![
6483                Some(false),
6484                Some(true),
6485                Some(true),
6486                Some(false),
6487                Some(false),
6488                Some(true),
6489                Some(false),
6490                None,
6491                Some(true),
6492                None,
6493            ]),
6494            // RHS true on selected rows exercises the uniform-fill path.
6495            BooleanArray::from(vec![Some(true); 10]),
6496            // RHS false on selected rows exercises the return-LHS path.
6497            BooleanArray::from(vec![Some(false); 10]),
6498        ];
6499
6500        for d in d_cases {
6501            let batch = RecordBatch::try_new(
6502                Arc::clone(&schema),
6503                vec![
6504                    Arc::new(c.clone()) as ArrayRef,
6505                    Arc::new(d.clone()) as ArrayRef,
6506                ],
6507            )
6508            .unwrap();
6509
6510            let expr = logical2physical(&logical_col("c").or(logical_col("d")), &schema);
6511            let result = expr.evaluate(&batch).unwrap().into_array(c.len()).unwrap();
6512
6513            let expected = or_kleene(&c, &d).unwrap();
6514            assert_eq!(
6515                expected,
6516                *result.as_boolean(),
6517                "OR pre-selection must match Kleene OR for d = {d:?}"
6518            );
6519        }
6520    }
6521
6522    fn left_deep_and(conjuncts: &[Arc<dyn PhysicalExpr>]) -> Arc<dyn PhysicalExpr> {
6523        conjuncts
6524            .iter()
6525            .cloned()
6526            .reduce(|l, r| Arc::new(BinaryExpr::new(l, Operator::And, r)))
6527            .unwrap()
6528    }
6529
6530    fn right_deep_and(conjuncts: &[Arc<dyn PhysicalExpr>]) -> Arc<dyn PhysicalExpr> {
6531        conjuncts
6532            .iter()
6533            .cloned()
6534            .rev()
6535            .reduce(|r, l| Arc::new(BinaryExpr::new(l, Operator::And, r)))
6536            .unwrap()
6537    }
6538
6539    fn balanced_and(conjuncts: &[Arc<dyn PhysicalExpr>]) -> Arc<dyn PhysicalExpr> {
6540        if let [conjunct] = conjuncts {
6541            return Arc::clone(conjunct);
6542        }
6543        let (l, r) = conjuncts.split_at(conjuncts.len() / 2);
6544        Arc::new(BinaryExpr::new(
6545            balanced_and(l),
6546            Operator::And,
6547            balanced_and(r),
6548        ))
6549    }
6550
6551    type RowCountLog = Arc<std::sync::Mutex<Vec<(usize, usize)>>>;
6552
6553    /// Records rows seen by each conjunct and bypasses the cheap-expression path.
6554    #[derive(Debug)]
6555    struct RowCountRecorder {
6556        id: usize,
6557        inner: Arc<dyn PhysicalExpr>,
6558        log: RowCountLog,
6559    }
6560
6561    impl RowCountRecorder {
6562        fn wrap(
6563            id: usize,
6564            inner: &Arc<dyn PhysicalExpr>,
6565            log: &RowCountLog,
6566        ) -> Arc<dyn PhysicalExpr> {
6567            Arc::new(Self {
6568                id,
6569                inner: Arc::clone(inner),
6570                log: Arc::clone(log),
6571            })
6572        }
6573    }
6574
6575    impl PartialEq for RowCountRecorder {
6576        fn eq(&self, other: &Self) -> bool {
6577            self.id == other.id && self.inner.eq(&other.inner)
6578        }
6579    }
6580
6581    impl Eq for RowCountRecorder {}
6582
6583    impl Hash for RowCountRecorder {
6584        fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
6585            self.id.hash(state);
6586            self.inner.hash(state);
6587        }
6588    }
6589
6590    impl std::fmt::Display for RowCountRecorder {
6591        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
6592            write!(f, "{}", self.inner)
6593        }
6594    }
6595
6596    impl PhysicalExpr for RowCountRecorder {
6597        fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
6598            self.inner.data_type(input_schema)
6599        }
6600
6601        fn nullable(&self, input_schema: &Schema) -> Result<bool> {
6602            self.inner.nullable(input_schema)
6603        }
6604
6605        fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
6606            self.log.lock().unwrap().push((self.id, batch.num_rows()));
6607            self.inner.evaluate(batch)
6608        }
6609
6610        fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
6611            vec![&self.inner]
6612        }
6613
6614        fn with_new_children(
6615            self: Arc<Self>,
6616            mut children: Vec<Arc<dyn PhysicalExpr>>,
6617        ) -> Result<Arc<dyn PhysicalExpr>> {
6618            Ok(Self::wrap(self.id, &children.swap_remove(0), &self.log))
6619        }
6620
6621        fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6622            self.inner.fmt_sql(f)
6623        }
6624    }
6625
6626    #[test]
6627    fn test_conjunction_matches_kleene_and() -> Result<()> {
6628        use rand::rngs::StdRng;
6629        use rand::{Rng, SeedableRng};
6630
6631        let log = RowCountLog::default();
6632        let mut rng = StdRng::seed_from_u64(25035);
6633        for num_rows in [0, 1, 7, 100, 1000] {
6634            for _ in 0..50 {
6635                let mut fields = vec![];
6636                let mut columns: Vec<ArrayRef> = vec![];
6637                let mut conjuncts: Vec<Arc<dyn PhysicalExpr>> = vec![];
6638                let mut expected: Option<BooleanArray> = None;
6639                for id in 0..rng.random_range(2..=6) {
6640                    // Mostly nullable columns, sometimes a boolean literal.
6641                    let (conjunct, values): (Arc<dyn PhysicalExpr>, BooleanArray) = if rng
6642                        .random_bool(0.15)
6643                    {
6644                        let value =
6645                            [Some(true), Some(false), None][rng.random_range(0..3)];
6646                        (
6647                            lit(ScalarValue::Boolean(value)),
6648                            vec![value; num_rows].into(),
6649                        )
6650                    } else {
6651                        let p_true = [0.05, 0.3, 0.7, 0.95, 1.0][rng.random_range(0..5)];
6652                        let p_null = [0.0, 0.0, 0.1, 0.5][rng.random_range(0..4)];
6653                        let values = (0..num_rows)
6654                            .map(|_| {
6655                                (!rng.random_bool(p_null))
6656                                    .then(|| rng.random_bool(p_true))
6657                            })
6658                            .collect::<BooleanArray>();
6659                        let index = columns.len();
6660                        let name = format!("c{index}");
6661                        fields.push(Field::new(&name, DataType::Boolean, true));
6662                        columns.push(Arc::new(values.clone()));
6663                        (Arc::new(Column::new(&name, index)), values)
6664                    };
6665                    // Opaque half the time, so filtering kicks in.
6666                    let conjunct = if rng.random_bool(0.5) {
6667                        RowCountRecorder::wrap(id, &conjunct, &log)
6668                    } else {
6669                        conjunct
6670                    };
6671                    conjuncts.push(conjunct);
6672                    expected = Some(match expected {
6673                        None => values,
6674                        Some(acc) => and_kleene(&acc, &values)?,
6675                    });
6676                }
6677                let expected = expected.unwrap();
6678                let batch = RecordBatch::try_new_with_options(
6679                    Arc::new(Schema::new(fields)),
6680                    columns,
6681                    &RecordBatchOptions::new().with_row_count(Some(num_rows)),
6682                )?;
6683
6684                for expr in [
6685                    left_deep_and(&conjuncts),
6686                    right_deep_and(&conjuncts),
6687                    balanced_and(&conjuncts),
6688                ] {
6689                    let result = expr.evaluate(&batch)?.into_array(num_rows)?;
6690                    assert_eq!(&expected, result.as_boolean(), "{expr}");
6691                }
6692            }
6693        }
6694        // Filtering did kick in.
6695        let log = log.lock().unwrap();
6696        assert!(log.iter().any(|(_, rows)| (8..100).contains(rows)));
6697        Ok(())
6698    }
6699
6700    /// Compares three tree shapes and records rows seen by each conjunct.
6701    fn evaluate_recorded_conjunction(
6702        conjuncts: &[Arc<dyn PhysicalExpr>],
6703        batch: &RecordBatch,
6704    ) -> Result<(ArrayRef, Vec<usize>)> {
6705        let log = RowCountLog::default();
6706        let recorded: Vec<_> = conjuncts
6707            .iter()
6708            .enumerate()
6709            .map(|(id, conjunct)| RowCountRecorder::wrap(id, conjunct, &log))
6710            .collect();
6711
6712        let mut outcomes = vec![];
6713        for expr in [
6714            left_deep_and(&recorded),
6715            right_deep_and(&recorded),
6716            balanced_and(&recorded),
6717        ] {
6718            let result = expr.evaluate(batch)?.into_array(batch.num_rows())?;
6719            let log = std::mem::take(&mut *log.lock().unwrap());
6720            let (ids, rows): (Vec<_>, Vec<_>) = log.into_iter().unzip();
6721            assert_eq!(ids, (0..conjuncts.len()).collect::<Vec<_>>(), "{expr}");
6722            outcomes.push((result, rows));
6723        }
6724        // Tree shape must not change results or row counts.
6725        assert!(outcomes.windows(2).all(|w| w[0] == w[1]), "{outcomes:?}");
6726        Ok(outcomes.swap_remove(0))
6727    }
6728
6729    #[test]
6730    fn test_conjunction_filters_to_undecided_rows() -> Result<()> {
6731        let schema =
6732            Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
6733        let batch = RecordBatch::try_new(
6734            Arc::clone(&schema),
6735            vec![Arc::new(Int32Array::from_iter_values(0..100))],
6736        )?;
6737        let id_lt =
6738            |n: i32| logical2physical(&logical_col("id").lt(expr_lit(n)), &schema);
6739
6740        let (result, rows) = evaluate_recorded_conjunction(
6741            &[
6742                id_lt(50),
6743                id_lt(30),
6744                id_lt(20),
6745                // Filter when 20% remain.
6746                id_lt(10),
6747                // Filter again to the undecided rows.
6748                logical2physical(&logical_col("id").gt_eq(expr_lit(0)), &schema),
6749                id_lt(5),
6750            ],
6751            &batch,
6752        )?;
6753        assert_eq!(rows, vec![100, 100, 100, 20, 10, 10]);
6754        let expected: BooleanArray = (0..100).map(|id| Some(id < 5)).collect();
6755        assert_eq!(&expected, result.as_boolean());
6756        Ok(())
6757    }
6758
6759    #[test]
6760    fn test_conjunction_keeps_null_rows_undecided() -> Result<()> {
6761        let schema = Arc::new(Schema::new(vec![
6762            Field::new("id", DataType::Int32, false),
6763            Field::new("c", DataType::Boolean, true),
6764        ]));
6765        // `c` is NULL for ids 0..10, true for 10..15 and false otherwise.
6766        let c: BooleanArray = (0..100).map(|id| (id >= 10).then_some(id < 15)).collect();
6767        let batch = RecordBatch::try_new(
6768            Arc::clone(&schema),
6769            vec![Arc::new(Int32Array::from_iter_values(0..100)), Arc::new(c)],
6770        )?;
6771
6772        let (result, rows) = evaluate_recorded_conjunction(
6773            &[
6774                logical2physical(&logical_col("c"), &schema),
6775                logical2physical(&logical_col("id").gt_eq(expr_lit(5)), &schema),
6776            ],
6777            &batch,
6778        )?;
6779        // Keep all 10 NULL rows and the 5 true rows.
6780        assert_eq!(rows, vec![100, 15]);
6781        // A later false resolves the first 5 NULL rows.
6782        let expected: BooleanArray = (0..100)
6783            .map(|id| match id {
6784                0..5 => Some(false),
6785                5..10 => None,
6786                10..15 => Some(true),
6787                _ => Some(false),
6788            })
6789            .collect();
6790        assert_eq!(&expected, result.as_boolean());
6791        Ok(())
6792    }
6793
6794    #[test]
6795    fn test_conjunction_filters_before_fallible_conjunct() -> Result<()> {
6796        let schema = Arc::new(Schema::new(vec![
6797            Field::new("id", DataType::Int32, false),
6798            Field::new("a", DataType::Int32, false),
6799        ]));
6800        // `a` is only non-zero where `id < 10`.
6801        let batch = RecordBatch::try_new(
6802            Arc::clone(&schema),
6803            vec![
6804                Arc::new(Int32Array::from_iter_values(0..100)),
6805                Arc::new(Int32Array::from_iter_values(
6806                    (0..100).map(|id| if id < 10 { id + 1 } else { 0 }),
6807                )),
6808            ],
6809        )?;
6810        let conjuncts = [
6811            logical2physical(&logical_col("id").gt_eq(expr_lit(0)), &schema),
6812            logical2physical(&logical_col("id").lt(expr_lit(10)), &schema),
6813            // Divides by zero on the other 90 rows.
6814            logical2physical(
6815                &(expr_lit(100) / logical_col("a")).gt(expr_lit(1)),
6816                &schema,
6817            ),
6818        ];
6819
6820        let expected: BooleanArray = (0..100).map(|id| Some(id < 10)).collect();
6821        for expr in [
6822            left_deep_and(&conjuncts),
6823            right_deep_and(&conjuncts),
6824            balanced_and(&conjuncts),
6825        ] {
6826            let result = expr.evaluate(&batch)?.into_array(batch.num_rows())?;
6827            assert_eq!(&expected, result.as_boolean(), "{expr}");
6828        }
6829        Ok(())
6830    }
6831
6832    #[test]
6833    fn test_is_cheap_and_infallible() {
6834        use datafusion_expr::{binary_expr, cast, not};
6835
6836        let schema = Schema::new(vec![
6837            Field::new("a", DataType::Int32, true),
6838            Field::new("b", DataType::Int32, true),
6839            Field::new("c", DataType::Boolean, true),
6840            Field::new("s", DataType::Utf8, true),
6841        ]);
6842        let is_cheap = |expr: &datafusion_expr::Expr| {
6843            is_cheap_and_infallible(&logical2physical(expr, &schema), &schema)
6844        };
6845        let (a, b, c, s) = (
6846            logical_col("a"),
6847            logical_col("b"),
6848            logical_col("c"),
6849            logical_col("s"),
6850        );
6851
6852        assert!(is_cheap(&a.clone().lt(expr_lit(5))));
6853        assert!(is_cheap(&a.clone().eq(b.clone()).and(not(c.clone()))));
6854        assert!(is_cheap(
6855            &c.clone().is_null().or(a.clone().gt_eq(expr_lit(1)))
6856        ));
6857        assert!(is_cheap(&binary_expr(
6858            a.clone(),
6859            Operator::IsDistinctFrom,
6860            b.clone(),
6861        )));
6862        assert!(is_cheap(&s.clone().not_eq(expr_lit("x"))));
6863        assert!(is_cheap(
6864            &a.clone().in_list(vec![expr_lit(1), expr_lit(2)], false)
6865        ));
6866        // Widening and wrapping arithmetic cannot fail.
6867        assert!(is_cheap(
6868            &cast(a.clone(), DataType::Int64).lt(expr_lit(5i64))
6869        ));
6870        assert!(is_cheap(
6871            &(a.clone() * b.clone() - expr_lit(1)).gt(a.clone())
6872        ));
6873
6874        // Narrowing, parsing, division, and checked arithmetic can fail.
6875        let checked_plus = BinaryExpr::new(
6876            logical2physical(&a, &schema),
6877            Operator::Plus,
6878            logical2physical(&b, &schema),
6879        )
6880        .with_fail_on_overflow(true);
6881        assert!(!is_cheap_and_infallible(
6882            &(Arc::new(checked_plus) as _),
6883            &schema
6884        ));
6885        assert!(!is_cheap(
6886            &cast(a.clone(), DataType::Int8).lt(expr_lit(5i8))
6887        ));
6888        assert!(!is_cheap(&cast(s.clone(), DataType::Int32).gt(a.clone())));
6889        assert!(!is_cheap(&(expr_lit(10) / a.clone()).gt(expr_lit(1))));
6890        assert!(!is_cheap(&a.in_list(vec![expr_lit(10) / b.clone()], false)));
6891        assert!(!is_cheap(&s.clone().like(expr_lit("x%"))));
6892        assert!(!is_cheap(&binary_expr(
6893            s,
6894            Operator::RegexMatch,
6895            expr_lit("x")
6896        )));
6897    }
6898
6899    #[test]
6900    fn test_rows_to_filter_before() {
6901        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
6902        let cheap = logical2physical(&logical_col("a").lt(expr_lit(5)), &schema);
6903        let fallible =
6904            logical2physical(&(expr_lit(10) / logical_col("a")).gt(expr_lit(1)), &schema);
6905        // 1 true and 1 NULL row out of 10.
6906        let few_left = ColumnarValue::Array(Arc::new(BooleanArray::from(
6907            (0..10)
6908                .map(|i| (i != 1).then_some(i == 0))
6909                .collect::<Vec<_>>(),
6910        )));
6911        let many_left = ColumnarValue::Array(Arc::new(BooleanArray::from(
6912            (0..10).map(|i| Some(i < 3)).collect::<Vec<_>>(),
6913        )));
6914        let all_true = ColumnarValue::Array(Arc::new(BooleanArray::from(vec![true; 10])));
6915
6916        // Filter before fallible work when few rows remain; keep NULLs.
6917        let expected = BooleanArray::from((0..10).map(|i| i < 2).collect::<Vec<_>>());
6918        assert_eq!(
6919            rows_to_filter_before(&fallible, &few_left, &schema, 10),
6920            Some(expected)
6921        );
6922        assert_eq!(rows_to_filter_before(&cheap, &few_left, &schema, 10), None);
6923        assert_eq!(
6924            rows_to_filter_before(&fallible, &many_left, &schema, 10),
6925            None
6926        );
6927        assert_eq!(
6928            rows_to_filter_before(&fallible, &all_true, &schema, 10),
6929            None
6930        );
6931        let scalar = ColumnarValue::Scalar(ScalarValue::Boolean(None));
6932        assert_eq!(rows_to_filter_before(&fallible, &scalar, &schema, 10), None);
6933    }
6934
6935    #[test]
6936    fn test_conjunction_rejects_non_boolean_operand() -> Result<()> {
6937        let schema = Arc::new(Schema::new(vec![
6938            Field::new("a", DataType::Int32, false),
6939            Field::new("b", DataType::Boolean, false),
6940        ]));
6941        let batch = RecordBatch::try_new(
6942            Arc::clone(&schema),
6943            vec![
6944                Arc::new(Int32Array::from(vec![1, 2])),
6945                Arc::new(BooleanArray::from(vec![true, false])),
6946            ],
6947        )?;
6948        let (a, b) = (col("a", &schema)?, col("b", &schema)?);
6949
6950        for expr in [
6951            BinaryExpr::new(Arc::clone(&a), Operator::And, Arc::clone(&b)),
6952            BinaryExpr::new(b, Operator::And, a),
6953        ] {
6954            let err = expr.evaluate(&batch).unwrap_err();
6955            assert_contains!(err.to_string(), "Cannot evaluate AND with a Int32 operand");
6956        }
6957        Ok(())
6958    }
6959
6960    #[test]
6961    fn test_integer_interval_propagation_covers_runtime_values() {
6962        // Enumerate small domains and both ends of Int8, including zero divisors,
6963        // truncation, signed overflow and checked arithmetic. Every successful
6964        // runtime evaluation must remain possible after interval propagation.
6965        let batch = RecordBatch::new_empty(Arc::new(Schema::empty()));
6966        let domains = [
6967            (-3i8, 3i8),
6968            (0, 1),
6969            (1, 3),
6970            (-3, -1),
6971            (-128, -127),
6972            (126, 127),
6973        ];
6974        for checked in [false, true] {
6975            for op in [
6976                Operator::Plus,
6977                Operator::Minus,
6978                Operator::Multiply,
6979                Operator::Divide,
6980            ] {
6981                let expr = BinaryExpr::new(lit(0i8), op, lit(0i8))
6982                    .with_fail_on_overflow(checked);
6983                for (lo, hi) in domains {
6984                    for (rlo, rhi) in
6985                        domains.into_iter().chain([(-1, -1), (0, 0), (2, 2)])
6986                    {
6987                        let left = Interval::make(Some(lo), Some(hi)).unwrap();
6988                        let right = Interval::make(Some(rlo), Some(rhi)).unwrap();
6989                        let bounds = expr.evaluate_bounds(&[&left, &right]).unwrap();
6990                        if matches!(op, Operator::Plus | Operator::Minus) {
6991                            let children = [left.clone(), right.clone()].map(|range| {
6992                                ExprProperties {
6993                                    range,
6994                                    ..ExprProperties::new_unknown()
6995                                }
6996                            });
6997                            assert_eq!(
6998                                expr.get_properties(&children).unwrap().range,
6999                                bounds
7000                            );
7001                        }
7002                        for a in lo..=hi {
7003                            for b in rlo..=rhi {
7004                                // Use the execution kernel as the oracle rather than
7005                                // duplicating its checked and wrapping arithmetic.
7006                                let runtime = BinaryExpr::new(lit(a), op, lit(b))
7007                                    .with_fail_on_overflow(checked);
7008                                let result = match runtime.evaluate(&batch) {
7009                                    Ok(value) => value.into_array(1).unwrap(),
7010                                    Err(error) => {
7011                                        assert!(
7012                                            checked || op == Operator::Divide,
7013                                            "wrapping {a} {op} {b} failed: {error}"
7014                                        );
7015                                        continue;
7016                                    }
7017                                };
7018                                let result = result.as_primitive::<Int8Type>().value(0);
7019                                let result =
7020                                    Interval::make(Some(result), Some(result)).unwrap();
7021                                assert_eq!(
7022                                    bounds.contains(&result).unwrap(),
7023                                    Interval::TRUE,
7024                                    "forward {a} {op} {b}, checked={checked}, bounds={bounds:?}"
7025                                );
7026                                let propagated = expr
7027                                    .propagate_constraints(&result, &[&left, &right])
7028                                    .unwrap();
7029                                let propagated = propagated
7030                                    .expect("successful runtime result must be feasible");
7031                                if !propagated.is_empty() {
7032                                    assert_eq!(
7033                                        propagated[0]
7034                                            .contains(
7035                                                Interval::make(Some(a), Some(a)).unwrap()
7036                                            )
7037                                            .unwrap(),
7038                                        Interval::TRUE,
7039                                        "left input excluded for {a} {op} {b}, checked={checked}: {propagated:?}"
7040                                    );
7041                                    assert_eq!(
7042                                        propagated[1]
7043                                            .contains(
7044                                                Interval::make(Some(b), Some(b)).unwrap()
7045                                            )
7046                                            .unwrap(),
7047                                        Interval::TRUE,
7048                                        "right input excluded for {a} {op} {b}, checked={checked}: {propagated:?}"
7049                                    );
7050                                }
7051                            }
7052                        }
7053                    }
7054                }
7055            }
7056        }
7057    }
7058
7059    #[test]
7060    fn test_integer_interval_error_propagation() {
7061        // Compare error messages without backtraces, which differ by call path.
7062        let integer = Interval::make(Some(1i32), Some(2i32)).unwrap();
7063        let boolean = Interval::TRUE;
7064        for op in [Operator::Plus, Operator::Minus] {
7065            let expr = BinaryExpr::new(lit(1i32), op, lit(true));
7066            let expected = apply_operator(&op, &integer, &boolean)
7067                .unwrap_err()
7068                .strip_backtrace();
7069            assert_eq!(
7070                expr.evaluate_bounds(&[&integer, &boolean])
7071                    .unwrap_err()
7072                    .strip_backtrace(),
7073                expected
7074            );
7075            let children =
7076                [integer.clone(), boolean.clone()].map(|range| ExprProperties {
7077                    range,
7078                    ..ExprProperties::new_unknown()
7079                });
7080            assert_eq!(
7081                expr.get_properties(&children)
7082                    .unwrap_err()
7083                    .strip_backtrace(),
7084                expected
7085            );
7086        }
7087
7088        // A nonnumeric parent cannot describe an integer product. Preserve
7089        // the error from constructing zero for its unsupported type.
7090        let parent = Interval::make_unbounded(&DataType::Utf8).unwrap();
7091        let expr = BinaryExpr::new(lit(1i32), Operator::Multiply, lit(2i32));
7092        assert_eq!(
7093            expr.propagate_constraints(&parent, &[&integer, &integer])
7094                .unwrap_err()
7095                .strip_backtrace(),
7096            ScalarValue::new_zero(&DataType::Utf8)
7097                .unwrap_err()
7098                .strip_backtrace()
7099        );
7100    }
7101
7102    #[test]
7103    fn test_unsigned_subtraction_interval_underflow() {
7104        let expr = BinaryExpr::new(lit(0u8), Operator::Minus, lit(1u8));
7105        let left = Interval::make(Some(0u8), Some(2u8)).unwrap();
7106        let right = Interval::make(Some(1u8), Some(1u8)).unwrap();
7107        let wrapped = Interval::make(Some(255u8), Some(255u8)).unwrap();
7108        assert_eq!(
7109            expr.evaluate_bounds(&[&left, &right])
7110                .unwrap()
7111                .contains(&wrapped)
7112                .unwrap(),
7113            Interval::TRUE
7114        );
7115        assert_eq!(
7116            expr.propagate_constraints(&wrapped, &[&left, &right])
7117                .unwrap(),
7118            Some(vec![])
7119        );
7120    }
7121
7122    #[test]
7123    fn test_nested_wrapping_arithmetic_properties() {
7124        let difference = Arc::new(BinaryExpr::new(lit(0u8), Operator::Minus, lit(1u8)));
7125        let singleton = |value: u8| ExprProperties {
7126            sort_properties: SortProperties::Singleton,
7127            range: Interval::make(Some(value), Some(value)).unwrap(),
7128            ..ExprProperties::new_unknown()
7129        };
7130        let difference_props = difference
7131            .get_properties(&[singleton(0), singleton(1)])
7132            .unwrap();
7133        assert_eq!(difference_props.sort_properties, SortProperties::Singleton);
7134        assert!(
7135            difference_props
7136                .range
7137                .contains_value(ScalarValue::UInt8(Some(255)))
7138                .unwrap()
7139        );
7140
7141        // The inner constant wraps to 255. An incorrect range of [0, 0]
7142        // would let the outer addition claim to preserve ascending order.
7143        let expr =
7144            BinaryExpr::new(Arc::new(Column::new("a", 0)), Operator::Plus, difference);
7145        let properties = expr
7146            .get_properties(&[
7147                ExprProperties {
7148                    sort_properties: SortProperties::Ordered(SortOptions::default()),
7149                    range: Interval::make(Some(0u8), Some(1u8)).unwrap(),
7150                    ..ExprProperties::new_unknown()
7151                },
7152                difference_props,
7153            ])
7154            .unwrap();
7155        let batch = RecordBatch::try_new(
7156            Arc::new(Schema::new(vec![Field::new("a", DataType::UInt8, false)])),
7157            vec![Arc::new(UInt8Array::from(vec![0, 1]))],
7158        )
7159        .unwrap();
7160        let actual = expr.evaluate(&batch).unwrap().into_array(2).unwrap();
7161        assert_eq!(actual.as_ref(), &UInt8Array::from(vec![255, 0]));
7162        assert_eq!(properties.sort_properties, SortProperties::Unordered);
7163        for value in [0u8, 255] {
7164            assert!(
7165                properties
7166                    .range
7167                    .contains_value(ScalarValue::UInt8(Some(value)))
7168                    .unwrap()
7169            );
7170        }
7171    }
7172
7173    #[test]
7174    fn test_integer_comparison_still_propagates() {
7175        // Integer comparisons must bypass the arithmetic overflow guard and
7176        // still narrow their inputs: a = 5 restricts a in [0, 10] to [5, 5].
7177        let expr = BinaryExpr::new(lit(0i32), Operator::Eq, lit(5i32));
7178        let left = Interval::make(Some(0i32), Some(10i32)).unwrap();
7179        let right = Interval::make(Some(5i32), Some(5i32)).unwrap();
7180        assert_eq!(
7181            expr.propagate_constraints(&Interval::TRUE, &[&left, &right])
7182                .unwrap(),
7183            Some(vec![right.clone(), right])
7184        );
7185    }
7186
7187    #[test]
7188    fn test_safe_integer_multiplication_still_propagates() {
7189        let expr = BinaryExpr::new(lit(0i32), Operator::Multiply, lit(2i32));
7190        let left = Interval::make(Some(0i32), Some(10i32)).unwrap();
7191        let right = Interval::make(Some(2i32), Some(2i32)).unwrap();
7192        let parent = Interval::make(Some(4i32), Some(4i32)).unwrap();
7193        assert_eq!(
7194            expr.propagate_constraints(&parent, &[&left, &right])
7195                .unwrap(),
7196            Some(vec![Interval::make(Some(2i32), Some(2i32)).unwrap(), right])
7197        );
7198    }
7199
7200    #[test]
7201    fn test_evaluate_bounds_int32() {
7202        let schema = Schema::new(vec![
7203            Field::new("a", DataType::Int32, false),
7204            Field::new("b", DataType::Int32, false),
7205        ]);
7206
7207        let a = Arc::new(Column::new("a", 0)) as _;
7208        let b = Arc::new(Column::new("b", 1)) as _;
7209
7210        // Test addition bounds
7211        let add_expr =
7212            binary_expr(Arc::clone(&a), Operator::Plus, Arc::clone(&b), &schema).unwrap();
7213        let add_bounds = add_expr
7214            .evaluate_bounds(&[
7215                &Interval::make(Some(1), Some(10)).unwrap(),
7216                &Interval::make(Some(5), Some(15)).unwrap(),
7217            ])
7218            .unwrap();
7219        assert_eq!(add_bounds, Interval::make(Some(6), Some(25)).unwrap());
7220
7221        // Test subtraction bounds
7222        let sub_expr =
7223            binary_expr(Arc::clone(&a), Operator::Minus, Arc::clone(&b), &schema)
7224                .unwrap();
7225        let sub_bounds = sub_expr
7226            .evaluate_bounds(&[
7227                &Interval::make(Some(1), Some(10)).unwrap(),
7228                &Interval::make(Some(5), Some(15)).unwrap(),
7229            ])
7230            .unwrap();
7231        assert_eq!(sub_bounds, Interval::make(Some(-14), Some(5)).unwrap());
7232
7233        // Test multiplication bounds
7234        let mul_expr =
7235            binary_expr(Arc::clone(&a), Operator::Multiply, Arc::clone(&b), &schema)
7236                .unwrap();
7237        let mul_bounds = mul_expr
7238            .evaluate_bounds(&[
7239                &Interval::make(Some(1), Some(10)).unwrap(),
7240                &Interval::make(Some(5), Some(15)).unwrap(),
7241            ])
7242            .unwrap();
7243        assert_eq!(mul_bounds, Interval::make(Some(5), Some(150)).unwrap());
7244
7245        // Test division bounds
7246        let div_expr =
7247            binary_expr(Arc::clone(&a), Operator::Divide, Arc::clone(&b), &schema)
7248                .unwrap();
7249        let div_bounds = div_expr
7250            .evaluate_bounds(&[
7251                &Interval::make(Some(10), Some(20)).unwrap(),
7252                &Interval::make(Some(2), Some(5)).unwrap(),
7253            ])
7254            .unwrap();
7255        assert_eq!(div_bounds, Interval::make(Some(2), Some(10)).unwrap());
7256    }
7257
7258    #[test]
7259    fn test_evaluate_bounds_bool() {
7260        let schema = Schema::new(vec![
7261            Field::new("a", DataType::Boolean, false),
7262            Field::new("b", DataType::Boolean, false),
7263        ]);
7264
7265        let a = Arc::new(Column::new("a", 0)) as _;
7266        let b = Arc::new(Column::new("b", 1)) as _;
7267
7268        // Test OR bounds
7269        let or_expr =
7270            binary_expr(Arc::clone(&a), Operator::Or, Arc::clone(&b), &schema).unwrap();
7271        let or_bounds = or_expr
7272            .evaluate_bounds(&[
7273                &Interval::make(Some(true), Some(true)).unwrap(),
7274                &Interval::make(Some(false), Some(false)).unwrap(),
7275            ])
7276            .unwrap();
7277        assert_eq!(or_bounds, Interval::make(Some(true), Some(true)).unwrap());
7278
7279        // Test AND bounds
7280        let and_expr =
7281            binary_expr(Arc::clone(&a), Operator::And, Arc::clone(&b), &schema).unwrap();
7282        let and_bounds = and_expr
7283            .evaluate_bounds(&[
7284                &Interval::make(Some(true), Some(true)).unwrap(),
7285                &Interval::make(Some(false), Some(false)).unwrap(),
7286            ])
7287            .unwrap();
7288        assert_eq!(
7289            and_bounds,
7290            Interval::make(Some(false), Some(false)).unwrap()
7291        );
7292    }
7293
7294    #[test]
7295    fn test_evaluate_nested_type() {
7296        let batch_schema = Arc::new(Schema::new(vec![
7297            Field::new(
7298                "a",
7299                DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))),
7300                true,
7301            ),
7302            Field::new(
7303                "b",
7304                DataType::List(Arc::new(Field::new_list_field(DataType::Int32, true))),
7305                true,
7306            ),
7307        ]));
7308
7309        let mut list_builder_a = ListBuilder::new(Int32Builder::new());
7310
7311        list_builder_a.append_value([Some(1)]);
7312        list_builder_a.append_value([Some(2)]);
7313        list_builder_a.append_value([]);
7314        list_builder_a.append_value([None]);
7315
7316        let list_array_a: ArrayRef = Arc::new(list_builder_a.finish());
7317
7318        let mut list_builder_b = ListBuilder::new(Int32Builder::new());
7319
7320        list_builder_b.append_value([Some(1)]);
7321        list_builder_b.append_value([Some(2)]);
7322        list_builder_b.append_value([]);
7323        list_builder_b.append_value([None]);
7324
7325        let list_array_b: ArrayRef = Arc::new(list_builder_b.finish());
7326
7327        let batch =
7328            RecordBatch::try_new(batch_schema, vec![list_array_a, list_array_b]).unwrap();
7329
7330        let schema = Arc::new(Schema::new(vec![
7331            Field::new(
7332                "a",
7333                DataType::List(Arc::new(Field::new("foo", DataType::Int32, true))),
7334                true,
7335            ),
7336            Field::new(
7337                "b",
7338                DataType::List(Arc::new(Field::new("bar", DataType::Int32, true))),
7339                true,
7340            ),
7341        ]));
7342
7343        let a = Arc::new(Column::new("a", 0)) as _;
7344        let b = Arc::new(Column::new("b", 1)) as _;
7345
7346        let eq_expr =
7347            binary_expr(Arc::clone(&a), Operator::Eq, Arc::clone(&b), &schema).unwrap();
7348
7349        let eq_result = eq_expr.evaluate(&batch).unwrap();
7350        let expected =
7351            BooleanArray::from_iter(vec![Some(true), Some(true), Some(true), Some(true)]);
7352        assert_eq!(eq_result.into_array(4).unwrap().as_boolean(), &expected);
7353    }
7354}