Skip to main content

datafusion_physical_expr/expressions/
binary.rs

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