Skip to main content

datafusion_optimizer/simplify_expressions/
expr_simplifier.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Expression simplification API
6
7use arrow::{
8    array::{Array, AsArray, new_null_array},
9    datatypes::{DataType, Field, Schema},
10    record_batch::RecordBatch,
11};
12use std::borrow::Cow;
13use std::collections::HashSet;
14use std::ops::Not;
15use std::sync::Arc;
16use std::sync::LazyLock;
17
18use datafusion_common::config::ConfigOptions;
19use datafusion_common::float_semantics::has_float_leaf;
20use datafusion_common::nested_struct::has_one_of_more_common_fields;
21use datafusion_common::{
22    DFSchema, DataFusionError, Result, ScalarValue, exec_datafusion_err, internal_err,
23};
24use datafusion_common::{
25    HashMap,
26    cast::{as_large_list_array, as_list_array},
27    metadata::FieldMetadata,
28    tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRewriter},
29};
30use datafusion_expr::expr::HigherOrderFunction;
31use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
32use datafusion_expr::{
33    BinaryExpr, Case, ColumnarValue, Expr, ExprSchemable, Like, Operator, Volatility,
34    and, binary::BinaryTypeCoercer, lit, or, preimage::PreimageResult,
35};
36use datafusion_expr::{
37    Cast, TryCast,
38    simplify::{ExprSimplifyResult, REGEX_PLANNING_SIZE_LIMIT_BYTES},
39};
40use datafusion_expr::{expr::ScalarFunction, interval_arithmetic::NullableInterval};
41use datafusion_expr::{
42    expr::{InList, InSubquery},
43    utils::{iter_conjunction, iter_conjunction_owned},
44};
45use datafusion_physical_expr::{create_physical_expr, execution_props::ExecutionProps};
46
47use super::inlist_simplifier::ShortenInListSimplifier;
48use super::utils::*;
49use crate::simplify_expressions::SimplifyContext;
50use crate::simplify_expressions::cast_preimage::{
51    rewrite_cast_predicate_for_binary, rewrite_cast_predicate_for_inlist,
52    supports_cast_predicate_for_binary, supports_cast_predicate_for_inlist,
53};
54use crate::simplify_expressions::regex::simplify_regex_expr;
55use crate::{
56    analyzer::type_coercion::TypeCoercionRewriter,
57    simplify_expressions::udf_preimage::rewrite_with_preimage,
58};
59use datafusion_expr::expr_rewriter::rewrite_with_guarantees_map;
60use indexmap::IndexSet;
61use regex::{Error as RegexError, Regex, RegexBuilder};
62
63/// This structure handles API for expression simplification
64///
65/// Provides simplification information based on DFSchema and
66/// [`ExecutionProps`]. This is the default implementation used by DataFusion
67///
68/// For example:
69/// ```
70/// use arrow::datatypes::{DataType, Field, Schema};
71/// use datafusion_common::{DataFusionError, ToDFSchema};
72/// use datafusion_expr::simplify::SimplifyContext;
73/// use datafusion_expr::{col, lit};
74/// use datafusion_optimizer::simplify_expressions::ExprSimplifier;
75///
76/// // Create the schema
77/// let schema = Schema::new(vec![Field::new("i", DataType::Int64, false)])
78///     .to_dfschema_ref()
79///     .unwrap();
80///
81/// // Create the simplifier
82/// let context = SimplifyContext::builder().with_schema(schema).build();
83/// let simplifier = ExprSimplifier::new(context);
84///
85/// // Use the simplifier
86///
87/// // b < 2 or (1 > 3)
88/// let expr = col("b").lt(lit(2)).or(lit(1).gt(lit(3)));
89///
90/// // b < 2
91/// let simplified = simplifier.simplify(expr).unwrap();
92/// assert_eq!(simplified, col("b").lt(lit(2)));
93/// ```
94pub struct ExprSimplifier {
95    info: SimplifyContext,
96    /// Guarantees about the values of columns. This is provided by the user
97    /// in [ExprSimplifier::with_guarantees()].
98    guarantees: Vec<(Expr, NullableInterval)>,
99    /// Should expressions be canonicalized before simplification? Defaults to
100    /// true
101    canonicalize: bool,
102    /// Maximum number of simplifier cycles
103    max_simplifier_cycles: u32,
104}
105
106/// Largest `IN` list considered for expansion into binary comparisons.
107///
108/// The final decision also accounts for the measured performance of the column
109/// representation and whether the list values are literals.
110/// See [PR #25187](https://github.com/apache/datafusion/pull/25187) for the
111/// benchmark evidence.
112pub const THRESHOLD_INLINE_INLIST: usize = 3;
113pub const DEFAULT_MAX_SIMPLIFIER_CYCLES: u32 = 3;
114
115impl ExprSimplifier {
116    /// Create a new `ExprSimplifier` with the given [`SimplifyContext`].
117    /// See [`simplify`](Self::simplify) for an example.
118    ///
119    /// [`SimplifyContext`]: datafusion_expr::simplify::SimplifyContext
120    pub fn new(info: SimplifyContext) -> Self {
121        Self {
122            info,
123            guarantees: vec![],
124            canonicalize: true,
125            max_simplifier_cycles: DEFAULT_MAX_SIMPLIFIER_CYCLES,
126        }
127    }
128
129    /// Simplifies this [`Expr`] as much as possible, evaluating
130    /// constants and applying algebraic simplifications.
131    ///
132    /// The types of the expression must match what operators expect,
133    /// or else an error may occur trying to evaluate. See
134    /// [`coerce`](Self::coerce) for a function to help.
135    ///
136    /// # Example:
137    ///
138    /// `b > 2 AND b > 2`
139    ///
140    /// can be written to
141    ///
142    /// `b > 2`
143    ///
144    /// ```
145    /// use arrow::datatypes::{DataType, Field, Schema};
146    /// use datafusion_common::{DFSchema, ToDFSchema};
147    /// use datafusion_common::Result;
148    /// use datafusion_expr::simplify::SimplifyContext;
149    /// use datafusion_expr::{col, lit, Expr};
150    /// use datafusion_optimizer::simplify_expressions::ExprSimplifier;
151    /// use std::sync::Arc;
152    ///
153    /// // Create a schema and SimplifyContext
154    /// let schema = Schema::new(vec![Field::new("b", DataType::Int32, true)])
155    ///     .to_dfschema_ref()
156    ///     .unwrap();
157    /// // Create the simplifier
158    /// let context = SimplifyContext::builder().with_schema(schema).build();
159    /// let simplifier = ExprSimplifier::new(context);
160    ///
161    /// // b < 2
162    /// let b_lt_2 = col("b").gt(lit(2));
163    ///
164    /// // (b < 2) OR (b < 2)
165    /// let expr = b_lt_2.clone().or(b_lt_2.clone());
166    ///
167    /// // (b < 2) OR (b < 2) --> (b < 2)
168    /// let expr = simplifier.simplify(expr).unwrap();
169    /// assert_eq!(expr, b_lt_2);
170    /// ```
171    pub fn simplify(&self, expr: Expr) -> Result<Expr> {
172        Ok(self.simplify_with_cycle_count_transformed(expr)?.0.data)
173    }
174
175    /// Like [Self::simplify], simplifies this [`Expr`] as much as possible, evaluating
176    /// constants and applying algebraic simplifications. Additionally returns a `u32`
177    /// representing the number of simplification cycles performed, which can be useful for testing
178    /// optimizations.
179    ///
180    /// # Returns
181    ///
182    /// A tuple containing:
183    /// - The simplified expression wrapped in a `Transformed<Expr>` indicating if changes were made
184    /// - The number of simplification cycles that were performed
185    ///
186    /// See [Self::simplify] for details and usage examples.
187    pub fn simplify_with_cycle_count_transformed(
188        &self,
189        mut expr: Expr,
190    ) -> Result<(Transformed<Expr>, u32)> {
191        let mut simplifier = Simplifier::new(&self.info);
192        let config_options = Some(Arc::clone(self.info.config_options()));
193        let mut const_evaluator = ConstEvaluator::try_new(config_options)?;
194        let mut shorten_in_list_simplifier =
195            ShortenInListSimplifier::new(self.info.schema());
196        let guarantees_map: HashMap<&Expr, &NullableInterval> =
197            self.guarantees.iter().map(|(k, v)| (k, v)).collect();
198
199        if self.canonicalize {
200            expr = expr.rewrite(&mut Canonicalizer::new()).data()?
201        }
202
203        // Evaluating constants can enable new simplifications and
204        // simplifications can enable new constant evaluation
205        // see `Self::with_max_cycles`
206        let mut num_cycles = 0;
207        let mut has_transformed = false;
208        loop {
209            let Transformed {
210                data, transformed, ..
211            } = expr
212                .rewrite(&mut const_evaluator)?
213                .transform_data(|expr| expr.rewrite(&mut simplifier))?
214                .transform_data(|expr| {
215                    rewrite_with_guarantees_map(expr, &guarantees_map)
216                })?;
217            expr = data;
218            num_cycles += 1;
219            // Track if any transformation occurred
220            has_transformed = has_transformed || transformed;
221            if !transformed || num_cycles >= self.max_simplifier_cycles {
222                break;
223            }
224        }
225        // shorten inlist should be started after other inlist rules are applied
226        expr = expr.rewrite(&mut shorten_in_list_simplifier).data()?;
227        Ok((
228            Transformed::new_transformed(expr, has_transformed),
229            num_cycles,
230        ))
231    }
232
233    /// Apply type coercion to an [`Expr`] so that it can be
234    /// evaluated as a [`PhysicalExpr`](datafusion_physical_expr::PhysicalExpr).
235    ///
236    /// See the [type coercion module](datafusion_expr::type_coercion)
237    /// documentation for more details on type coercion
238    pub fn coerce(&self, expr: Expr, schema: &DFSchema) -> Result<Expr> {
239        let mut expr_rewrite = TypeCoercionRewriter::new(schema).with_session_time_zone(
240            self.info
241                .config_options()
242                .execution
243                .time_zone
244                .as_ref()
245                .map(|tz| tz.as_str()),
246        );
247        expr.rewrite(&mut expr_rewrite).data()
248    }
249
250    /// Input guarantees about the values of columns.
251    ///
252    /// The guarantees can simplify expressions. For example, if a column `x` is
253    /// guaranteed to be `3`, then the expression `x > 1` can be replaced by the
254    /// literal `true`.
255    ///
256    /// The guarantees are provided as a `Vec<(Expr, NullableInterval)>`,
257    /// where the [Expr] is a column reference and the [NullableInterval]
258    /// is an interval representing the known possible values of that column.
259    ///
260    /// ```rust
261    /// use arrow::datatypes::{DataType, Field, Schema};
262    /// use datafusion_common::{Result, ScalarValue, ToDFSchema};
263    /// use datafusion_expr::interval_arithmetic::{Interval, NullableInterval};
264    /// use datafusion_expr::simplify::SimplifyContext;
265    /// use datafusion_expr::{col, lit, Expr};
266    /// use datafusion_optimizer::simplify_expressions::ExprSimplifier;
267    ///
268    /// let schema = Schema::new(vec![
269    ///     Field::new("x", DataType::Int64, false),
270    ///     Field::new("y", DataType::UInt32, false),
271    ///     Field::new("z", DataType::Int64, false),
272    /// ])
273    /// .to_dfschema_ref()
274    /// .unwrap();
275    ///
276    /// // Create the simplifier
277    /// let context = SimplifyContext::builder().with_schema(schema).build();
278    ///
279    /// // Expression: (x >= 3) AND (y + 2 < 10) AND (z > 5)
280    /// let expr_x = col("x").gt_eq(lit(3_i64));
281    /// let expr_y = (col("y") + lit(2_u32)).lt(lit(10_u32));
282    /// let expr_z = col("z").gt(lit(5_i64));
283    /// let expr = expr_x.and(expr_y).and(expr_z.clone());
284    ///
285    /// let guarantees = vec![
286    ///     // x ∈ [3, 5]
287    ///     (
288    ///         col("x"),
289    ///         NullableInterval::NotNull {
290    ///             values: Interval::make(Some(3_i64), Some(5_i64)).unwrap(),
291    ///         },
292    ///     ),
293    ///     // y = 3
294    ///     (
295    ///         col("y"),
296    ///         NullableInterval::from(ScalarValue::UInt32(Some(3))),
297    ///     ),
298    /// ];
299    /// let simplifier = ExprSimplifier::new(context).with_guarantees(guarantees);
300    /// let output = simplifier.simplify(expr).unwrap();
301    /// // Expression becomes: true AND true AND (z > 5), which simplifies to
302    /// // z > 5.
303    /// assert_eq!(output, expr_z);
304    /// ```
305    pub fn with_guarantees(mut self, guarantees: Vec<(Expr, NullableInterval)>) -> Self {
306        self.guarantees = guarantees;
307        self
308    }
309
310    /// Should `Canonicalizer` be applied before simplification?
311    ///
312    /// If true (the default), the expression will be rewritten to canonical
313    /// form before simplification. This is useful to ensure that the simplifier
314    /// can apply all possible simplifications.
315    ///
316    /// Some expressions, such as those in some Joins, can not be canonicalized
317    /// without changing their meaning. In these cases, canonicalization should
318    /// be disabled.
319    ///
320    /// ```rust
321    /// use arrow::datatypes::{DataType, Field, Schema};
322    /// use datafusion_common::{Result, ScalarValue, ToDFSchema};
323    /// use datafusion_expr::interval_arithmetic::{Interval, NullableInterval};
324    /// use datafusion_expr::simplify::SimplifyContext;
325    /// use datafusion_expr::{col, lit, Expr};
326    /// use datafusion_optimizer::simplify_expressions::ExprSimplifier;
327    ///
328    /// let schema = Schema::new(vec![
329    ///     Field::new("a", DataType::Int64, false),
330    ///     Field::new("b", DataType::Int64, false),
331    ///     Field::new("c", DataType::Int64, false),
332    /// ])
333    /// .to_dfschema_ref()
334    /// .unwrap();
335    ///
336    /// // Create the simplifier
337    /// let context = SimplifyContext::builder().with_schema(schema).build();
338    /// let simplifier = ExprSimplifier::new(context);
339    ///
340    /// // Expression: a = c AND 1 = b
341    /// let expr = col("a").eq(col("c")).and(lit(1).eq(col("b")));
342    ///
343    /// // With canonicalization, the expression is rewritten to canonical form
344    /// // (though it is no simpler in this case):
345    /// let canonical = simplifier.simplify(expr.clone()).unwrap();
346    /// // Expression has been rewritten to: (c = a AND b = 1)
347    /// assert_eq!(canonical, col("c").eq(col("a")).and(col("b").eq(lit(1))));
348    ///
349    /// // If canonicalization is disabled, the expression is not changed
350    /// let non_canonicalized = simplifier
351    ///     .with_canonicalize(false)
352    ///     .simplify(expr.clone())
353    ///     .unwrap();
354    ///
355    /// assert_eq!(non_canonicalized, expr);
356    /// ```
357    pub fn with_canonicalize(mut self, canonicalize: bool) -> Self {
358        self.canonicalize = canonicalize;
359        self
360    }
361
362    /// Specifies the maximum number of simplification cycles to run.
363    ///
364    /// The simplifier can perform multiple passes of simplification. This is
365    /// because the output of one simplification step can allow more optimizations
366    /// in another simplification step. For example, constant evaluation can allow more
367    /// expression simplifications, and expression simplifications can allow more constant
368    /// evaluations.
369    ///
370    /// This method specifies the maximum number of allowed iteration cycles before the simplifier
371    /// returns an [Expr] output. However, it does not always perform the maximum number of cycles.
372    /// The simplifier will attempt to detect when an [Expr] is unchanged by all the simplification
373    /// passes, and return early. This avoids wasting time on unnecessary [Expr] tree traversals.
374    ///
375    /// If no maximum is specified, the value of [DEFAULT_MAX_SIMPLIFIER_CYCLES] is used
376    /// instead.
377    ///
378    /// ```rust
379    /// use arrow::datatypes::{DataType, Field, Schema};
380    /// use datafusion_expr::{col, lit, Expr};
381    /// use datafusion_common::{Result, ScalarValue, ToDFSchema};
382    /// use datafusion_expr::simplify::SimplifyContext;
383    /// use datafusion_optimizer::simplify_expressions::ExprSimplifier;
384    ///
385    /// let schema = Schema::new(vec![
386    ///   Field::new("a", DataType::Int64, false),
387    ///   ])
388    ///   .to_dfschema_ref().unwrap();
389    ///
390    /// // Create the simplifier
391    /// let context = SimplifyContext::builder().with_schema(schema).build();
392    /// let simplifier = ExprSimplifier::new(context);
393    ///
394    /// // Expression: a IS NOT NULL
395    /// let expr = col("a").is_not_null();
396    ///
397    /// // When using default maximum cycles, 2 cycles will be performed.
398    /// let (simplified_expr, count) = simplifier.simplify_with_cycle_count_transformed(expr.clone()).unwrap();
399    /// assert_eq!(simplified_expr.data, lit(true));
400    /// // 2 cycles were executed, but only 1 was needed
401    /// assert_eq!(count, 2);
402    ///
403    /// // Only 1 simplification pass is necessary here, so we can set the maximum cycles to 1.
404    /// let (simplified_expr, count) = simplifier.with_max_cycles(1).simplify_with_cycle_count_transformed(expr.clone()).unwrap();
405    /// // Expression has been rewritten to: (c = a AND b = 1)
406    /// assert_eq!(simplified_expr.data, lit(true));
407    /// // Only 1 cycle was executed
408    /// assert_eq!(count, 1);
409    /// ```
410    pub fn with_max_cycles(mut self, max_simplifier_cycles: u32) -> Self {
411        self.max_simplifier_cycles = max_simplifier_cycles;
412        self
413    }
414}
415
416/// Canonicalize any BinaryExprs that are not in canonical form
417///
418/// `<literal> <op> <col>` is rewritten to `<col> <op> <literal>`
419///
420/// `<col1> <op> <col2>` is rewritten so that the name of `col1` sorts higher
421/// than `col2` (`a > b` would be canonicalized to `b < a`)
422struct Canonicalizer {}
423
424impl Canonicalizer {
425    fn new() -> Self {
426        Self {}
427    }
428}
429
430impl TreeNodeRewriter for Canonicalizer {
431    type Node = Expr;
432
433    fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
434        let Expr::BinaryExpr(BinaryExpr { left, op, right }) = expr else {
435            return Ok(Transformed::no(expr));
436        };
437        match (left.as_ref(), right.as_ref(), op.swap()) {
438            // <col1> <op> <col2>
439            (Expr::Column(left_col), Expr::Column(right_col), Some(swapped_op))
440                if right_col > left_col =>
441            {
442                Ok(Transformed::yes(Expr::BinaryExpr(BinaryExpr {
443                    left: right,
444                    op: swapped_op,
445                    right: left,
446                })))
447            }
448            // <literal> <op> <col>
449            (Expr::Literal(_a, _), Expr::Column(_b), Some(swapped_op)) => {
450                Ok(Transformed::yes(Expr::BinaryExpr(BinaryExpr {
451                    left: right,
452                    op: swapped_op,
453                    right: left,
454                })))
455            }
456            _ => Ok(Transformed::no(Expr::BinaryExpr(BinaryExpr {
457                left,
458                op,
459                right,
460            }))),
461        }
462    }
463}
464
465/// Partially evaluate `Expr`s so constant subtrees are evaluated at plan time.
466///
467/// Note it does not handle algebraic rewrites such as `(a or false)`
468/// --> `a`, which is handled by [`Simplifier`]
469struct ConstEvaluator {
470    /// `can_evaluate` is used during the depth-first-search of the
471    /// `Expr` tree to track if any siblings (or their descendants) were
472    /// non evaluatable (e.g. had a column reference or volatile
473    /// function)
474    ///
475    /// Specifically, `can_evaluate[N]` represents the state of
476    /// traversal when we are N levels deep in the tree, one entry for
477    /// this Expr and each of its parents.
478    ///
479    /// After visiting all siblings if `can_evaluate.top()` is true, that
480    /// means there were no non evaluatable siblings (or their
481    /// descendants) so this `Expr` can be evaluated
482    can_evaluate: Vec<bool>,
483    /// Execution properties needed to call [`create_physical_expr`].
484    /// `ConstEvaluator` only evaluates expressions without column references
485    /// (i.e. constant expressions) and doesn't use the variable binding features
486    /// of `ExecutionProps` (we explicitly filter out [`Expr::ScalarVariable`]).
487    /// The `config_options` are passed from the session to allow scalar functions
488    /// to access configuration like timezone.
489    execution_props: ExecutionProps,
490}
491
492/// The simplify result of ConstEvaluator
493enum ConstSimplifyResult {
494    // Expr was simplified and contains the new expression
495    Simplified(ScalarValue, Option<FieldMetadata>),
496    // Expr was not simplified and original value is returned
497    NotSimplified(ScalarValue, Option<FieldMetadata>),
498    // Evaluation encountered an error, contains the original expression
499    SimplifyRuntimeError(DataFusionError, Expr),
500    // Evaluation was deliberately deferred to runtime
501    Deferred(Expr),
502}
503
504impl TreeNodeRewriter for ConstEvaluator {
505    type Node = Expr;
506
507    fn f_down(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
508        // Default to being able to evaluate this node
509        self.can_evaluate.push(true);
510
511        // if this expr is not ok to evaluate, mark entire parent
512        // stack as not ok (as all parents have at least one child or
513        // descendant that can not be evaluated
514
515        if !Self::can_evaluate(&expr) {
516            // walk back up stack, marking first parent that is not mutable
517            let parent_iter = self.can_evaluate.iter_mut().rev();
518            for p in parent_iter {
519                if !*p {
520                    // optimization: if we find an element on the
521                    // stack already marked, know all elements above are also marked
522                    break;
523                }
524                *p = false;
525            }
526        }
527
528        // NB: do not short circuit recursion even if we find a non
529        // evaluatable node (so we can fold other children, args to
530        // functions, etc.)
531        Ok(Transformed::no(expr))
532    }
533
534    fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
535        match self.can_evaluate.pop() {
536            // Certain expressions such as `CASE` and `COALESCE` are short-circuiting
537            // and may not evaluate all their sub expressions. Thus, if
538            // any error is countered during simplification, return the original
539            // so that normal evaluation can occur
540            Some(true) => match self.evaluate_to_scalar(expr) {
541                ConstSimplifyResult::Simplified(s, m) => {
542                    Ok(Transformed::yes(Expr::Literal(s, m)))
543                }
544                ConstSimplifyResult::NotSimplified(s, m) => {
545                    Ok(Transformed::no(Expr::Literal(s, m)))
546                }
547                ConstSimplifyResult::SimplifyRuntimeError(err, expr) => {
548                    // For CAST expressions with literal inputs, propagate the error at plan time rather than deferring to execution time.
549                    // This provides clearer error messages and fails fast.
550                    if let Expr::Cast(Cast { ref expr, .. })
551                    | Expr::TryCast(TryCast { ref expr, .. }) = expr
552                        && matches!(expr.as_ref(), Expr::Literal(_, _))
553                    {
554                        return Err(err);
555                    }
556                    // For other expressions (like CASE, COALESCE), preserve the original
557                    // to allow short-circuit evaluation at execution time
558                    Ok(Transformed::yes(expr))
559                }
560                ConstSimplifyResult::Deferred(expr) => {
561                    // Prevent an evaluatable parent (for example, an Alias)
562                    // from evaluating this deferred subtree indirectly.
563                    self.can_evaluate.iter_mut().for_each(|can_evaluate| {
564                        *can_evaluate = false;
565                    });
566                    Ok(Transformed::no(expr))
567                }
568            },
569            Some(false) => Ok(Transformed::no(expr)),
570            _ => internal_err!("Failed to pop can_evaluate"),
571        }
572    }
573}
574
575static DUMMY_SCHEMA: LazyLock<Arc<Schema>> =
576    LazyLock::new(|| Arc::new(Schema::new(vec![Field::new(".", DataType::Null, true)])));
577
578static DUMMY_DF_SCHEMA: LazyLock<DFSchema> =
579    LazyLock::new(|| DFSchema::try_from(Arc::clone(&*DUMMY_SCHEMA)).unwrap());
580
581static DUMMY_BATCH: LazyLock<RecordBatch> = LazyLock::new(|| {
582    // Need a single "input" row to produce a single output row
583    let col = new_null_array(&DataType::Null, 1);
584    RecordBatch::try_new(DUMMY_SCHEMA.clone(), vec![col]).unwrap()
585});
586
587impl ConstEvaluator {
588    /// Create a new `ConstantEvaluator`.
589    ///
590    /// Note: `ConstEvaluator` filters out expressions with scalar variables
591    /// (like `$var`) and volatile functions, so it creates its own default
592    /// `ExecutionProps` internally. The filtered expressions will be evaluated
593    /// at runtime where proper variable bindings are available.
594    ///
595    /// The `config_options` parameter is used to pass session configuration
596    /// (like timezone) to scalar functions during constant evaluation.
597    pub fn try_new(config_options: Option<Arc<ConfigOptions>>) -> Result<Self> {
598        // The dummy column name is unused and doesn't matter as only
599        // expressions without column references can be evaluated
600
601        let mut execution_props = ExecutionProps::new();
602        execution_props.config_options = config_options;
603
604        Ok(Self {
605            can_evaluate: vec![],
606            execution_props,
607        })
608    }
609
610    /// Can a function of the specified volatility be evaluated?
611    fn volatility_ok(volatility: Volatility) -> bool {
612        match volatility {
613            Volatility::Immutable => true,
614            // Values for functions such as now() are taken from ExecutionProps
615            Volatility::Stable => true,
616            Volatility::Volatile => false,
617        }
618    }
619
620    /// Can the expression be evaluated at plan time, (assuming all of
621    /// its children can also be evaluated)?
622    fn can_evaluate(expr: &Expr) -> bool {
623        // check for reasons we can't evaluate this node
624        //
625        // NOTE all expr types are listed here so when new ones are
626        // added they can be checked for their ability to be evaluated
627        // at plan time
628        match expr {
629            // TODO: remove the next line after `Expr::Wildcard` is removed
630            #[expect(deprecated)]
631            Expr::AggregateFunction { .. }
632            | Expr::ScalarVariable(_, _)
633            | Expr::Column(_)
634            | Expr::OuterReferenceColumn(_, _)
635            | Expr::Exists { .. }
636            | Expr::InSubquery(_)
637            | Expr::SetComparison(_)
638            | Expr::ScalarSubquery(_)
639            | Expr::WindowFunction { .. }
640            | Expr::GroupingSet(_)
641            | Expr::Wildcard { .. }
642            | Expr::Placeholder(_) => false,
643            Expr::ScalarFunction(ScalarFunction { func, .. }) => {
644                Self::volatility_ok(func.signature().volatility)
645            }
646            Expr::HigherOrderFunction(HigherOrderFunction { func, .. }) => {
647                Self::volatility_ok(func.signature().volatility)
648            }
649            Expr::Cast(Cast { expr, field }) | Expr::TryCast(TryCast { expr, field }) => {
650                if let (
651                    Ok(DataType::Struct(source_fields)),
652                    DataType::Struct(target_fields),
653                ) = (expr.get_type(&DFSchema::empty()), field.data_type())
654                {
655                    // Don't const-fold struct casts with different field counts
656                    if source_fields.len() != target_fields.len() {
657                        return false;
658                    }
659
660                    // Skip const-folding when there is no field name overlap
661                    if !has_one_of_more_common_fields(&source_fields, target_fields) {
662                        return false;
663                    }
664
665                    // Don't const-fold struct casts with empty (0-row) literals
666                    // The simplifier uses a 1-row input batch, which causes dimension mismatches
667                    // when evaluating 0-row struct literals
668                    if let Expr::Literal(ScalarValue::Struct(struct_array), _) =
669                        expr.as_ref()
670                        && struct_array.len() == 0
671                    {
672                        return false;
673                    }
674                }
675                true
676            }
677            Expr::Literal(_, _)
678            | Expr::Alias(..)
679            | Expr::Unnest(_)
680            | Expr::BinaryExpr { .. }
681            | Expr::Not(_)
682            | Expr::IsNotNull(_)
683            | Expr::IsNull(_)
684            | Expr::IsTrue(_)
685            | Expr::IsFalse(_)
686            | Expr::IsUnknown(_)
687            | Expr::IsNotTrue(_)
688            | Expr::IsNotFalse(_)
689            | Expr::IsNotUnknown(_)
690            | Expr::Negative(_)
691            | Expr::Between { .. }
692            | Expr::Like { .. }
693            | Expr::SimilarTo { .. }
694            | Expr::Case(_)
695            | Expr::InList { .. }
696            | Expr::Lambda(_)
697            | Expr::LambdaVariable(_) => true,
698        }
699    }
700
701    /// Internal helper to evaluates an Expr
702    pub(crate) fn evaluate_to_scalar(&mut self, expr: Expr) -> ConstSimplifyResult {
703        if let Expr::Literal(s, m) = expr {
704            return ConstSimplifyResult::NotSimplified(s, m);
705        }
706
707        if !should_evaluate_const_expr(&expr) {
708            return ConstSimplifyResult::Deferred(expr);
709        }
710
711        let phys_expr = match create_physical_expr(
712            &expr,
713            &DUMMY_DF_SCHEMA,
714            &self.execution_props,
715            &PhysicalPlanningContext::default(),
716        ) {
717            Ok(e) => e,
718            Err(err) => return ConstSimplifyResult::SimplifyRuntimeError(err, expr),
719        };
720        let metadata = phys_expr
721            .return_field(DUMMY_BATCH.schema_ref())
722            .ok()
723            .and_then(|f| {
724                let m = f.metadata();
725                match m.is_empty() {
726                    true => None,
727                    false => Some(FieldMetadata::from(m)),
728                }
729            });
730        let col_val = match phys_expr.evaluate(&DUMMY_BATCH) {
731            Ok(v) => v,
732            Err(err) => return ConstSimplifyResult::SimplifyRuntimeError(err, expr),
733        };
734        match col_val {
735            ColumnarValue::Array(a) => {
736                if a.len() != 1 {
737                    ConstSimplifyResult::SimplifyRuntimeError(
738                        exec_datafusion_err!(
739                            "Could not evaluate the expression, found a result of length {}",
740                            a.len()
741                        ),
742                        expr,
743                    )
744                } else if as_list_array(&a).is_ok() {
745                    ConstSimplifyResult::Simplified(
746                        ScalarValue::List(a.as_list::<i32>().to_owned().into()),
747                        metadata,
748                    )
749                } else if as_large_list_array(&a).is_ok() {
750                    ConstSimplifyResult::Simplified(
751                        ScalarValue::LargeList(a.as_list::<i64>().to_owned().into()),
752                        metadata,
753                    )
754                } else {
755                    // Non-ListArray
756                    match ScalarValue::try_from_array(&a, 0) {
757                        Ok(s) => ConstSimplifyResult::Simplified(s, metadata),
758                        Err(err) => ConstSimplifyResult::SimplifyRuntimeError(err, expr),
759                    }
760                }
761            }
762            ColumnarValue::Scalar(s) => ConstSimplifyResult::Simplified(s, metadata),
763        }
764    }
765}
766
767fn should_evaluate_const_expr(expr: &Expr) -> bool {
768    match expr {
769        Expr::ScalarFunction(ScalarFunction { func, args }) => {
770            let Some(args) = args
771                .iter()
772                .map(|arg| match arg {
773                    Expr::Literal(value, _) => Some(value),
774                    _ => None,
775                })
776                .collect::<Option<Vec<_>>>()
777            else {
778                return true;
779            };
780            func.should_evaluate_const(&args)
781        }
782        Expr::BinaryExpr(BinaryExpr { op, right, .. })
783            if matches!(
784                op,
785                Operator::RegexMatch
786                    | Operator::RegexNotMatch
787                    | Operator::RegexIMatch
788                    | Operator::RegexNotIMatch
789            ) =>
790        {
791            regex_is_within_planning_budget(op, right)
792        }
793        _ => true,
794    }
795}
796
797fn regex_is_within_planning_budget(op: &Operator, pattern: &Expr) -> bool {
798    let Expr::Literal(pattern, _) = pattern else {
799        return true;
800    };
801    let Some(pattern) = pattern.try_as_str().flatten() else {
802        return true;
803    };
804    let mut builder = RegexBuilder::new(pattern);
805    builder.size_limit(REGEX_PLANNING_SIZE_LIMIT_BYTES);
806    if matches!(op, Operator::RegexIMatch | Operator::RegexNotIMatch) {
807        builder.case_insensitive(true);
808    }
809    !matches!(builder.build(), Err(RegexError::CompiledTooBig(_)))
810}
811
812/// Simplifies [`Expr`]s by applying algebraic transformation rules
813///
814/// Example transformations that are applied:
815/// * `expr = true` and `expr != false` to `expr` when `expr` is of boolean type
816/// * `expr = false` and `expr != true` to `!expr` when `expr` is of boolean type
817/// * `true = true` and `false = false` to `true`
818/// * `false = true` and `true = false` to `false`
819/// * `!!expr` to `expr`
820/// * `expr = null` and `expr != null` to `null`
821struct Simplifier<'a> {
822    info: &'a SimplifyContext,
823}
824
825impl<'a> Simplifier<'a> {
826    pub fn new(info: &'a SimplifyContext) -> Self {
827        Self { info }
828    }
829}
830
831/// Returns whether values of the given type are guaranteed to satisfy `value % 1 == 0`.
832fn modulo_one_is_zero_type(data_type: &DataType) -> bool {
833    match data_type {
834        DataType::Int8
835        | DataType::Int16
836        | DataType::Int32
837        | DataType::Int64
838        | DataType::UInt8
839        | DataType::UInt16
840        | DataType::UInt32
841        | DataType::UInt64 => true,
842        // A non-positive scale makes every decimal value an integer.
843        DataType::Decimal32(_, scale)
844        | DataType::Decimal64(_, scale)
845        | DataType::Decimal128(_, scale)
846        | DataType::Decimal256(_, scale) => *scale <= 0,
847        _ => false,
848    }
849}
850
851impl TreeNodeRewriter for Simplifier<'_> {
852    type Node = Expr;
853
854    /// rewrite the expression simplifying any constant expressions
855    fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
856        use datafusion_expr::Operator::{
857            And, BitwiseAnd, BitwiseOr, BitwiseShiftLeft, BitwiseShiftRight, BitwiseXor,
858            Divide, Eq, Modulo, Multiply, NotEq, Or, RegexIMatch, RegexMatch,
859            RegexNotIMatch, RegexNotMatch,
860        };
861
862        let info = self.info;
863        Ok(match expr {
864            // `value op NULL` -> `NULL`
865            // `NULL op value` -> `NULL`
866            // except for few operators that can return non-null value even when one of the operands is NULL
867            ref expr @ Expr::BinaryExpr(BinaryExpr {
868                ref left,
869                ref op,
870                ref right,
871            }) if op.returns_null_on_null()
872                && (is_null(left.as_ref()) || is_null(right.as_ref())) =>
873            {
874                Transformed::yes(Expr::Literal(
875                    ScalarValue::try_new_null(&info.get_data_type(expr)?)?,
876                    None,
877                ))
878            }
879
880            // `NULL {AND, OR} NULL` -> `NULL`
881            Expr::BinaryExpr(BinaryExpr {
882                left,
883                op: And | Or,
884                right,
885            }) if is_null(&left) && is_null(&right) => Transformed::yes(lit_bool_null()),
886
887            //
888            // Rules for Eq
889            //
890
891            // true = A  --> A
892            // false = A --> !A
893            // null = A --> null
894            Expr::BinaryExpr(BinaryExpr {
895                left,
896                op: Eq,
897                right,
898            }) if is_bool_lit(&left) && info.is_boolean_type(&right)? => {
899                Transformed::yes(match as_bool_lit(&left)? {
900                    Some(true) => *right,
901                    Some(false) => Expr::Not(right),
902                    None => lit_bool_null(),
903                })
904            }
905            // A = true  --> A
906            // A = false --> !A
907            // A = null --> null
908            Expr::BinaryExpr(BinaryExpr {
909                left,
910                op: Eq,
911                right,
912            }) if is_bool_lit(&right) && info.is_boolean_type(&left)? => {
913                Transformed::yes(match as_bool_lit(&right)? {
914                    Some(true) => *left,
915                    Some(false) => Expr::Not(left),
916                    None => lit_bool_null(),
917                })
918            }
919            // According to SQL's null semantics, NULL = NULL evaluates to NULL
920            // Both sides are the same expression (A = A) and A is non-volatile expression
921            // A = A --> A IS NOT NULL OR NULL
922            // A = A --> true (if A not nullable)
923            Expr::BinaryExpr(BinaryExpr {
924                left,
925                op: Eq,
926                right,
927            }) if (left == right) & !left.is_volatile() => {
928                Transformed::yes(match !info.nullable(&left)? {
929                    true => lit(true),
930                    false => Expr::BinaryExpr(BinaryExpr {
931                        left: Box::new(Expr::IsNotNull(left)),
932                        op: Or,
933                        right: Box::new(lit_bool_null()),
934                    }),
935                })
936            }
937
938            // Rules for NotEq
939            //
940
941            // true != A  --> !A
942            // false != A --> A
943            // null != A --> null
944            Expr::BinaryExpr(BinaryExpr {
945                left,
946                op: NotEq,
947                right,
948            }) if is_bool_lit(&left) && info.is_boolean_type(&right)? => {
949                Transformed::yes(match as_bool_lit(&left)? {
950                    Some(true) => Expr::Not(right),
951                    Some(false) => *right,
952                    None => lit_bool_null(),
953                })
954            }
955            // A != true  --> !A
956            // A != false --> A
957            // A != null --> null,
958            Expr::BinaryExpr(BinaryExpr {
959                left,
960                op: NotEq,
961                right,
962            }) if is_bool_lit(&right) && info.is_boolean_type(&left)? => {
963                Transformed::yes(match as_bool_lit(&right)? {
964                    Some(true) => Expr::Not(left),
965                    Some(false) => *left,
966                    None => lit_bool_null(),
967                })
968            }
969
970            //
971            // Rules for OR
972            //
973
974            // true OR A --> true (even if A is null)
975            Expr::BinaryExpr(BinaryExpr {
976                left,
977                op: Or,
978                right: _,
979            }) if is_true(&left) => Transformed::yes(*left),
980            // false OR A --> A
981            Expr::BinaryExpr(BinaryExpr {
982                left,
983                op: Or,
984                right,
985            }) if is_false(&left) => Transformed::yes(*right),
986            // A OR true --> true (even if A is null)
987            Expr::BinaryExpr(BinaryExpr {
988                left: _,
989                op: Or,
990                right,
991            }) if is_true(&right) => Transformed::yes(*right),
992            // A OR false --> A
993            Expr::BinaryExpr(BinaryExpr {
994                left,
995                op: Or,
996                right,
997            }) if is_false(&right) => Transformed::yes(*left),
998            // A OR !A ---> true (if A not nullable)
999            Expr::BinaryExpr(BinaryExpr {
1000                left,
1001                op: Or,
1002                right,
1003            }) if is_not_of(&right, &left) && !info.nullable(&left)? => {
1004                Transformed::yes(lit(true))
1005            }
1006            // !A OR A ---> true (if A not nullable)
1007            Expr::BinaryExpr(BinaryExpr {
1008                left,
1009                op: Or,
1010                right,
1011            }) if is_not_of(&left, &right) && !info.nullable(&right)? => {
1012                Transformed::yes(lit(true))
1013            }
1014            // (..A..) OR A --> (..A..)
1015            Expr::BinaryExpr(BinaryExpr {
1016                left,
1017                op: Or,
1018                right,
1019            }) if expr_contains(&left, &right, Or) => Transformed::yes(*left),
1020            // A OR (..A..) --> (..A..)
1021            Expr::BinaryExpr(BinaryExpr {
1022                left,
1023                op: Or,
1024                right,
1025            }) if expr_contains(&right, &left, Or) => Transformed::yes(*right),
1026            // A OR (A AND B) --> A
1027            Expr::BinaryExpr(BinaryExpr {
1028                left,
1029                op: Or,
1030                right,
1031            }) if is_op_with(And, &right, &left) => Transformed::yes(*left),
1032            // (A AND B) OR A --> A
1033            Expr::BinaryExpr(BinaryExpr {
1034                left,
1035                op: Or,
1036                right,
1037            }) if is_op_with(And, &left, &right) => Transformed::yes(*right),
1038            // Eliminate common factors in conjunctions e.g
1039            // (A AND B) OR (A AND C) -> A AND (B OR C)
1040            Expr::BinaryExpr(BinaryExpr {
1041                left,
1042                op: Or,
1043                right,
1044            }) if has_common_conjunction(&left, &right) => {
1045                let lhs: IndexSet<Expr> = iter_conjunction_owned(*left).collect();
1046                let (common, rhs): (Vec<_>, Vec<_>) = iter_conjunction_owned(*right)
1047                    .partition(|e| lhs.contains(e) && !e.is_volatile());
1048
1049                let new_rhs = rhs.into_iter().reduce(and);
1050                let new_lhs = lhs.into_iter().filter(|e| !common.contains(e)).reduce(and);
1051                let common_conjunction = common.into_iter().reduce(and).unwrap();
1052
1053                let new_expr = match (new_lhs, new_rhs) {
1054                    (Some(lhs), Some(rhs)) => and(common_conjunction, or(lhs, rhs)),
1055                    (_, _) => common_conjunction,
1056                };
1057                Transformed::yes(new_expr)
1058            }
1059
1060            //
1061            // Rules for AND
1062            //
1063
1064            // true AND A --> A
1065            Expr::BinaryExpr(BinaryExpr {
1066                left,
1067                op: And,
1068                right,
1069            }) if is_true(&left) => Transformed::yes(*right),
1070            // false AND A --> false (even if A is null)
1071            Expr::BinaryExpr(BinaryExpr {
1072                left,
1073                op: And,
1074                right: _,
1075            }) if is_false(&left) => Transformed::yes(*left),
1076            // A AND true --> A
1077            Expr::BinaryExpr(BinaryExpr {
1078                left,
1079                op: And,
1080                right,
1081            }) if is_true(&right) => Transformed::yes(*left),
1082            // A AND false --> false (even if A is null)
1083            Expr::BinaryExpr(BinaryExpr {
1084                left: _,
1085                op: And,
1086                right,
1087            }) if is_false(&right) => Transformed::yes(*right),
1088            // A AND !A ---> false (if A not nullable)
1089            Expr::BinaryExpr(BinaryExpr {
1090                left,
1091                op: And,
1092                right,
1093            }) if is_not_of(&right, &left) && !info.nullable(&left)? => {
1094                Transformed::yes(lit(false))
1095            }
1096            // !A AND A ---> false (if A not nullable)
1097            Expr::BinaryExpr(BinaryExpr {
1098                left,
1099                op: And,
1100                right,
1101            }) if is_not_of(&left, &right) && !info.nullable(&right)? => {
1102                Transformed::yes(lit(false))
1103            }
1104            // (..A..) AND A --> (..A..)
1105            Expr::BinaryExpr(BinaryExpr {
1106                left,
1107                op: And,
1108                right,
1109            }) if expr_contains(&left, &right, And) => Transformed::yes(*left),
1110            // A AND (..A..) --> (..A..)
1111            Expr::BinaryExpr(BinaryExpr {
1112                left,
1113                op: And,
1114                right,
1115            }) if expr_contains(&right, &left, And) => Transformed::yes(*right),
1116            // A AND (A OR B) --> A
1117            Expr::BinaryExpr(BinaryExpr {
1118                left,
1119                op: And,
1120                right,
1121            }) if is_op_with(Or, &right, &left) => Transformed::yes(*left),
1122            // (A OR B) AND A --> A
1123            Expr::BinaryExpr(BinaryExpr {
1124                left,
1125                op: And,
1126                right,
1127            }) if is_op_with(Or, &left, &right) => Transformed::yes(*right),
1128            // A >= constant AND constant <= A --> A = constant
1129            Expr::BinaryExpr(BinaryExpr {
1130                left,
1131                op: And,
1132                right,
1133            }) if can_reduce_to_equal_statement(&left, &right) => {
1134                if let Expr::BinaryExpr(BinaryExpr {
1135                    left: left_left,
1136                    right: left_right,
1137                    ..
1138                }) = *left
1139                {
1140                    Transformed::yes(Expr::BinaryExpr(BinaryExpr {
1141                        left: left_left,
1142                        op: Eq,
1143                        right: left_right,
1144                    }))
1145                } else {
1146                    return internal_err!(
1147                        "can_reduce_to_equal_statement should only be called with a BinaryExpr"
1148                    );
1149                }
1150            }
1151            // A = L1 AND A != L2 --> A = L1 (when L1 != L2)
1152            Expr::BinaryExpr(BinaryExpr {
1153                left,
1154                op: And,
1155                right,
1156            }) if is_eq_and_ne_with_different_literal(&left, &right) => {
1157                Transformed::yes(*left)
1158            }
1159            // A != L2 AND A = L1 --> A = L1 (when L1 != L2)
1160            Expr::BinaryExpr(BinaryExpr {
1161                left,
1162                op: And,
1163                right,
1164            }) if is_eq_and_ne_with_different_literal(&right, &left) => {
1165                Transformed::yes(*right)
1166            }
1167
1168            //
1169            // Rules for Multiply
1170            //
1171
1172            // A * 1 --> A (with type coercion if needed)
1173            Expr::BinaryExpr(BinaryExpr {
1174                left,
1175                op: Multiply,
1176                right,
1177            }) if is_one(&right) => {
1178                simplify_right_is_one_case(info, left, &Multiply, &right)?
1179            }
1180            // 1 * A --> A
1181            Expr::BinaryExpr(BinaryExpr {
1182                left,
1183                op: Multiply,
1184                right,
1185            }) if is_one(&left) => {
1186                // 1 * A is equivalent to A * 1
1187                simplify_right_is_one_case(info, right, &Multiply, &left)?
1188            }
1189
1190            // A * 0 --> 0 (if A is not null and not floating, since NAN * 0 -> NAN)
1191            Expr::BinaryExpr(BinaryExpr {
1192                left,
1193                op: Multiply,
1194                right,
1195            }) if !info.nullable(&left)?
1196                && !info.get_data_type(&left)?.is_floating()
1197                && is_zero(&right) =>
1198            {
1199                Transformed::yes(*right)
1200            }
1201            // 0 * A --> 0 (if A is not null and not floating, since 0 * NAN -> NAN)
1202            Expr::BinaryExpr(BinaryExpr {
1203                left,
1204                op: Multiply,
1205                right,
1206            }) if !info.nullable(&right)?
1207                && !info.get_data_type(&right)?.is_floating()
1208                && is_zero(&left) =>
1209            {
1210                Transformed::yes(*left)
1211            }
1212
1213            //
1214            // Rules for Divide
1215            //
1216
1217            // A / 1 --> A
1218            Expr::BinaryExpr(BinaryExpr {
1219                left,
1220                op: Divide,
1221                right,
1222            }) if is_one(&right) => {
1223                simplify_right_is_one_case(info, left, &Divide, &right)?
1224            }
1225
1226            //
1227            // Rules for Modulo
1228            //
1229
1230            // A % 1 --> 0 (if A is non-null and its type guarantees an integer value)
1231            Expr::BinaryExpr(BinaryExpr {
1232                left,
1233                op: Modulo,
1234                right,
1235            }) if !info.nullable(&left)?
1236                && modulo_one_is_zero_type(&info.get_data_type(&left)?)
1237                && is_one(&right) =>
1238            {
1239                Transformed::yes(Expr::Literal(
1240                    ScalarValue::new_zero(&info.get_data_type(&left)?)?,
1241                    None,
1242                ))
1243            }
1244
1245            //
1246            // Rules for BitwiseAnd
1247            //
1248
1249            // A & 0 -> 0 (if A not nullable)
1250            Expr::BinaryExpr(BinaryExpr {
1251                left,
1252                op: BitwiseAnd,
1253                right,
1254            }) if !info.nullable(&left)? && is_zero(&right) => Transformed::yes(*right),
1255
1256            // 0 & A -> 0 (if A not nullable)
1257            Expr::BinaryExpr(BinaryExpr {
1258                left,
1259                op: BitwiseAnd,
1260                right,
1261            }) if !info.nullable(&right)? && is_zero(&left) => Transformed::yes(*left),
1262
1263            // (..A..) & A --> (..A..)
1264            Expr::BinaryExpr(BinaryExpr {
1265                left,
1266                op: BitwiseAnd,
1267                right,
1268            }) if expr_contains(&left, &right, BitwiseAnd) => Transformed::yes(*left),
1269
1270            // A & (..A..) --> (..A..)
1271            Expr::BinaryExpr(BinaryExpr {
1272                left,
1273                op: BitwiseAnd,
1274                right,
1275            }) if expr_contains(&right, &left, BitwiseAnd) => Transformed::yes(*right),
1276
1277            // A & (A | B) --> A (if B not null)
1278            Expr::BinaryExpr(BinaryExpr {
1279                left,
1280                op: BitwiseAnd,
1281                right,
1282            }) if !info.nullable(&right)? && is_op_with(BitwiseOr, &right, &left) => {
1283                Transformed::yes(*left)
1284            }
1285
1286            // (A | B) & A --> A (if B not null)
1287            Expr::BinaryExpr(BinaryExpr {
1288                left,
1289                op: BitwiseAnd,
1290                right,
1291            }) if !info.nullable(&left)? && is_op_with(BitwiseOr, &left, &right) => {
1292                Transformed::yes(*right)
1293            }
1294
1295            //
1296            // Rules for BitwiseOr
1297            //
1298
1299            // A | 0 -> A (even if A is null)
1300            Expr::BinaryExpr(BinaryExpr {
1301                left,
1302                op: BitwiseOr,
1303                right,
1304            }) if is_zero(&right) => Transformed::yes(*left),
1305
1306            // 0 | A -> A (even if A is null)
1307            Expr::BinaryExpr(BinaryExpr {
1308                left,
1309                op: BitwiseOr,
1310                right,
1311            }) if is_zero(&left) => Transformed::yes(*right),
1312
1313            // (..A..) | A --> (..A..)
1314            Expr::BinaryExpr(BinaryExpr {
1315                left,
1316                op: BitwiseOr,
1317                right,
1318            }) if expr_contains(&left, &right, BitwiseOr) => Transformed::yes(*left),
1319
1320            // A | (..A..) --> (..A..)
1321            Expr::BinaryExpr(BinaryExpr {
1322                left,
1323                op: BitwiseOr,
1324                right,
1325            }) if expr_contains(&right, &left, BitwiseOr) => Transformed::yes(*right),
1326
1327            // A | (A & B) --> A (if B not null)
1328            Expr::BinaryExpr(BinaryExpr {
1329                left,
1330                op: BitwiseOr,
1331                right,
1332            }) if !info.nullable(&right)? && is_op_with(BitwiseAnd, &right, &left) => {
1333                Transformed::yes(*left)
1334            }
1335
1336            // (A & B) | A --> A (if B not null)
1337            Expr::BinaryExpr(BinaryExpr {
1338                left,
1339                op: BitwiseOr,
1340                right,
1341            }) if !info.nullable(&left)? && is_op_with(BitwiseAnd, &left, &right) => {
1342                Transformed::yes(*right)
1343            }
1344
1345            //
1346            // Rules for BitwiseXor
1347            //
1348
1349            // A ^ 0 -> A (if A not nullable)
1350            Expr::BinaryExpr(BinaryExpr {
1351                left,
1352                op: BitwiseXor,
1353                right,
1354            }) if !info.nullable(&left)? && is_zero(&right) => Transformed::yes(*left),
1355
1356            // 0 ^ A -> A (if A not nullable)
1357            Expr::BinaryExpr(BinaryExpr {
1358                left,
1359                op: BitwiseXor,
1360                right,
1361            }) if !info.nullable(&right)? && is_zero(&left) => Transformed::yes(*right),
1362
1363            // (..A..) ^ A --> (the expression without A, if number of A is odd, otherwise one A)
1364            Expr::BinaryExpr(BinaryExpr {
1365                left,
1366                op: BitwiseXor,
1367                right,
1368            }) if !info.nullable(&right)? && expr_contains(&left, &right, BitwiseXor) => {
1369                let expr = delete_xor_in_complex_expr(&left, &right, false);
1370                Transformed::yes(if expr == *right {
1371                    Expr::Literal(
1372                        ScalarValue::new_zero(&info.get_data_type(&right)?)?,
1373                        None,
1374                    )
1375                } else {
1376                    expr
1377                })
1378            }
1379
1380            // A ^ (..A..) --> (the expression without A, if number of A is odd, otherwise one A)
1381            Expr::BinaryExpr(BinaryExpr {
1382                left,
1383                op: BitwiseXor,
1384                right,
1385            }) if !info.nullable(&left)? && expr_contains(&right, &left, BitwiseXor) => {
1386                let expr = delete_xor_in_complex_expr(&right, &left, true);
1387                Transformed::yes(if expr == *left {
1388                    Expr::Literal(
1389                        ScalarValue::new_zero(&info.get_data_type(&left)?)?,
1390                        None,
1391                    )
1392                } else {
1393                    expr
1394                })
1395            }
1396
1397            //
1398            // Rules for BitwiseShiftRight
1399            //
1400
1401            // A >> 0 -> A (even if A is null)
1402            Expr::BinaryExpr(BinaryExpr {
1403                left,
1404                op: BitwiseShiftRight,
1405                right,
1406            }) if is_zero(&right) => Transformed::yes(*left),
1407
1408            //
1409            // Rules for BitwiseShiftRight
1410            //
1411
1412            // A << 0 -> A (even if A is null)
1413            Expr::BinaryExpr(BinaryExpr {
1414                left,
1415                op: BitwiseShiftLeft,
1416                right,
1417            }) if is_zero(&right) => Transformed::yes(*left),
1418
1419            //
1420            // Rules for Not
1421            //
1422            Expr::Not(inner) => Transformed::yes(negate_clause(*inner)),
1423
1424            //
1425            // Rules for Negative
1426            //
1427            // Preserve the existing double-negation simplification without
1428            // applying bitwise-complement identities to arithmetic negation.
1429            Expr::Negative(inner) => match *inner {
1430                Expr::Negative(inner) => Transformed::yes(*inner),
1431                inner => Transformed::no(Expr::Negative(Box::new(inner))),
1432            },
1433
1434            //
1435            // Rules for Case
1436            //
1437
1438            // Inline a comparison to a literal with the case statement into the `THEN` clauses.
1439            // which can enable further simplifications
1440            // CASE WHEN X THEN "a" WHEN Y THEN "b" ... END = "a" --> CASE WHEN X THEN "a" = "a" WHEN Y THEN "b" = "a" END
1441            Expr::BinaryExpr(BinaryExpr {
1442                left,
1443                op: op @ (Eq | NotEq),
1444                right,
1445            }) if is_case_with_literal_outputs(&left) && is_lit(&right) => {
1446                let case = into_case(*left)?;
1447                Transformed::yes(Expr::Case(Case {
1448                    expr: None,
1449                    when_then_expr: case
1450                        .when_then_expr
1451                        .into_iter()
1452                        .map(|(when, then)| {
1453                            (
1454                                when,
1455                                Box::new(Expr::BinaryExpr(BinaryExpr {
1456                                    left: then,
1457                                    op,
1458                                    right: right.clone(),
1459                                })),
1460                            )
1461                        })
1462                        .collect(),
1463                    else_expr: case.else_expr.map(|els| {
1464                        Box::new(Expr::BinaryExpr(BinaryExpr {
1465                            left: els,
1466                            op,
1467                            right,
1468                        }))
1469                    }),
1470                }))
1471            }
1472
1473            // CASE WHEN true THEN A ... END --> A
1474            // CASE WHEN X THEN A WHEN TRUE THEN B ... END --> CASE WHEN X THEN A ELSE B END
1475            // CASE WHEN false THEN A END --> NULL
1476            // CASE WHEN false THEN A ELSE B END --> B
1477            // CASE WHEN X THEN A WHEN false THEN B END --> CASE WHEN X THEN A ELSE B END
1478            Expr::Case(Case {
1479                expr: None,
1480                when_then_expr,
1481                mut else_expr,
1482            }) if when_then_expr
1483                .iter()
1484                .any(|(when, _)| is_true(when.as_ref()) || is_false(when.as_ref())) =>
1485            {
1486                let out_type = info.get_data_type(&when_then_expr[0].1)?;
1487                let mut new_when_then_expr = Vec::with_capacity(when_then_expr.len());
1488
1489                for (when, then) in when_then_expr.into_iter() {
1490                    if is_true(when.as_ref()) {
1491                        // Skip adding the rest of the when-then expressions after WHEN true
1492                        // CASE WHEN X THEN A WHEN TRUE THEN B ... END --> CASE WHEN X THEN A ELSE B END
1493                        else_expr = Some(then);
1494                        break;
1495                    } else if !is_false(when.as_ref()) {
1496                        new_when_then_expr.push((when, then));
1497                    }
1498                    // else: skip WHEN false cases
1499                }
1500
1501                // Exclude CASE statement altogether if there are no when-then expressions left
1502                if new_when_then_expr.is_empty() {
1503                    // CASE WHEN false THEN A ELSE B END --> B
1504                    if let Some(else_expr) = else_expr {
1505                        return Ok(Transformed::yes(*else_expr));
1506                    // CASE WHEN false THEN A END --> NULL
1507                    } else {
1508                        let null =
1509                            Expr::Literal(ScalarValue::try_new_null(&out_type)?, None);
1510                        return Ok(Transformed::yes(null));
1511                    }
1512                }
1513
1514                Transformed::yes(Expr::Case(Case {
1515                    expr: None,
1516                    when_then_expr: new_when_then_expr,
1517                    else_expr,
1518                }))
1519            }
1520
1521            // CASE
1522            //   WHEN X THEN A
1523            //   WHEN Y THEN B
1524            //   ...
1525            //   ELSE Q
1526            // END
1527            //
1528            // ---> (X AND A) OR (Y AND B AND NOT X) OR ... (NOT (X OR Y) AND Q)
1529            //
1530            // Note: the rationale for this rewrite is that the expr can then be further
1531            // simplified using the existing rules for AND/OR. Unlike CASE, AND/OR
1532            // do not guarantee branch-local evaluation, so only expose columns
1533            // and literals from conditional branches.
1534            Expr::Case(Case {
1535                expr: None,
1536                when_then_expr,
1537                else_expr,
1538            }) if !when_then_expr.is_empty()
1539                // The rewrite is O(n²) in general so limit to small number of when-thens that can be true
1540                && (when_then_expr.len() < 3 // small number of input whens
1541                    // or all thens are literal bools and a small number of them are true
1542                    || (when_then_expr.iter().all(|(_, then)| is_bool_lit(then))
1543                        && when_then_expr.iter().filter(|(_, then)| is_true(then)).count() < 3))
1544                && info.is_boolean_type(&when_then_expr[0].1)?
1545                && can_lower_case_to_boolean(&when_then_expr, else_expr.as_deref()) =>
1546            {
1547                // String disjunction of all the when predicates encountered so far. Not nullable.
1548                let mut filter_expr = lit(false);
1549                // The disjunction of all the cases
1550                let mut out_expr = lit(false);
1551
1552                for (when, then) in when_then_expr {
1553                    let when = is_exactly_true(*when, info)?;
1554                    let case_expr =
1555                        when.clone().and(filter_expr.clone().not()).and(*then);
1556
1557                    out_expr = out_expr.or(case_expr);
1558                    filter_expr = filter_expr.or(when);
1559                }
1560
1561                let else_expr = else_expr.map(|b| *b).unwrap_or_else(lit_bool_null);
1562                let case_expr = filter_expr.not().and(else_expr);
1563                out_expr = out_expr.or(case_expr);
1564
1565                // Do a first pass at simplification
1566                out_expr.rewrite(self)?
1567            }
1568            // CASE
1569            //   WHEN X THEN true
1570            //   WHEN Y THEN true
1571            //   WHEN Z THEN false
1572            //   ...
1573            //   ELSE true
1574            // END
1575            //
1576            // --->
1577            //
1578            // NOT(CASE
1579            //   WHEN X THEN false
1580            //   WHEN Y THEN false
1581            //   WHEN Z THEN true
1582            //   ...
1583            //   ELSE false
1584            // END)
1585            //
1586            // Note: the rationale for this rewrite is that the case can then be further
1587            // simplified into a small number of ANDs and ORs
1588            Expr::Case(Case {
1589                expr: None,
1590                when_then_expr,
1591                else_expr,
1592            }) if !when_then_expr.is_empty()
1593                && when_then_expr
1594                    .iter()
1595                    .all(|(_, then)| is_bool_lit(then)) // all thens are literal bools
1596                // This simplification is only helpful if we end up with a small number of true thens
1597                && when_then_expr
1598                    .iter()
1599                    .filter(|(_, then)| is_false(then))
1600                    .count()
1601                    < 3
1602                && else_expr.as_deref().is_none_or(is_bool_lit)
1603                && can_lower_case_to_boolean(&when_then_expr, else_expr.as_deref()) =>
1604            {
1605                Transformed::yes(
1606                    Expr::Case(Case {
1607                        expr: None,
1608                        when_then_expr: when_then_expr
1609                            .into_iter()
1610                            .map(|(when, then)| (when, Box::new(Expr::Not(then))))
1611                            .collect(),
1612                        else_expr: else_expr
1613                            .map(|else_expr| Box::new(Expr::Not(else_expr))),
1614                    })
1615                    .not(),
1616                )
1617            }
1618            Expr::ScalarFunction(ScalarFunction { func: udf, args }) => {
1619                match udf.simplify(args, info)? {
1620                    ExprSimplifyResult::Original(args) => {
1621                        Transformed::no(Expr::ScalarFunction(ScalarFunction {
1622                            func: udf,
1623                            args,
1624                        }))
1625                    }
1626                    ExprSimplifyResult::Simplified(expr) => Transformed::yes(expr),
1627                }
1628            }
1629
1630            Expr::AggregateFunction(datafusion_expr::expr::AggregateFunction {
1631                ref func,
1632                ..
1633            }) => match (func.simplify(), expr) {
1634                (Some(simplify_function), Expr::AggregateFunction(af)) => {
1635                    Transformed::yes(simplify_function(af, info)?)
1636                }
1637                (_, expr) => Transformed::no(expr),
1638            },
1639
1640            Expr::WindowFunction(ref window_fun) => match (window_fun.simplify(), expr) {
1641                (Some(simplify_function), Expr::WindowFunction(wf)) => {
1642                    Transformed::yes(simplify_function(*wf, info)?)
1643                }
1644                (_, expr) => Transformed::no(expr),
1645            },
1646
1647            //
1648            // Rules for Between
1649            //
1650
1651            // a between 3 and 5  -->  a >= 3 AND a <=5
1652            // a not between 3 and 5  -->  a < 3 OR a > 5
1653            Expr::Between(between) => Transformed::yes(if between.negated {
1654                let l = *between.expr.clone();
1655                let r = *between.expr;
1656                or(l.lt(*between.low), r.gt(*between.high))
1657            } else {
1658                and(
1659                    between.expr.clone().gt_eq(*between.low),
1660                    between.expr.lt_eq(*between.high),
1661                )
1662            }),
1663
1664            //
1665            // Rules for regexes
1666            //
1667            Expr::BinaryExpr(BinaryExpr {
1668                left,
1669                op: op @ (RegexMatch | RegexNotMatch | RegexIMatch | RegexNotIMatch),
1670                right,
1671            }) => {
1672                // Non-constant regexes are not evaluated during planning, so
1673                // avoid adding a compilation preflight to their normal path.
1674                if !matches!(left.as_ref(), Expr::Literal(_, _))
1675                    || regex_is_within_planning_budget(&op, &right)
1676                {
1677                    simplify_regex_expr(left, op, right)?
1678                } else {
1679                    Transformed::no(Expr::BinaryExpr(BinaryExpr { left, op, right }))
1680                }
1681            }
1682
1683            // Rules for Like
1684            Expr::Like(like) => {
1685                // `\` is implicit escape, see https://github.com/apache/datafusion/issues/13291
1686                let escape_char = like.escape_char.unwrap_or('\\');
1687
1688                match StringScalar::try_from_expr(&like.pattern) {
1689                    Some(string_scalar) => {
1690                        let pattern_str = string_scalar.as_str();
1691                        match pattern_str {
1692                            None => return Ok(Transformed::yes(lit_bool_null())),
1693                            Some("%") => {
1694                                // exp LIKE '%' is
1695                                //   - when exp is not NULL, it's true
1696                                //   - when exp is NULL, it's NULL
1697                                // exp NOT LIKE '%' is
1698                                //   - when exp is not NULL, it's false
1699                                //   - when exp is NULL, it's NULL
1700                                let result_for_non_null = lit(!like.negated);
1701                                Transformed::yes(if !info.nullable(&like.expr)? {
1702                                    result_for_non_null
1703                                } else {
1704                                    Expr::Case(Case {
1705                                        expr: Some(Box::new(Expr::IsNotNull(like.expr))),
1706                                        when_then_expr: vec![(
1707                                            Box::new(lit(true)),
1708                                            Box::new(result_for_non_null),
1709                                        )],
1710                                        else_expr: None,
1711                                    })
1712                                })
1713                            }
1714                            Some(pattern_str)
1715                                if pattern_str.contains("%%")
1716                                    && !pattern_str.contains(escape_char) =>
1717                            {
1718                                // Repeated occurrences of wildcard are redundant so remove them
1719                                // exp LIKE '%%'  --> exp LIKE '%'
1720
1721                                static LIKE_REGEX: LazyLock<Regex> =
1722                                    LazyLock::new(|| Regex::new("%%+").unwrap());
1723                                let simplified_pattern =
1724                                    LIKE_REGEX.replace_all(pattern_str, "%").to_string();
1725                                Transformed::yes(Expr::Like(Like {
1726                                    pattern: Box::new(
1727                                        string_scalar.to_expr(&simplified_pattern),
1728                                    ),
1729                                    ..like
1730                                }))
1731                            }
1732                            Some(pattern_str)
1733                                if !like.case_insensitive
1734                                    && !pattern_str
1735                                        .contains(['%', '_', escape_char].as_ref()) =>
1736                            {
1737                                // If the pattern does not contain any wildcards, we can simplify the like expression to an equality expression
1738                                // TODO: handle escape characters
1739                                Transformed::yes(Expr::BinaryExpr(BinaryExpr {
1740                                    left: like.expr.clone(),
1741                                    op: if like.negated { NotEq } else { Eq },
1742                                    right: like.pattern.clone(),
1743                                }))
1744                            }
1745
1746                            Some(_pattern_str) => Transformed::no(Expr::Like(like)),
1747                        }
1748                    }
1749                    None => Transformed::no(Expr::Like(like)),
1750                }
1751            }
1752
1753            // a is not null/unknown --> true (if a is not nullable)
1754            Expr::IsNotNull(expr) | Expr::IsNotUnknown(expr)
1755                if !info.nullable(&expr)? =>
1756            {
1757                Transformed::yes(lit(true))
1758            }
1759
1760            // a is null/unknown --> false (if a is not nullable)
1761            Expr::IsNull(expr) | Expr::IsUnknown(expr) if !info.nullable(&expr)? => {
1762                Transformed::yes(lit(false))
1763            }
1764
1765            // expr IN () --> false
1766            // expr NOT IN () --> true
1767            Expr::InList(InList {
1768                expr: _,
1769                list,
1770                negated,
1771            }) if list.is_empty() => Transformed::yes(lit(negated)),
1772
1773            // null in (x, y, z) --> null
1774            // null not in (x, y, z) --> null
1775            Expr::InList(InList {
1776                expr,
1777                list,
1778                negated: _,
1779            }) if is_null(expr.as_ref()) && !list.is_empty() => {
1780                Transformed::yes(lit_bool_null())
1781            }
1782
1783            // expr IN ((subquery)) -> expr IN (subquery), see ##5529
1784            Expr::InList(InList {
1785                expr,
1786                mut list,
1787                negated,
1788            }) if list.len() == 1
1789                && matches!(list.first(), Some(Expr::ScalarSubquery { .. })) =>
1790            {
1791                let Expr::ScalarSubquery(subquery) = list.remove(0) else {
1792                    unreachable!()
1793                };
1794
1795                Transformed::yes(Expr::InSubquery(InSubquery::new(
1796                    expr, subquery, negated,
1797                )))
1798            }
1799
1800            // Combine multiple OR expressions into a single IN list expression if possible
1801            //
1802            // i.e. `a = 1 OR a = 2 OR a = 3` -> `a IN (1, 2, 3)`
1803            Expr::BinaryExpr(BinaryExpr {
1804                left,
1805                op: Or,
1806                right,
1807            }) if are_inlist_and_eq(left.as_ref(), right.as_ref()) => {
1808                let lhs = to_inlist(*left).unwrap();
1809                let rhs = to_inlist(*right).unwrap();
1810                #[allow(clippy::allow_attributes, clippy::mutable_key_type)]
1811                // Expr contains Arc with interior mutability but is intentionally used as hash key
1812                let mut seen: HashSet<Expr> =
1813                    HashSet::with_capacity(lhs.list.len() + rhs.list.len());
1814                let list = lhs
1815                    .list
1816                    .into_iter()
1817                    .chain(rhs.list)
1818                    .filter(|e| seen.insert(e.to_owned()))
1819                    .collect::<Vec<_>>();
1820
1821                let merged_inlist = InList {
1822                    expr: lhs.expr,
1823                    list,
1824                    negated: false,
1825                };
1826
1827                Transformed::yes(Expr::InList(merged_inlist))
1828            }
1829
1830            // Simplify expressions that is guaranteed to be true or false to a literal boolean expression
1831            //
1832            // Rules:
1833            // If both expressions are `IN` or `NOT IN`, then we can apply intersection or union on both lists
1834            //   Intersection:
1835            //     1. `a in (1,2,3) AND a in (4,5) -> a in (), which is false`
1836            //     2. `a in (1,2,3) AND a in (2,3,4) -> a in (2,3)`
1837            //     3. `a not in (1,2,3) OR a not in (3,4,5,6) -> a not in (3)`
1838            //   Union:
1839            //     4. `a not int (1,2,3) AND a not in (4,5,6) -> a not in (1,2,3,4,5,6)`
1840            //     # This rule is handled by `or_in_list_simplifier.rs`
1841            //     5. `a in (1,2,3) OR a in (4,5,6) -> a in (1,2,3,4,5,6)`
1842            // If one of the expressions is `IN` and another one is `NOT IN`, then we apply exception on `In` expression
1843            //     6. `a in (1,2,3,4) AND a not in (1,2,3,4,5) -> a in (), which is false`
1844            //     7. `a not in (1,2,3,4) AND a in (1,2,3,4,5) -> a = 5`
1845            //     8. `a in (1,2,3,4) AND a not in (5,6,7,8) -> a in (1,2,3,4)`
1846            Expr::BinaryExpr(BinaryExpr {
1847                left,
1848                op: And,
1849                right,
1850            }) if are_inlist_and_eq_and_match_neg(
1851                left.as_ref(),
1852                right.as_ref(),
1853                false,
1854                false,
1855            ) && inlists_have_set_comparable_literals(
1856                left.as_ref(),
1857                right.as_ref(),
1858            ) =>
1859            {
1860                match (*left, *right) {
1861                    (Expr::InList(l1), Expr::InList(l2)) => {
1862                        let simplified = inlist_intersection(l1.clone(), &l2, false)?;
1863                        if let Some(simplified) =
1864                            simplify_inlist_set_operation(info, &l1, &l2, simplified)?
1865                        {
1866                            Transformed::yes(simplified)
1867                        } else {
1868                            Transformed::no(Expr::InList(l1).and(Expr::InList(l2)))
1869                        }
1870                    }
1871                    // Matched previously once
1872                    _ => unreachable!(),
1873                }
1874            }
1875
1876            Expr::BinaryExpr(BinaryExpr {
1877                left,
1878                op: And,
1879                right,
1880            }) if are_inlist_and_eq_and_match_neg(
1881                left.as_ref(),
1882                right.as_ref(),
1883                true,
1884                true,
1885            ) =>
1886            {
1887                match (*left, *right) {
1888                    (Expr::InList(l1), Expr::InList(l2)) => {
1889                        return inlist_union(l1, l2, true).map(Transformed::yes);
1890                    }
1891                    // Matched previously once
1892                    _ => unreachable!(),
1893                }
1894            }
1895
1896            Expr::BinaryExpr(BinaryExpr {
1897                left,
1898                op: And,
1899                right,
1900            }) if are_inlist_and_eq_and_match_neg(
1901                left.as_ref(),
1902                right.as_ref(),
1903                false,
1904                true,
1905            ) && inlists_have_set_comparable_literals(
1906                left.as_ref(),
1907                right.as_ref(),
1908            ) =>
1909            {
1910                match (*left, *right) {
1911                    (Expr::InList(l1), Expr::InList(l2)) => {
1912                        let simplified = inlist_except(l1.clone(), &l2)?;
1913                        if let Some(simplified) =
1914                            simplify_inlist_set_operation(info, &l1, &l2, simplified)?
1915                        {
1916                            Transformed::yes(simplified)
1917                        } else {
1918                            Transformed::no(Expr::InList(l1).and(Expr::InList(l2)))
1919                        }
1920                    }
1921                    // Matched previously once
1922                    _ => unreachable!(),
1923                }
1924            }
1925
1926            Expr::BinaryExpr(BinaryExpr {
1927                left,
1928                op: And,
1929                right,
1930            }) if are_inlist_and_eq_and_match_neg(
1931                left.as_ref(),
1932                right.as_ref(),
1933                true,
1934                false,
1935            ) && inlists_have_set_comparable_literals(
1936                left.as_ref(),
1937                right.as_ref(),
1938            ) =>
1939            {
1940                match (*left, *right) {
1941                    (Expr::InList(l1), Expr::InList(l2)) => {
1942                        let simplified = inlist_except(l2.clone(), &l1)?;
1943                        if let Some(simplified) =
1944                            simplify_inlist_set_operation(info, &l1, &l2, simplified)?
1945                        {
1946                            Transformed::yes(simplified)
1947                        } else {
1948                            Transformed::no(Expr::InList(l1).and(Expr::InList(l2)))
1949                        }
1950                    }
1951                    // Matched previously once
1952                    _ => unreachable!(),
1953                }
1954            }
1955
1956            Expr::BinaryExpr(BinaryExpr {
1957                left,
1958                op: Or,
1959                right,
1960            }) if are_inlist_and_eq_and_match_neg(
1961                left.as_ref(),
1962                right.as_ref(),
1963                true,
1964                true,
1965            ) && inlists_have_set_comparable_literals(
1966                left.as_ref(),
1967                right.as_ref(),
1968            ) =>
1969            {
1970                match (*left, *right) {
1971                    (Expr::InList(l1), Expr::InList(l2)) => {
1972                        let simplified = inlist_intersection(l1.clone(), &l2, true)?;
1973                        if let Some(simplified) =
1974                            simplify_inlist_set_operation(info, &l1, &l2, simplified)?
1975                        {
1976                            Transformed::yes(simplified)
1977                        } else {
1978                            Transformed::no(Expr::InList(l1).or(Expr::InList(l2)))
1979                        }
1980                    }
1981                    // Matched previously once
1982                    _ => unreachable!(),
1983                }
1984            }
1985
1986            // =======================================
1987            // cast_predicate_in_comparison
1988            // =======================================
1989            //
1990            // For case:
1991            // try_cast/cast(expr as data_type) op literal
1992            Expr::BinaryExpr(BinaryExpr { left, op, right })
1993                if supports_cast_predicate_for_binary(info, &left, op, &right)
1994                    && op.supports_propagation() =>
1995            {
1996                rewrite_cast_predicate_for_binary(info, *left, *right, op)?
1997            }
1998            // literal op try_cast/cast(expr as data_type)
1999            // -->
2000            // try_cast/cast(expr as data_type) op_swap literal
2001            Expr::BinaryExpr(BinaryExpr { left, op, right })
2002                if op.supports_propagation()
2003                    && op.swap().is_some_and(|swapped| {
2004                        supports_cast_predicate_for_binary(info, &right, swapped, &left)
2005                    }) =>
2006            {
2007                rewrite_cast_predicate_for_binary(
2008                    info,
2009                    *right,
2010                    *left,
2011                    op.swap().unwrap(),
2012                )?
2013            }
2014            // For case:
2015            // try_cast/cast(expr as left_type) in (expr1,expr2,expr3)
2016            Expr::InList(InList {
2017                expr,
2018                list,
2019                negated,
2020            }) if supports_cast_predicate_for_inlist(info, &expr, &list) => {
2021                rewrite_cast_predicate_for_inlist(info, *expr, list, negated)?
2022            }
2023
2024            // =======================================
2025            // preimage_in_comparison
2026            // =======================================
2027            //
2028            // For case:
2029            // date_part('YEAR', expr) op literal
2030            //
2031            // For details see datafusion_expr::ScalarUDFImpl::preimage
2032            Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
2033                use datafusion_expr::Operator::*;
2034                let is_preimage_op = matches!(
2035                    op,
2036                    Eq | NotEq
2037                        | Lt
2038                        | LtEq
2039                        | Gt
2040                        | GtEq
2041                        | IsDistinctFrom
2042                        | IsNotDistinctFrom
2043                );
2044                if !is_preimage_op || is_null(&right) {
2045                    return Ok(Transformed::no(Expr::BinaryExpr(BinaryExpr {
2046                        left,
2047                        op,
2048                        right,
2049                    })));
2050                }
2051
2052                if let PreimageResult::Range { interval, expr } =
2053                    get_preimage(left.as_ref(), right.as_ref(), info)?
2054                {
2055                    rewrite_with_preimage(*interval, op, expr)?
2056                } else if let Some(swapped) = op.swap() {
2057                    if let PreimageResult::Range { interval, expr } =
2058                        get_preimage(right.as_ref(), left.as_ref(), info)?
2059                    {
2060                        rewrite_with_preimage(*interval, swapped, expr)?
2061                    } else {
2062                        Transformed::no(Expr::BinaryExpr(BinaryExpr { left, op, right }))
2063                    }
2064                } else {
2065                    Transformed::no(Expr::BinaryExpr(BinaryExpr { left, op, right }))
2066                }
2067            }
2068            // For case:
2069            // date_part('YEAR', expr) IN (literal1, literal2, ...)
2070            Expr::InList(InList {
2071                expr,
2072                list,
2073                negated,
2074            }) => {
2075                if list.len() > THRESHOLD_INLINE_INLIST || list.iter().any(is_null) {
2076                    return Ok(Transformed::no(Expr::InList(InList {
2077                        expr,
2078                        list,
2079                        negated,
2080                    })));
2081                }
2082
2083                let (op, combiner): (Operator, fn(Expr, Expr) -> Expr) =
2084                    if negated { (NotEq, and) } else { (Eq, or) };
2085
2086                let mut rewritten: Option<Expr> = None;
2087                for item in &list {
2088                    let PreimageResult::Range { interval, expr } =
2089                        get_preimage(expr.as_ref(), item, info)?
2090                    else {
2091                        return Ok(Transformed::no(Expr::InList(InList {
2092                            expr,
2093                            list,
2094                            negated,
2095                        })));
2096                    };
2097
2098                    let range_expr = rewrite_with_preimage(*interval, op, expr)?.data;
2099                    rewritten = Some(match rewritten {
2100                        None => range_expr,
2101                        Some(acc) => combiner(acc, range_expr),
2102                    });
2103                }
2104
2105                if let Some(rewritten) = rewritten {
2106                    Transformed::yes(rewritten)
2107                } else {
2108                    Transformed::no(Expr::InList(InList {
2109                        expr,
2110                        list,
2111                        negated,
2112                    }))
2113                }
2114            }
2115
2116            // no additional rewrites possible
2117            expr => Transformed::no(expr),
2118        })
2119    }
2120}
2121
2122fn get_preimage(
2123    left_expr: &Expr,
2124    right_expr: &Expr,
2125    info: &SimplifyContext,
2126) -> Result<PreimageResult> {
2127    let Expr::ScalarFunction(ScalarFunction { func, args }) = left_expr else {
2128        return Ok(PreimageResult::None);
2129    };
2130    if !is_literal_or_literal_cast(right_expr) {
2131        return Ok(PreimageResult::None);
2132    }
2133    if func.signature().volatility != Volatility::Immutable {
2134        return Ok(PreimageResult::None);
2135    }
2136    // We can get duplicate expressions due to preimage rewrites due to volatile arguments
2137    if args.iter().any(Expr::is_volatile) {
2138        return Ok(PreimageResult::None);
2139    }
2140
2141    func.preimage(args, right_expr, info)
2142}
2143
2144fn is_literal_or_literal_cast(expr: &Expr) -> bool {
2145    match expr {
2146        Expr::Literal(_, _) => true,
2147        Expr::Cast(Cast { expr, .. }) => matches!(expr.as_ref(), Expr::Literal(_, _)),
2148        Expr::TryCast(TryCast { expr, .. }) => {
2149            matches!(expr.as_ref(), Expr::Literal(_, _))
2150        }
2151        _ => false,
2152    }
2153}
2154
2155/// Helper for working with string scalar values (Utf8, LargeUtf8, Utf8View)
2156pub(crate) enum StringScalar<'a> {
2157    Utf8(&'a ScalarValue),
2158    LargeUtf8(&'a ScalarValue),
2159    Utf8View(&'a ScalarValue),
2160}
2161
2162impl<'a> StringScalar<'a> {
2163    /// Create a `StringScalar` view from an `Expr` if it is a supported string literal.
2164    /// Returns `None` if the expression is not a string literal.
2165    pub(crate) fn try_from_expr(expr: &'a Expr) -> Option<Self> {
2166        match expr {
2167            Expr::Literal(scalar, _) => Self::try_from_scalar(scalar),
2168            _ => None,
2169        }
2170    }
2171
2172    /// Create a `StringScalar` view from a `ScalarValue` if it is a supported string type.
2173    /// Returns `None` if the scalar value is not a supported string type.
2174    fn try_from_scalar(scalar: &'a ScalarValue) -> Option<Self> {
2175        match scalar {
2176            ScalarValue::Utf8(_) => Some(Self::Utf8(scalar)),
2177            ScalarValue::LargeUtf8(_) => Some(Self::LargeUtf8(scalar)),
2178            ScalarValue::Utf8View(_) => Some(Self::Utf8View(scalar)),
2179            _ => None,
2180        }
2181    }
2182
2183    /// Returns the underlying string slice.
2184    pub(crate) fn as_str(&self) -> Option<&'a str> {
2185        match self {
2186            Self::Utf8(scalar) | Self::LargeUtf8(scalar) | Self::Utf8View(scalar) => {
2187                scalar.try_as_str().flatten()
2188            }
2189        }
2190    }
2191
2192    /// Build a new `Expr` of the same string type with the given value.
2193    pub(crate) fn to_expr(&self, val: &str) -> Expr {
2194        match self {
2195            Self::Utf8(_) => Expr::Literal(ScalarValue::Utf8(Some(val.to_owned())), None),
2196            Self::LargeUtf8(_) => {
2197                Expr::Literal(ScalarValue::LargeUtf8(Some(val.to_owned())), None)
2198            }
2199            Self::Utf8View(_) => {
2200                Expr::Literal(ScalarValue::Utf8View(Some(val.to_owned())), None)
2201            }
2202        }
2203    }
2204}
2205
2206#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // Expr contains Arc with interior mutability but is intentionally used as hash key
2207fn has_common_conjunction(lhs: &Expr, rhs: &Expr) -> bool {
2208    let lhs_set: HashSet<&Expr> = iter_conjunction(lhs).collect();
2209    iter_conjunction(rhs).any(|e| lhs_set.contains(&e) && !e.is_volatile())
2210}
2211
2212// TODO: We might not need this after defer pattern for Box is stabilized. https://github.com/rust-lang/rust/issues/87121
2213fn are_inlist_and_eq_and_match_neg(
2214    left: &Expr,
2215    right: &Expr,
2216    is_left_neg: bool,
2217    is_right_neg: bool,
2218) -> bool {
2219    match (left, right) {
2220        (Expr::InList(l), Expr::InList(r)) => {
2221            l.expr == r.expr
2222                && !l.expr.is_volatile()
2223                && !l.list.iter().chain(&r.list).any(Expr::is_volatile)
2224                && l.negated == is_left_neg
2225                && r.negated == is_right_neg
2226        }
2227        _ => false,
2228    }
2229}
2230
2231/// Structural equality can determine set membership only for non-null literals
2232/// whose equality agrees with runtime comparisons. Different runtime expressions
2233/// can evaluate to the same value, and floating-point equality can differ from
2234/// literal equality (for example, positive and negative zero).
2235fn inlists_have_set_comparable_literals(left: &Expr, right: &Expr) -> bool {
2236    match (left, right) {
2237        (Expr::InList(l), Expr::InList(r)) => l.list.iter().chain(&r.list).all(|item| {
2238            item.as_literal().is_some_and(|value| {
2239                !value.is_null() && !has_float_leaf(&value.data_type())
2240            })
2241        }),
2242        _ => false,
2243    }
2244}
2245
2246// TODO: We might not need this after defer pattern for Box is stabilized. https://github.com/rust-lang/rust/issues/87121
2247fn are_inlist_and_eq(left: &Expr, right: &Expr) -> bool {
2248    let left = as_inlist(left);
2249    let right = as_inlist(right);
2250    if let (Some(lhs), Some(rhs)) = (left, right) {
2251        matches!(lhs.expr.as_ref(), Expr::Column(_))
2252            && matches!(rhs.expr.as_ref(), Expr::Column(_))
2253            && lhs.expr == rhs.expr
2254            && !lhs.list.iter().chain(&rhs.list).any(Expr::is_volatile)
2255            && !lhs.negated
2256            && !rhs.negated
2257    } else {
2258        false
2259    }
2260}
2261
2262/// Try to convert an expression to an in-list expression
2263fn as_inlist(expr: &'_ Expr) -> Option<Cow<'_, InList>> {
2264    match expr {
2265        Expr::InList(inlist) => Some(Cow::Borrowed(inlist)),
2266        Expr::BinaryExpr(BinaryExpr { left, op, right }) if *op == Operator::Eq => {
2267            match (left.as_ref(), right.as_ref()) {
2268                (Expr::Column(_), Expr::Literal(_, _)) => Some(Cow::Owned(InList {
2269                    expr: left.clone(),
2270                    list: vec![*right.clone()],
2271                    negated: false,
2272                })),
2273                (Expr::Literal(_, _), Expr::Column(_)) => Some(Cow::Owned(InList {
2274                    expr: right.clone(),
2275                    list: vec![*left.clone()],
2276                    negated: false,
2277                })),
2278                _ => None,
2279            }
2280        }
2281        _ => None,
2282    }
2283}
2284
2285fn to_inlist(expr: Expr) -> Option<InList> {
2286    match expr {
2287        Expr::InList(inlist) => Some(inlist),
2288        Expr::BinaryExpr(BinaryExpr {
2289            left,
2290            op: Operator::Eq,
2291            right,
2292        }) => match (left.as_ref(), right.as_ref()) {
2293            (Expr::Column(_), Expr::Literal(_, _)) => Some(InList {
2294                expr: left,
2295                list: vec![*right],
2296                negated: false,
2297            }),
2298            (Expr::Literal(_, _), Expr::Column(_)) => Some(InList {
2299                expr: right,
2300                list: vec![*left],
2301                negated: false,
2302            }),
2303            _ => None,
2304        },
2305        _ => None,
2306    }
2307}
2308
2309/// Return the union of two inlist expressions
2310/// maintaining the order of the elements in the two lists
2311#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // Expr contains Arc with interior mutability but is intentionally used as hash key
2312fn inlist_union(mut l1: InList, l2: InList, negated: bool) -> Result<Expr> {
2313    // extend the list in l1 with the elements in l2 that are not already in l1
2314    let l1_items: HashSet<_> = l1.list.iter().collect();
2315
2316    // keep all l2 items that do not also appear in l1
2317    let keep_l2: Vec<_> = l2
2318        .list
2319        .into_iter()
2320        .filter_map(|e| if l1_items.contains(&e) { None } else { Some(e) })
2321        .collect();
2322
2323    l1.list.extend(keep_l2);
2324    l1.negated = negated;
2325    Ok(Expr::InList(l1))
2326}
2327
2328/// Return the intersection of two inlist expressions
2329/// maintaining the order of the elements in the two lists
2330#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // Expr contains Arc with interior mutability but is intentionally used as hash key
2331fn inlist_intersection(mut l1: InList, l2: &InList, negated: bool) -> Result<Expr> {
2332    let l2_items = l2.list.iter().collect::<HashSet<_>>();
2333
2334    // remove all items from l1 that are not in l2
2335    l1.list.retain(|e| l2_items.contains(e));
2336
2337    // e in () is always false
2338    // e not in () is always true
2339    if l1.list.is_empty() {
2340        return Ok(lit(negated));
2341    }
2342    Ok(Expr::InList(l1))
2343}
2344
2345/// Return the all items in l1 that are not in l2
2346/// maintaining the order of the elements in the two lists
2347#[allow(clippy::allow_attributes, clippy::mutable_key_type)] // Expr contains Arc with interior mutability but is intentionally used as hash key
2348fn inlist_except(mut l1: InList, l2: &InList) -> Result<Expr> {
2349    let l2_items = l2.list.iter().collect::<HashSet<_>>();
2350
2351    // keep only items from l1 that are not in l2
2352    l1.list.retain(|e| !l2_items.contains(e));
2353
2354    if l1.list.is_empty() {
2355        return Ok(lit(false));
2356    }
2357    Ok(Expr::InList(l1))
2358}
2359
2360/// Set algebra on `IN` lists is only sound if nullable list items are not
2361/// discarded. When the tested expression is nullable, preserve the NULL branch
2362/// of an otherwise constant result explicitly.
2363fn simplify_inlist_set_operation(
2364    info: &SimplifyContext,
2365    left: &InList,
2366    right: &InList,
2367    result: Expr,
2368) -> Result<Option<Expr>> {
2369    for item in left.list.iter().chain(&right.list) {
2370        if info.nullable(item)? {
2371            return Ok(None);
2372        }
2373    }
2374
2375    if !is_true(&result) && !is_false(&result) {
2376        return Ok(Some(result));
2377    }
2378
2379    Ok(Some(if !info.nullable(left.expr.as_ref())? {
2380        result
2381    } else if is_true(&result) {
2382        Expr::IsNotNull(left.expr.clone()).or(lit_bool_null())
2383    } else {
2384        Expr::IsNull(left.expr.clone()).and(lit_bool_null())
2385    }))
2386}
2387
2388/// Conservatively checks the inputs whose evaluation can change when lowering
2389/// CASE to AND/OR. [`Expr`] has no general fallibility analysis: only columns and
2390/// literals are admitted for all WHEN conditions and branch outputs.
2391fn can_lower_case_to_boolean(
2392    when_then_expr: &[(Box<Expr>, Box<Expr>)],
2393    else_expr: Option<&Expr>,
2394) -> bool {
2395    let is_leaf = |expr: &Expr| matches!(expr, Expr::Column(_) | Expr::Literal(..));
2396    when_then_expr
2397        .iter()
2398        .all(|(when, then)| is_leaf(when) && is_leaf(then))
2399        && else_expr.is_none_or(is_leaf)
2400}
2401
2402/// Returns expression testing a boolean `expr` for being exactly `true` (not `false` or NULL).
2403fn is_exactly_true(expr: Expr, info: &SimplifyContext) -> Result<Expr> {
2404    if !info.nullable(&expr)? {
2405        Ok(expr)
2406    } else {
2407        Ok(Expr::BinaryExpr(BinaryExpr {
2408            left: Box::new(expr),
2409            op: Operator::IsNotDistinctFrom,
2410            right: Box::new(lit(true)),
2411        }))
2412    }
2413}
2414
2415// A * 1 -> A
2416// A / 1 -> A
2417//
2418// Move this function body out of the large match branch avoid stack overflow
2419fn simplify_right_is_one_case(
2420    info: &SimplifyContext,
2421    left: Box<Expr>,
2422    op: &Operator,
2423    right: &Expr,
2424) -> Result<Transformed<Expr>> {
2425    // Check if resulting type would be different due to coercion
2426    let left_type = info.get_data_type(&left)?;
2427    let right_type = info.get_data_type(right)?;
2428    match BinaryTypeCoercer::new(&left_type, op, &right_type).get_result_type() {
2429        Ok(result_type) => {
2430            // Only cast if the types differ
2431            if left_type != result_type {
2432                Ok(Transformed::yes(Expr::Cast(Cast::new(left, result_type))))
2433            } else {
2434                Ok(Transformed::yes(*left))
2435            }
2436        }
2437        Err(_) => Ok(Transformed::yes(*left)),
2438    }
2439}
2440
2441#[cfg(test)]
2442mod tests {
2443    use super::*;
2444    use crate::test::test_table_scan_with_name;
2445    use arrow::{
2446        array::{BooleanArray, Float64Array, Int32Array, StructArray},
2447        datatypes::{FieldRef, Fields},
2448    };
2449    use datafusion_common::{DFSchemaRef, ToDFSchema, assert_contains};
2450    use datafusion_expr::{
2451        expr::WindowFunction,
2452        function::{
2453            AccumulatorArgs, AggregateFunctionSimplification,
2454            WindowFunctionSimplification,
2455        },
2456        interval_arithmetic::Interval,
2457        *,
2458    };
2459    use datafusion_functions_window_common::field::WindowUDFFieldArgs;
2460    use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
2461    use datafusion_physical_expr::PhysicalExpr;
2462    use std::hash::Hash;
2463    use std::sync::LazyLock;
2464    use std::{
2465        collections::HashMap,
2466        ops::{BitAnd, BitOr, BitXor},
2467        sync::Arc,
2468    };
2469
2470    // ------------------------------
2471    // --- ExprSimplifier tests -----
2472    // ------------------------------
2473    #[test]
2474    fn api_basic() {
2475        let simplifier = ExprSimplifier::new(
2476            SimplifyContext::builder()
2477                .with_schema(test_schema())
2478                .build(),
2479        );
2480
2481        let expr = lit(1) + lit(2);
2482        let expected = lit(3);
2483        assert_eq!(expected, simplifier.simplify(expr).unwrap());
2484    }
2485
2486    #[test]
2487    fn basic_coercion() {
2488        let schema = test_schema();
2489        let simplifier = ExprSimplifier::new(
2490            SimplifyContext::builder()
2491                .with_schema(Arc::clone(&schema))
2492                .build(),
2493        );
2494
2495        // Note expr type is int32 (not int64)
2496        // (1i64 + 2i32) < i
2497        let expr = (lit(1i64) + lit(2i32)).lt(col("i"));
2498        // should fully simplify to 3 < i (though i has been coerced to i64)
2499        let expected = lit(3i64).lt(col("i"));
2500
2501        let expr = simplifier.coerce(expr, &schema).unwrap();
2502
2503        assert_eq!(expected, simplifier.simplify(expr).unwrap());
2504    }
2505
2506    fn test_schema() -> DFSchemaRef {
2507        static TEST_SCHEMA: LazyLock<DFSchemaRef> = LazyLock::new(|| {
2508            Schema::new(vec![
2509                Field::new("i", DataType::Int64, false),
2510                Field::new("b", DataType::Boolean, true),
2511            ])
2512            .to_dfschema_ref()
2513            .unwrap()
2514        });
2515        Arc::clone(&TEST_SCHEMA)
2516    }
2517
2518    #[test]
2519    fn simplify_and_constant_prop() {
2520        let simplifier = ExprSimplifier::new(
2521            SimplifyContext::builder()
2522                .with_schema(test_schema())
2523                .build(),
2524        );
2525
2526        // should be able to simplify to false
2527        // (i * (1 - 2)) > 0
2528        let expr = (col("i") * (lit(1) - lit(1))).gt(lit(0));
2529        let expected = lit(false);
2530        assert_eq!(expected, simplifier.simplify(expr).unwrap());
2531    }
2532
2533    #[test]
2534    fn simplify_and_constant_prop_with_case() {
2535        let simplifier = ExprSimplifier::new(
2536            SimplifyContext::builder()
2537                .with_schema(test_schema())
2538                .build(),
2539        );
2540
2541        //   CASE
2542        //     WHEN i>5 AND false THEN i > 5
2543        //     WHEN i<5 AND true THEN i < 5
2544        //     ELSE false
2545        //   END
2546        //
2547        // Fold the constant conditions, but preserve CASE because the THEN
2548        // expression is outside the conservative column/literal subset.
2549        let expr = when(col("i").gt(lit(5)).and(lit(false)), col("i").gt(lit(5)))
2550            .when(col("i").lt(lit(5)).and(lit(true)), col("i").lt(lit(5)))
2551            .otherwise(lit(false))
2552            .unwrap();
2553        let expected = when(col("i").lt(lit(5)), col("i").lt(lit(5)))
2554            .otherwise(lit(false))
2555            .unwrap();
2556        assert_eq!(expected, simplifier.simplify(expr).unwrap());
2557    }
2558
2559    // ------------------------------
2560    // --- Simplifier tests -----
2561    // ------------------------------
2562
2563    #[test]
2564    fn test_simplify_canonicalize() {
2565        {
2566            let expr = lit(1).lt(col("c2")).and(col("c2").gt(lit(1)));
2567            let expected = col("c2").gt(lit(1));
2568            assert_eq!(simplify(expr), expected);
2569        }
2570        {
2571            let expr = col("c1").lt(col("c2")).and(col("c2").gt(col("c1")));
2572            let expected = col("c2").gt(col("c1"));
2573            assert_eq!(simplify(expr), expected);
2574        }
2575        {
2576            let expr = col("c1")
2577                .eq(lit(1))
2578                .and(lit(1).eq(col("c1")))
2579                .and(col("c1").eq(lit(3)));
2580            let expected = col("c1").eq(lit(1)).and(col("c1").eq(lit(3)));
2581            assert_eq!(simplify(expr), expected);
2582        }
2583        {
2584            let expr = col("c1")
2585                .eq(col("c2"))
2586                .and(col("c1").gt(lit(5)))
2587                .and(col("c2").eq(col("c1")));
2588            let expected = col("c2").eq(col("c1")).and(col("c1").gt(lit(5)));
2589            assert_eq!(simplify(expr), expected);
2590        }
2591        {
2592            let expr = col("c1")
2593                .eq(lit(1))
2594                .and(col("c2").gt(lit(3)).or(lit(3).lt(col("c2"))));
2595            let expected = col("c1").eq(lit(1)).and(col("c2").gt(lit(3)));
2596            assert_eq!(simplify(expr), expected);
2597        }
2598        {
2599            let expr = col("c1").lt(lit(5)).and(col("c1").gt_eq(lit(5)));
2600            let expected = col("c1").lt(lit(5)).and(col("c1").gt_eq(lit(5)));
2601            assert_eq!(simplify(expr), expected);
2602        }
2603        {
2604            let expr = col("c1").lt(lit(5)).and(col("c1").gt_eq(lit(5)));
2605            let expected = col("c1").lt(lit(5)).and(col("c1").gt_eq(lit(5)));
2606            assert_eq!(simplify(expr), expected);
2607        }
2608        {
2609            let expr = col("c1").gt(col("c2")).and(col("c1").gt(col("c2")));
2610            let expected = col("c2").lt(col("c1"));
2611            assert_eq!(simplify(expr), expected);
2612        }
2613    }
2614
2615    #[test]
2616    fn test_simplify_swapped_operands_in_and_or_no_canonicalize() {
2617        // Regression test for https://github.com/apache/datafusion/issues/14943
2618        //
2619        // `SimplifyExpressions` disables canonicalization for `LogicalPlan::Join`
2620        // (see https://github.com/apache/datafusion/pull/8780), so commutative
2621        // operands like `A = B` and `B = A` cannot be normalized to a single
2622        // form before AND/OR dedup runs. The dedup itself must therefore
2623        // recognize commutative equivalence directly.
2624
2625        // c3 = 5 AND 5 = c3 --> c3 = 5
2626        let expr = col("c3_non_null")
2627            .eq(lit(5_i64))
2628            .and(lit(5_i64).eq(col("c3_non_null")));
2629        let expected = col("c3_non_null").eq(lit(5_i64));
2630        assert_eq!(simplify_no_canonicalize(expr), expected);
2631
2632        // 5 = c3 AND c3 = 5 --> 5 = c3
2633        let expr = lit(5_i64)
2634            .eq(col("c3_non_null"))
2635            .and(col("c3_non_null").eq(lit(5_i64)));
2636        let expected = lit(5_i64).eq(col("c3_non_null"));
2637        assert_eq!(simplify_no_canonicalize(expr), expected);
2638
2639        // c3 = 5 OR 5 = c3 --> c3 = 5
2640        let expr = col("c3_non_null")
2641            .eq(lit(5_i64))
2642            .or(lit(5_i64).eq(col("c3_non_null")));
2643        let expected = col("c3_non_null").eq(lit(5_i64));
2644        assert_eq!(simplify_no_canonicalize(expr), expected);
2645
2646        // (c3 = 5 AND c4 > 0) AND (5 = c3) --> c3 = 5 AND c4 > 0
2647        let expr = col("c3_non_null")
2648            .eq(lit(5_i64))
2649            .and(col("c4_non_null").gt(lit(0_u32)))
2650            .and(lit(5_i64).eq(col("c3_non_null")));
2651        let expected = col("c3_non_null")
2652            .eq(lit(5_i64))
2653            .and(col("c4_non_null").gt(lit(0_u32)));
2654        assert_eq!(simplify_no_canonicalize(expr), expected);
2655    }
2656
2657    #[test]
2658    fn test_simplify_swapped_operands_in_xor_no_canonicalize() {
2659        // `expr_contains` guards the XOR rules, so `delete_xor_in_complex_expr` has to
2660        // use the same equality relation. Comparing structurally there while the guard
2661        // normalizes makes the rule rebuild its input and still report `Transformed::yes`,
2662        // which spins the simplifier until it hits the cycle limit.
2663        //
2664        // Operands are non-nullable so the expected results do not depend on how the XOR
2665        // rules treat a NULL operand, which is a separate question from the cycle.
2666
2667        // (c4_non_null + 1) ^ (1 + c4_non_null) --> 0
2668        let expr = bitwise_xor(
2669            col("c4_non_null") + lit(1_u32),
2670            lit(1_u32) + col("c4_non_null"),
2671        );
2672        let (simplified, cycles) = simplify_no_canonicalize_with_cycle_count(expr);
2673        assert_eq!(simplified, lit(0_u32));
2674        assert_eq!(cycles, 2);
2675
2676        // (c4_non_null + 1) ^ ((1 + c4_non_null) ^ c4_non_null) --> c4_non_null
2677        let expr = bitwise_xor(
2678            col("c4_non_null") + lit(1_u32),
2679            bitwise_xor(lit(1_u32) + col("c4_non_null"), col("c4_non_null")),
2680        );
2681        let (simplified, cycles) = simplify_no_canonicalize_with_cycle_count(expr);
2682        assert_eq!(simplified, col("c4_non_null"));
2683        assert_eq!(cycles, 2);
2684    }
2685
2686    #[test]
2687    fn test_simplify_eq_not_self() {
2688        // `expr_a`: column `c2` is nullable, so `c2 = c2` simplifies to `c2 IS NOT NULL OR NULL`
2689        // This ensures the expression is only true when `c2` is not NULL, accounting for SQL's NULL semantics.
2690        let expr_a = col("c2").eq(col("c2"));
2691        let expected_a = col("c2").is_not_null().or(lit_bool_null());
2692
2693        // `expr_b`: column `c2_non_null` is explicitly non-nullable, so `c2_non_null = c2_non_null` is always true
2694        let expr_b = col("c2_non_null").eq(col("c2_non_null"));
2695        let expected_b = lit(true);
2696
2697        assert_eq!(simplify(expr_a), expected_a);
2698        assert_eq!(simplify(expr_b), expected_b);
2699    }
2700
2701    /// `c3_non_null IN (SELECT a FROM t)`, where `a` has the given nullability.
2702    fn in_subquery_expr(a_nullable: bool) -> Expr {
2703        let schema = Schema::new(vec![Field::new("a", DataType::Int64, a_nullable)]);
2704        let source = Arc::new(LogicalTableSource::new(Arc::new(schema)));
2705        let subquery = LogicalPlanBuilder::scan("t", source, None)
2706            .unwrap()
2707            .project(vec![col("a")])
2708            .unwrap()
2709            .build()
2710            .unwrap();
2711
2712        in_subquery(col("c3_non_null"), Arc::new(subquery))
2713    }
2714
2715    #[test]
2716    fn test_simplify_eq_not_self_in_subquery() {
2717        // `expr_a`: even though `c3_non_null` is non-nullable, the `IN` evaluates to NULL
2718        // when `c3_non_null` matches no row and the subquery's `a` contains a NULL. So the
2719        // expression is nullable and `A = A` must not fold to `true`.
2720        let expr_a = in_subquery_expr(true);
2721        let expected_a = expr_a.clone().is_not_null().or(lit_bool_null());
2722
2723        // `expr_b`: neither side can be NULL, so the `IN` is non-nullable and `A = A` is true.
2724        let expr_b = in_subquery_expr(false);
2725        let expected_b = lit(true);
2726
2727        assert_eq!(simplify(expr_a.clone().eq(expr_a)), expected_a);
2728        assert_eq!(simplify(expr_b.clone().eq(expr_b)), expected_b);
2729    }
2730
2731    #[test]
2732    fn test_simplify_or_true() {
2733        let expr_a = col("c2").or(lit(true));
2734        let expr_b = lit(true).or(col("c2"));
2735        let expected = lit(true);
2736
2737        assert_eq!(simplify(expr_a), expected);
2738        assert_eq!(simplify(expr_b), expected);
2739    }
2740
2741    #[test]
2742    fn test_simplify_or_false() {
2743        let expr_a = lit(false).or(col("c2"));
2744        let expr_b = col("c2").or(lit(false));
2745        let expected = col("c2");
2746
2747        assert_eq!(simplify(expr_a), expected);
2748        assert_eq!(simplify(expr_b), expected);
2749    }
2750
2751    #[test]
2752    fn test_simplify_or_same() {
2753        let expr = col("c2").or(col("c2"));
2754        let expected = col("c2");
2755
2756        assert_eq!(simplify(expr), expected);
2757    }
2758
2759    #[test]
2760    fn test_simplify_or_not_self() {
2761        // A OR !A if A is not nullable --> true
2762        // !A OR A if A is not nullable --> true
2763        let expr_a = col("c2_non_null").or(col("c2_non_null").not());
2764        let expr_b = col("c2_non_null").not().or(col("c2_non_null"));
2765        let expected = lit(true);
2766
2767        assert_eq!(simplify(expr_a), expected);
2768        assert_eq!(simplify(expr_b), expected);
2769    }
2770
2771    #[test]
2772    fn test_simplify_and_false() {
2773        let expr_a = lit(false).and(col("c2"));
2774        let expr_b = col("c2").and(lit(false));
2775        let expected = lit(false);
2776
2777        assert_eq!(simplify(expr_a), expected);
2778        assert_eq!(simplify(expr_b), expected);
2779    }
2780
2781    #[test]
2782    fn test_simplify_and_same() {
2783        let expr = col("c2").and(col("c2"));
2784        let expected = col("c2");
2785
2786        assert_eq!(simplify(expr), expected);
2787    }
2788
2789    #[test]
2790    fn test_simplify_and_true() {
2791        let expr_a = lit(true).and(col("c2"));
2792        let expr_b = col("c2").and(lit(true));
2793        let expected = col("c2");
2794
2795        assert_eq!(simplify(expr_a), expected);
2796        assert_eq!(simplify(expr_b), expected);
2797    }
2798
2799    #[test]
2800    fn test_simplify_and_not_self() {
2801        // A AND !A if A is not nullable --> false
2802        // !A AND A if A is not nullable --> false
2803        let expr_a = col("c2_non_null").and(col("c2_non_null").not());
2804        let expr_b = col("c2_non_null").not().and(col("c2_non_null"));
2805        let expected = lit(false);
2806
2807        assert_eq!(simplify(expr_a), expected);
2808        assert_eq!(simplify(expr_b), expected);
2809    }
2810
2811    #[test]
2812    fn test_simplify_eq_and_neq_with_different_literals() {
2813        // A = 1 AND A != 0 --> A = 1 (when 1 != 0)
2814        let expr = col("c2").eq(lit(1)).and(col("c2").not_eq(lit(0)));
2815        let expected = col("c2").eq(lit(1));
2816        assert_eq!(simplify(expr), expected);
2817
2818        // A != 0 AND A = 1 --> A = 1 (when 1 != 0)
2819        let expr = col("c2").not_eq(lit(0)).and(col("c2").eq(lit(1)));
2820        let expected = col("c2").eq(lit(1));
2821        assert_eq!(simplify(expr), expected);
2822
2823        // Should NOT simplify when literals are the same (A = 1 AND A != 1)
2824        // This is a contradiction but handled by other rules
2825        let expr = col("c2").eq(lit(1)).and(col("c2").not_eq(lit(1)));
2826        // Should not be simplified by this rule (left unchanged or handled elsewhere)
2827        let result = simplify(expr.clone());
2828        // The expression should not have been simplified
2829        assert_eq!(result, expr);
2830
2831        // Signed zeros compare equal at runtime and must not be treated as
2832        // different literals
2833        let expr = col("f")
2834            .eq(lit(0.0_f64))
2835            .and(col("f").not_eq(lit(-0.0_f64)));
2836        assert_eq!(simplify(expr.clone()), expr);
2837    }
2838
2839    #[test]
2840    fn test_simplify_multiply_by_one() {
2841        let expr_a = col("c2") * lit(1);
2842        let expr_b = lit(1) * col("c2");
2843        let expected = col("c2");
2844
2845        assert_eq!(simplify(expr_a), expected);
2846        assert_eq!(simplify(expr_b), expected);
2847
2848        let expr = col("c2") * lit(ScalarValue::Decimal128(Some(10000000000), 38, 10));
2849        assert_eq!(simplify(expr), expected);
2850
2851        let expr = lit(ScalarValue::Decimal128(Some(10000000000), 31, 10)) * col("c2");
2852        assert_eq!(simplify(expr), expected);
2853    }
2854
2855    #[test]
2856    fn test_simplify_multiply_by_null() {
2857        let null = lit(ScalarValue::Int64(None));
2858        // A * null --> null
2859        {
2860            let expr = col("c3") * null.clone();
2861            assert_eq!(simplify(expr), null);
2862        }
2863        // null * A --> null
2864        {
2865            let expr = null.clone() * col("c3");
2866            assert_eq!(simplify(expr), null);
2867        }
2868    }
2869
2870    #[test]
2871    fn test_simplify_multiply_by_zero() {
2872        // cannot optimize A * null (null * A) if A is nullable
2873        {
2874            let expr_a = col("c2") * lit(0);
2875            let expr_b = lit(0) * col("c2");
2876
2877            assert_eq!(simplify(expr_a.clone()), expr_a);
2878            assert_eq!(simplify(expr_b.clone()), expr_b);
2879        }
2880        // 0 * A --> 0 if A is not nullable
2881        {
2882            let expr = lit(0) * col("c2_non_null");
2883            assert_eq!(simplify(expr), lit(0));
2884        }
2885        // A * 0 --> 0 if A is not nullable
2886        {
2887            let expr = col("c2_non_null") * lit(0);
2888            assert_eq!(simplify(expr), lit(0));
2889        }
2890        // A * Decimal128(0) --> 0 if A is not nullable
2891        {
2892            let expr = col("c2_non_null") * lit(ScalarValue::Decimal128(Some(0), 31, 10));
2893            assert_eq!(
2894                simplify(expr),
2895                lit(ScalarValue::Decimal128(Some(0), 31, 10))
2896            );
2897            let expr = binary_expr(
2898                lit(ScalarValue::Decimal128(Some(0), 31, 10)),
2899                Operator::Multiply,
2900                col("c2_non_null"),
2901            );
2902            assert_eq!(
2903                simplify(expr),
2904                lit(ScalarValue::Decimal128(Some(0), 31, 10))
2905            );
2906        }
2907    }
2908
2909    #[test]
2910    fn test_simplify_divide_by_one() {
2911        let expr = binary_expr(col("c2"), Operator::Divide, lit(1));
2912        let expected = col("c2");
2913        assert_eq!(simplify(expr), expected);
2914        let expr = col("c2") / lit(ScalarValue::Decimal128(Some(10000000000), 31, 10));
2915        assert_eq!(simplify(expr), expected);
2916    }
2917
2918    #[test]
2919    fn test_simplify_divide_null() {
2920        // A / null --> null
2921        let null = lit(ScalarValue::Int64(None));
2922        {
2923            let expr = col("c3") / null.clone();
2924            assert_eq!(simplify(expr), null);
2925        }
2926        // null / A --> null
2927        {
2928            let expr = null.clone() / col("c3");
2929            assert_eq!(simplify(expr), null);
2930        }
2931    }
2932
2933    #[test]
2934    fn test_simplify_divide_by_same() {
2935        let expr = col("c2") / col("c2");
2936        // if c2 is null, c2 / c2 = null, so can't simplify
2937        let expected = expr.clone();
2938
2939        assert_eq!(simplify(expr), expected);
2940    }
2941
2942    #[test]
2943    fn test_simplify_modulo_by_null() {
2944        let null = lit(ScalarValue::Int64(None));
2945        // A % null --> null
2946        {
2947            let expr = col("c3") % null.clone();
2948            assert_eq!(simplify(expr), null);
2949        }
2950        // null % A --> null
2951        {
2952            let expr = null.clone() % col("c3");
2953            assert_eq!(simplify(expr), null);
2954        }
2955    }
2956
2957    #[test]
2958    fn test_simplify_modulo_by_one() {
2959        let expr = col("c2") % lit(1);
2960        // if c2 is null, c2 % 1 = null, so can't simplify
2961        let expected = expr.clone();
2962
2963        assert_eq!(simplify(expr), expected);
2964    }
2965
2966    #[test]
2967    fn test_simplify_divide_zero_by_zero() {
2968        // because divide by 0 maybe occur in short-circuit expression
2969        // so we should not simplify this, and throw error in runtime
2970        let expr = lit(0) / lit(0);
2971        let expected = expr.clone();
2972
2973        assert_eq!(simplify(expr), expected);
2974    }
2975
2976    #[test]
2977    fn test_simplify_divide_by_zero() {
2978        // because divide by 0 maybe occur in short-circuit expression
2979        // so we should not simplify this, and throw error in runtime
2980        let expr = col("c2_non_null") / lit(0);
2981        let expected = expr.clone();
2982
2983        assert_eq!(simplify(expr), expected);
2984    }
2985
2986    #[test]
2987    fn test_simplify_modulo_by_one_non_null() {
2988        let expr = col("c3_non_null") % lit(1);
2989        let expected = lit(0_i64);
2990        assert_eq!(simplify(expr), expected);
2991        let expr =
2992            col("c3_non_null") % lit(ScalarValue::Decimal128(Some(10000000000), 31, 10));
2993        assert_eq!(simplify(expr), expected);
2994    }
2995
2996    #[test]
2997    fn test_simplify_modulo_by_one_types() {
2998        for (data_type, folds) in [
2999            (DataType::Int8, true),
3000            (DataType::Int16, true),
3001            (DataType::Int32, true),
3002            (DataType::Int64, true),
3003            (DataType::UInt8, true),
3004            (DataType::UInt16, true),
3005            (DataType::UInt32, true),
3006            (DataType::UInt64, true),
3007            (DataType::Float32, false),
3008            (DataType::Float64, false),
3009            (DataType::Decimal32(9, -1), true),
3010            (DataType::Decimal32(9, 0), true),
3011            (DataType::Decimal32(9, 2), false),
3012            (DataType::Decimal64(18, -1), true),
3013            (DataType::Decimal64(18, 0), true),
3014            (DataType::Decimal64(18, 2), false),
3015            (DataType::Decimal128(38, -1), true),
3016            (DataType::Decimal128(38, 0), true),
3017            (DataType::Decimal128(38, 2), false),
3018            (DataType::Decimal256(76, -1), true),
3019            (DataType::Decimal256(76, 0), true),
3020            (DataType::Decimal256(76, 2), false),
3021        ] {
3022            for nullable in [false, true] {
3023                let schema =
3024                    Schema::new(vec![Field::new("a", data_type.clone(), nullable)])
3025                        .to_dfschema_ref()
3026                        .unwrap();
3027                let simplifier = ExprSimplifier::new(
3028                    SimplifyContext::builder().with_schema(schema).build(),
3029                );
3030                let expr = col("a") % lit(1);
3031                let expected = if folds && !nullable {
3032                    lit(ScalarValue::new_zero(&data_type).unwrap())
3033                } else {
3034                    expr.clone()
3035                };
3036                assert_eq!(
3037                    simplifier.simplify(expr).unwrap(),
3038                    expected,
3039                    "{data_type:?}, nullable={nullable}"
3040                );
3041            }
3042        }
3043    }
3044
3045    #[test]
3046    fn test_simplify_bitwise_xor_by_null() {
3047        let null = lit(ScalarValue::Int64(None));
3048        // A ^ null --> null
3049        {
3050            let expr = col("c3") ^ null.clone();
3051            assert_eq!(simplify(expr), null);
3052        }
3053        // null ^ A --> null
3054        {
3055            let expr = null.clone() ^ col("c3");
3056            assert_eq!(simplify(expr), null);
3057        }
3058    }
3059
3060    #[test]
3061    fn test_simplify_bitwise_shift_right_by_null() {
3062        let null = lit(ScalarValue::Int64(None));
3063        // A >> null --> null
3064        {
3065            let expr = col("c3") >> null.clone();
3066            assert_eq!(simplify(expr), null);
3067        }
3068        // null >> A --> null
3069        {
3070            let expr = null.clone() >> col("c3");
3071            assert_eq!(simplify(expr), null);
3072        }
3073    }
3074
3075    #[test]
3076    fn test_simplify_bitwise_shift_left_by_null() {
3077        let null = lit(ScalarValue::Int64(None));
3078        // A << null --> null
3079        {
3080            let expr = col("c3") << null.clone();
3081            assert_eq!(simplify(expr), null);
3082        }
3083        // null << A --> null
3084        {
3085            let expr = null.clone() << col("c3");
3086            assert_eq!(simplify(expr), null);
3087        }
3088    }
3089
3090    #[test]
3091    fn test_simplify_bitwise_and_by_zero() {
3092        // A & 0 --> 0
3093        {
3094            let expr = col("c2_non_null") & lit(0);
3095            assert_eq!(simplify(expr), lit(0));
3096        }
3097        // 0 & A --> 0
3098        {
3099            let expr = lit(0) & col("c2_non_null");
3100            assert_eq!(simplify(expr), lit(0));
3101        }
3102    }
3103
3104    #[test]
3105    fn test_simplify_bitwise_or_by_zero() {
3106        // A | 0 --> A
3107        {
3108            let expr = col("c2_non_null") | lit(0);
3109            assert_eq!(simplify(expr), col("c2_non_null"));
3110        }
3111        // 0 | A --> A
3112        {
3113            let expr = lit(0) | col("c2_non_null");
3114            assert_eq!(simplify(expr), col("c2_non_null"));
3115        }
3116    }
3117
3118    #[test]
3119    fn test_simplify_bitwise_xor_by_zero() {
3120        // A ^ 0 --> A
3121        {
3122            let expr = col("c2_non_null") ^ lit(0);
3123            assert_eq!(simplify(expr), col("c2_non_null"));
3124        }
3125        // 0 ^ A --> A
3126        {
3127            let expr = lit(0) ^ col("c2_non_null");
3128            assert_eq!(simplify(expr), col("c2_non_null"));
3129        }
3130    }
3131
3132    #[test]
3133    fn test_simplify_bitwise_bitwise_shift_right_by_zero() {
3134        // A >> 0 --> A
3135        {
3136            let expr = col("c2_non_null") >> lit(0);
3137            assert_eq!(simplify(expr), col("c2_non_null"));
3138        }
3139    }
3140
3141    #[test]
3142    fn test_simplify_bitwise_bitwise_shift_left_by_zero() {
3143        // A << 0 --> A
3144        {
3145            let expr = col("c2_non_null") << lit(0);
3146            assert_eq!(simplify(expr), col("c2_non_null"));
3147        }
3148    }
3149
3150    #[test]
3151    fn test_simplify_bitwise_and_by_null() {
3152        let null = Expr::Literal(ScalarValue::Int64(None), None);
3153        // A & null --> null
3154        {
3155            let expr = col("c3") & null.clone();
3156            assert_eq!(simplify(expr), null);
3157        }
3158        // null & A --> null
3159        {
3160            let expr = null.clone() & col("c3");
3161            assert_eq!(simplify(expr), null);
3162        }
3163    }
3164
3165    #[test]
3166    fn test_simplify_concat_by_null() {
3167        let null = Expr::Literal(ScalarValue::Utf8(None), None);
3168        // A || null --> null
3169        {
3170            let expr = binary_expr(col("c1"), Operator::StringConcat, null.clone());
3171            assert_eq!(simplify(expr), null);
3172        }
3173        // null || A --> null
3174        {
3175            let expr = binary_expr(null.clone(), Operator::StringConcat, col("c1"));
3176            assert_eq!(simplify(expr), null);
3177        }
3178    }
3179
3180    #[test]
3181    fn test_simplify_composed_bitwise_and() {
3182        // ((c2 > 5) & (c1 < 6)) & (c2 > 5) --> (c2 > 5) & (c1 < 6)
3183
3184        let expr = bitwise_and(
3185            bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
3186            col("c2").gt(lit(5)),
3187        );
3188        let expected = bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
3189
3190        assert_eq!(simplify(expr), expected);
3191
3192        // (c2 > 5) & ((c2 > 5) & (c1 < 6)) --> (c2 > 5) & (c1 < 6)
3193
3194        let expr = bitwise_and(
3195            col("c2").gt(lit(5)),
3196            bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
3197        );
3198        let expected = bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
3199        assert_eq!(simplify(expr), expected);
3200    }
3201
3202    #[test]
3203    fn test_simplify_composed_bitwise_or() {
3204        // ((c2 > 5) | (c1 < 6)) | (c2 > 5) --> (c2 > 5) | (c1 < 6)
3205
3206        let expr = bitwise_or(
3207            bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
3208            col("c2").gt(lit(5)),
3209        );
3210        let expected = bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
3211
3212        assert_eq!(simplify(expr), expected);
3213
3214        // (c2 > 5) | ((c2 > 5) | (c1 < 6)) --> (c2 > 5) | (c1 < 6)
3215
3216        let expr = bitwise_or(
3217            col("c2").gt(lit(5)),
3218            bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
3219        );
3220        let expected = bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
3221
3222        assert_eq!(simplify(expr), expected);
3223    }
3224
3225    #[test]
3226    fn test_simplify_composed_bitwise_xor() {
3227        // with an even number of the column "c2"
3228        // c2 ^ ((c2 ^ (c2 | c1)) ^ (c1 & c2)) --> (c2 | c1) ^ (c1 & c2)
3229
3230        let expr = bitwise_xor(
3231            col("c2_non_null"),
3232            bitwise_xor(
3233                bitwise_xor(
3234                    col("c2_non_null"),
3235                    bitwise_or(col("c2_non_null"), col("c1")),
3236                ),
3237                bitwise_and(col("c1"), col("c2_non_null")),
3238            ),
3239        );
3240
3241        let expected = bitwise_xor(
3242            bitwise_or(col("c2_non_null"), col("c1")),
3243            bitwise_and(col("c1"), col("c2_non_null")),
3244        );
3245
3246        assert_eq!(simplify(expr), expected);
3247
3248        // with an odd number of the column "c2"
3249        // c2 ^ (c2 ^ (c2 | c1)) ^ ((c1 & c2) ^ c2) --> c2 ^ ((c2 | c1) ^ (c1 & c2))
3250
3251        let expr = bitwise_xor(
3252            col("c2_non_null"),
3253            bitwise_xor(
3254                bitwise_xor(
3255                    col("c2_non_null"),
3256                    bitwise_or(col("c2_non_null"), col("c1")),
3257                ),
3258                bitwise_xor(
3259                    bitwise_and(col("c1"), col("c2_non_null")),
3260                    col("c2_non_null"),
3261                ),
3262            ),
3263        );
3264
3265        let expected = bitwise_xor(
3266            col("c2_non_null"),
3267            bitwise_xor(
3268                bitwise_or(col("c2_non_null"), col("c1")),
3269                bitwise_and(col("c1"), col("c2_non_null")),
3270            ),
3271        );
3272
3273        assert_eq!(simplify(expr), expected);
3274
3275        // with an even number of the column "c2"
3276        // ((c2 ^ (c2 | c1)) ^ (c1 & c2)) ^ c2 --> (c2 | c1) ^ (c1 & c2)
3277
3278        let expr = bitwise_xor(
3279            bitwise_xor(
3280                bitwise_xor(
3281                    col("c2_non_null"),
3282                    bitwise_or(col("c2_non_null"), col("c1")),
3283                ),
3284                bitwise_and(col("c1"), col("c2_non_null")),
3285            ),
3286            col("c2_non_null"),
3287        );
3288
3289        let expected = bitwise_xor(
3290            bitwise_or(col("c2_non_null"), col("c1")),
3291            bitwise_and(col("c1"), col("c2_non_null")),
3292        );
3293
3294        assert_eq!(simplify(expr), expected);
3295
3296        // with an odd number of the column "c2"
3297        // (c2 ^ (c2 | c1)) ^ ((c1 & c2) ^ c2) ^ c2 --> ((c2 | c1) ^ (c1 & c2)) ^ c2
3298
3299        let expr = bitwise_xor(
3300            bitwise_xor(
3301                bitwise_xor(
3302                    col("c2_non_null"),
3303                    bitwise_or(col("c2_non_null"), col("c1")),
3304                ),
3305                bitwise_xor(
3306                    bitwise_and(col("c1"), col("c2_non_null")),
3307                    col("c2_non_null"),
3308                ),
3309            ),
3310            col("c2_non_null"),
3311        );
3312
3313        let expected = bitwise_xor(
3314            bitwise_xor(
3315                bitwise_or(col("c2_non_null"), col("c1")),
3316                bitwise_and(col("c1"), col("c2_non_null")),
3317            ),
3318            col("c2_non_null"),
3319        );
3320
3321        assert_eq!(simplify(expr), expected);
3322    }
3323
3324    #[test]
3325    fn test_does_not_cancel_nullable_bitwise_xor() {
3326        let nullable = col("c3");
3327        let other = col("c3_non_null");
3328
3329        let expr = bitwise_xor(nullable.clone(), nullable.clone());
3330        assert_eq!(simplify(expr.clone()), expr);
3331
3332        let expr = bitwise_xor(
3333            bitwise_xor(nullable.clone(), other.clone()),
3334            nullable.clone(),
3335        );
3336        assert_eq!(simplify(expr.clone()), expr);
3337
3338        let expr = bitwise_xor(nullable.clone(), bitwise_xor(other, nullable));
3339        assert_eq!(simplify(expr.clone()), expr);
3340    }
3341
3342    #[test]
3343    fn test_preserve_arithmetic_negation() {
3344        let c3 = col("c3_non_null");
3345        let expressions = [
3346            (-c3.clone()) & c3.clone(),
3347            c3.clone() & (-c3.clone()),
3348            (-c3.clone()) | c3.clone(),
3349            c3.clone() | (-c3.clone()),
3350            (-c3.clone()) ^ c3.clone(),
3351            c3.clone() ^ (-c3.clone()),
3352            -bitwise_and(col("c3"), c3.clone()),
3353            -bitwise_or(col("c3"), c3.clone()),
3354        ];
3355
3356        for expr in expressions {
3357            assert_eq!(simplify(expr.clone()), expr);
3358        }
3359
3360        // Keep the pre-existing arithmetic double-negation simplification.
3361        assert_eq!(simplify(-(-c3.clone())), c3);
3362    }
3363
3364    #[test]
3365    fn test_simplify_bitwise_and_or() {
3366        // (c2 < 3) & ((c2 < 3) | c1) -> (c2 < 3)
3367        let expr = bitwise_and(
3368            col("c2_non_null").lt(lit(3)),
3369            bitwise_or(col("c2_non_null").lt(lit(3)), col("c1_non_null")),
3370        );
3371        let expected = col("c2_non_null").lt(lit(3));
3372
3373        assert_eq!(simplify(expr), expected);
3374    }
3375
3376    #[test]
3377    fn test_simplify_bitwise_or_and() {
3378        // (c2 < 3) | ((c2 < 3) & c1) -> (c2 < 3)
3379        let expr = bitwise_or(
3380            col("c2_non_null").lt(lit(3)),
3381            bitwise_and(col("c2_non_null").lt(lit(3)), col("c1_non_null")),
3382        );
3383        let expected = col("c2_non_null").lt(lit(3));
3384
3385        assert_eq!(simplify(expr), expected);
3386    }
3387
3388    #[test]
3389    fn test_simplify_simple_bitwise_and() {
3390        // (c2 > 5) & (c2 > 5) -> (c2 > 5)
3391        let expr = (col("c2").gt(lit(5))).bitand(col("c2").gt(lit(5)));
3392        let expected = col("c2").gt(lit(5));
3393
3394        assert_eq!(simplify(expr), expected);
3395    }
3396
3397    #[test]
3398    fn test_simplify_simple_bitwise_or() {
3399        // (c2 > 5) | (c2 > 5) -> (c2 > 5)
3400        let expr = (col("c2").gt(lit(5))).bitor(col("c2").gt(lit(5)));
3401        let expected = col("c2").gt(lit(5));
3402
3403        assert_eq!(simplify(expr), expected);
3404    }
3405
3406    #[test]
3407    fn test_simplify_simple_bitwise_xor() {
3408        // c4 ^ c4 -> 0
3409        let expr = (col("c4_non_null")).bitxor(col("c4_non_null"));
3410        let expected = lit(0u32);
3411
3412        assert_eq!(simplify(expr), expected);
3413
3414        // c3 ^ c3 -> 0
3415        let expr = col("c3_non_null").bitxor(col("c3_non_null"));
3416        let expected = lit(0i64);
3417
3418        assert_eq!(simplify(expr), expected);
3419    }
3420
3421    #[test]
3422    fn test_simplify_modulo_by_zero_non_null() {
3423        // because modulo by 0 maybe occur in short-circuit expression
3424        // so we should not simplify this, and throw error in runtime.
3425        let expr = col("c2_non_null") % lit(0);
3426        let expected = expr.clone();
3427
3428        assert_eq!(simplify(expr), expected);
3429    }
3430
3431    #[test]
3432    fn test_simplify_simple_and() {
3433        // (c2 > 5) AND (c2 > 5) -> (c2 > 5)
3434        let expr = (col("c2").gt(lit(5))).and(col("c2").gt(lit(5)));
3435        let expected = col("c2").gt(lit(5));
3436
3437        assert_eq!(simplify(expr), expected);
3438    }
3439
3440    #[test]
3441    fn test_simplify_composed_and() {
3442        // ((c2 > 5) AND (c1 < 6)) AND (c2 > 5)
3443        let expr = and(
3444            and(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
3445            col("c2").gt(lit(5)),
3446        );
3447        let expected = and(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
3448
3449        assert_eq!(simplify(expr), expected);
3450    }
3451
3452    #[test]
3453    fn test_simplify_negated_and() {
3454        // (c2 > 5) AND !(c2 > 5) --> (c2 > 5) AND (c2 <= 5)
3455        let expr = and(col("c2").gt(lit(5)), Expr::not(col("c2").gt(lit(5))));
3456        let expected = col("c2").gt(lit(5)).and(col("c2").lt_eq(lit(5)));
3457
3458        assert_eq!(simplify(expr), expected);
3459    }
3460
3461    #[test]
3462    fn test_simplify_or_and() {
3463        let l = col("c2").gt(lit(5));
3464        let r = and(col("c1").lt(lit(6)), col("c2").gt(lit(5)));
3465
3466        // (c2 > 5) OR ((c1 < 6) AND (c2 > 5))
3467        let expr = or(l.clone(), r.clone());
3468
3469        let expected = l.clone();
3470        assert_eq!(simplify(expr), expected);
3471
3472        // ((c1 < 6) AND (c2 > 5)) OR (c2 > 5)
3473        let expr = or(r, l);
3474        assert_eq!(simplify(expr), expected);
3475    }
3476
3477    #[test]
3478    fn test_simplify_or_and_non_null() {
3479        let l = col("c2_non_null").gt(lit(5));
3480        let r = and(col("c1_non_null").lt(lit(6)), col("c2_non_null").gt(lit(5)));
3481
3482        // (c2 > 5) OR ((c1 < 6) AND (c2 > 5)) --> c2 > 5
3483        let expr = or(l.clone(), r.clone());
3484
3485        // This is only true if `c1 < 6` is not nullable / can not be null.
3486        let expected = col("c2_non_null").gt(lit(5));
3487
3488        assert_eq!(simplify(expr), expected);
3489
3490        // ((c1 < 6) AND (c2 > 5)) OR (c2 > 5) --> c2 > 5
3491        let expr = or(l, r);
3492
3493        assert_eq!(simplify(expr), expected);
3494    }
3495
3496    #[test]
3497    fn test_simplify_and_or() {
3498        let l = col("c2").gt(lit(5));
3499        let r = or(col("c1").lt(lit(6)), col("c2").gt(lit(5)));
3500
3501        // (c2 > 5) AND ((c1 < 6) OR (c2 > 5)) --> c2 > 5
3502        let expr = and(l.clone(), r.clone());
3503
3504        let expected = l.clone();
3505        assert_eq!(simplify(expr), expected);
3506
3507        // ((c1 < 6) OR (c2 > 5)) AND (c2 > 5) --> c2 > 5
3508        let expr = and(r, l);
3509        assert_eq!(simplify(expr), expected);
3510    }
3511
3512    #[test]
3513    fn test_simplify_and_or_non_null() {
3514        let l = col("c2_non_null").gt(lit(5));
3515        let r = or(col("c1_non_null").lt(lit(6)), col("c2_non_null").gt(lit(5)));
3516
3517        // (c2 > 5) AND ((c1 < 6) OR (c2 > 5)) --> c2 > 5
3518        let expr = and(l.clone(), r.clone());
3519
3520        // This is only true if `c1 < 6` is not nullable / can not be null.
3521        let expected = col("c2_non_null").gt(lit(5));
3522
3523        assert_eq!(simplify(expr), expected);
3524
3525        // ((c1 < 6) OR (c2 > 5)) AND (c2 > 5) --> c2 > 5
3526        let expr = and(l, r);
3527
3528        assert_eq!(simplify(expr), expected);
3529    }
3530
3531    #[test]
3532    fn test_simplify_by_de_morgan_laws() {
3533        // Laws with logical operations
3534        // !(c3 AND c4) --> !c3 OR !c4
3535        let expr = and(col("c3"), col("c4")).not();
3536        let expected = or(col("c3").not(), col("c4").not());
3537        assert_eq!(simplify(expr), expected);
3538        // !(c3 OR c4) --> !c3 AND !c4
3539        let expr = or(col("c3"), col("c4")).not();
3540        let expected = and(col("c3").not(), col("c4").not());
3541        assert_eq!(simplify(expr), expected);
3542        // !(!c3) --> c3
3543        let expr = col("c3").not().not();
3544        let expected = col("c3");
3545        assert_eq!(simplify(expr), expected);
3546    }
3547
3548    #[test]
3549    fn test_simplify_null_and_false() {
3550        let expr = and(lit_bool_null(), lit(false));
3551        let expr_eq = lit(false);
3552
3553        assert_eq!(simplify(expr), expr_eq);
3554    }
3555
3556    #[test]
3557    fn test_simplify_divide_null_by_null() {
3558        let null = lit(ScalarValue::Int32(None));
3559        let expr_plus = null.clone() / null.clone();
3560        let expr_eq = null;
3561
3562        assert_eq!(simplify(expr_plus), expr_eq);
3563    }
3564
3565    #[test]
3566    fn test_simplify_simplify_arithmetic_expr() {
3567        let expr_plus = lit(1) + lit(1);
3568
3569        assert_eq!(simplify(expr_plus), lit(2));
3570    }
3571
3572    #[test]
3573    fn test_simplify_simplify_eq_expr() {
3574        let expr_eq = binary_expr(lit(1), Operator::Eq, lit(1));
3575
3576        assert_eq!(simplify(expr_eq), lit(true));
3577    }
3578
3579    #[test]
3580    fn test_constant_regex_respects_planning_budget() {
3581        // Small regexes retain the common-case constant folding behavior.
3582        assert_eq!(simplify(regex_match(lit("aaaaa"), lit("^a+$"))), lit(true));
3583
3584        // Six nested repetitions fit under the runtime regex limit, but exceed
3585        // the smaller planning budget and therefore remain for execution.
3586        let pattern = "a{5}{5}{5}{5}{5}{5}";
3587        let binary_expr = regex_match(lit("aaaaa"), lit(pattern));
3588        assert_eq!(simplify(binary_expr.clone()), binary_expr);
3589
3590        // Deferring a subtree must also prevent an evaluatable parent from
3591        // invoking it indirectly during constant folding.
3592        let aliased = regex_match(lit("aaaaa"), lit(pattern)).alias("matched");
3593        assert_eq!(simplify(aliased.clone()), aliased);
3594
3595        #[derive(Debug, PartialEq, Eq, Hash)]
3596        struct DeferredConstUdf {
3597            signature: Signature,
3598        }
3599
3600        impl ScalarUDFImpl for DeferredConstUdf {
3601            fn name(&self) -> &str {
3602                "deferred_const"
3603            }
3604
3605            fn signature(&self) -> &Signature {
3606                &self.signature
3607            }
3608
3609            fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
3610                Ok(DataType::Boolean)
3611            }
3612
3613            fn invoke_with_args(
3614                &self,
3615                _args: ScalarFunctionArgs,
3616            ) -> Result<ColumnarValue> {
3617                panic!("deferred UDF must not be evaluated during planning")
3618            }
3619
3620            fn should_evaluate_const(&self, _args: &[&ScalarValue]) -> bool {
3621                false
3622            }
3623        }
3624
3625        // UDFs can use the same hook when their literal inputs are expensive.
3626        let udf = ScalarUDF::new_from_impl(DeferredConstUdf {
3627            signature: Signature::exact(vec![DataType::Utf8], Volatility::Immutable),
3628        });
3629        let udf_expr = udf.call(vec![lit("value")]);
3630        assert_eq!(simplify(udf_expr.clone()), udf_expr);
3631    }
3632
3633    #[test]
3634    fn test_simplify_regex() {
3635        // malformed regex
3636        assert_contains!(
3637            try_simplify(regex_match(col("c1"), lit("foo{")))
3638                .unwrap_err()
3639                .to_string(),
3640            "regex parse error"
3641        );
3642
3643        // unsupported cases
3644        assert_no_change(regex_match(col("c1"), lit("foo.*")));
3645        assert_no_change(regex_match(col("c1"), lit("(foo)")));
3646        assert_no_change(regex_match(col("c1"), lit("%")));
3647        assert_no_change(regex_match(col("c1"), lit("_")));
3648        assert_no_change(regex_match(col("c1"), lit("f%o")));
3649        assert_no_change(regex_match(col("c1"), lit("^f%o")));
3650        assert_no_change(regex_match(col("c1"), lit("f_o")));
3651
3652        // empty cases
3653        assert_change(
3654            regex_match(col("c1"), lit("")),
3655            if_not_null(col("c1"), true),
3656        );
3657        assert_change(
3658            regex_not_match(col("c1"), lit("")),
3659            if_not_null(col("c1"), false),
3660        );
3661        assert_change(
3662            regex_imatch(col("c1"), lit("")),
3663            if_not_null(col("c1"), true),
3664        );
3665        assert_change(
3666            regex_not_imatch(col("c1"), lit("")),
3667            if_not_null(col("c1"), false),
3668        );
3669
3670        // single character
3671        assert_change(regex_match(col("c1"), lit("x")), col("c1").like(lit("%x%")));
3672
3673        // single word
3674        assert_change(
3675            regex_match(col("c1"), lit("foo")),
3676            col("c1").like(lit("%foo%")),
3677        );
3678
3679        // regular expressions that match an exact literal
3680        assert_change(regex_match(col("c1"), lit("^$")), col("c1").eq(lit("")));
3681        assert_change(
3682            regex_not_match(col("c1"), lit("^$")),
3683            col("c1").not_eq(lit("")),
3684        );
3685        assert_change(
3686            regex_match(col("c1"), lit("^foo$")),
3687            col("c1").eq(lit("foo")),
3688        );
3689        assert_change(
3690            regex_not_match(col("c1"), lit("^foo$")),
3691            col("c1").not_eq(lit("foo")),
3692        );
3693
3694        // regular expressions that match exact captured literals
3695        assert_change(
3696            regex_match(col("c1"), lit("^(foo|bar)$")),
3697            col("c1").eq(lit("foo")).or(col("c1").eq(lit("bar"))),
3698        );
3699        assert_change(
3700            regex_not_match(col("c1"), lit("^(foo|bar)$")),
3701            col("c1")
3702                .not_eq(lit("foo"))
3703                .and(col("c1").not_eq(lit("bar"))),
3704        );
3705        assert_change(
3706            regex_match(col("c1"), lit("^(foo)$")),
3707            col("c1").eq(lit("foo")),
3708        );
3709        assert_change(
3710            regex_match(col("c1"), lit("^(foo|bar|baz)$")),
3711            ((col("c1").eq(lit("foo"))).or(col("c1").eq(lit("bar"))))
3712                .or(col("c1").eq(lit("baz"))),
3713        );
3714        assert_change(
3715            regex_match(col("c1"), lit("^(foo|bar|baz|qux)$")),
3716            col("c1")
3717                .in_list(vec![lit("foo"), lit("bar"), lit("baz"), lit("qux")], false),
3718        );
3719        assert_change(
3720            regex_match(col("c1"), lit("^(fo_o)$")),
3721            col("c1").eq(lit("fo_o")),
3722        );
3723        assert_change(
3724            regex_match(col("c1"), lit("^(fo_o)$")),
3725            col("c1").eq(lit("fo_o")),
3726        );
3727        assert_change(
3728            regex_match(col("c1"), lit("^(fo_o|ba_r)$")),
3729            col("c1").eq(lit("fo_o")).or(col("c1").eq(lit("ba_r"))),
3730        );
3731        assert_change(
3732            regex_not_match(col("c1"), lit("^(fo_o|ba_r)$")),
3733            col("c1")
3734                .not_eq(lit("fo_o"))
3735                .and(col("c1").not_eq(lit("ba_r"))),
3736        );
3737        assert_change(
3738            regex_match(col("c1"), lit("^(fo_o|ba_r|ba_z)$")),
3739            ((col("c1").eq(lit("fo_o"))).or(col("c1").eq(lit("ba_r"))))
3740                .or(col("c1").eq(lit("ba_z"))),
3741        );
3742        assert_change(
3743            regex_match(col("c1"), lit("^(fo_o|ba_r|baz|qu_x)$")),
3744            col("c1").in_list(
3745                vec![lit("fo_o"), lit("ba_r"), lit("baz"), lit("qu_x")],
3746                false,
3747            ),
3748        );
3749
3750        // regular expressions that mismatch captured literals
3751        assert_no_change(regex_match(col("c1"), lit("(foo|bar)")));
3752        assert_no_change(regex_match(col("c1"), lit("(foo|bar)*")));
3753        assert_no_change(regex_match(col("c1"), lit("(fo_o|b_ar)")));
3754        assert_no_change(regex_match(col("c1"), lit("(foo|ba_r)*")));
3755        assert_no_change(regex_match(col("c1"), lit("(fo_o|ba_r)*")));
3756        assert_no_change(regex_match(col("c1"), lit("^(foo|bar)*")));
3757        assert_no_change(regex_match(col("c1"), lit("^(foo)(bar)$")));
3758        assert_no_change(regex_match(col("c1"), lit("^")));
3759        assert_no_change(regex_match(col("c1"), lit("$")));
3760        assert_no_change(regex_match(col("c1"), lit("$^")));
3761        assert_no_change(regex_match(col("c1"), lit("$foo^")));
3762
3763        // regular expressions that match a partial literal
3764        assert_change(
3765            regex_match(col("c1"), lit("^foo")),
3766            col("c1").like(lit("foo%")),
3767        );
3768        assert_change(
3769            regex_match(col("c1"), lit("foo$")),
3770            col("c1").like(lit("%foo")),
3771        );
3772        assert_change(
3773            regex_match(col("c1"), lit("^foo|bar$")),
3774            col("c1").like(lit("foo%")).or(col("c1").like(lit("%bar"))),
3775        );
3776
3777        // OR-chain
3778        assert_change(
3779            regex_match(col("c1"), lit("foo|bar|baz")),
3780            col("c1")
3781                .like(lit("%foo%"))
3782                .or(col("c1").like(lit("%bar%")))
3783                .or(col("c1").like(lit("%baz%"))),
3784        );
3785        assert_change(
3786            regex_match(col("c1"), lit("foo|x|baz")),
3787            col("c1")
3788                .like(lit("%foo%"))
3789                .or(col("c1").like(lit("%x%")))
3790                .or(col("c1").like(lit("%baz%"))),
3791        );
3792        assert_change(
3793            regex_not_match(col("c1"), lit("foo|bar|baz")),
3794            col("c1")
3795                .not_like(lit("%foo%"))
3796                .and(col("c1").not_like(lit("%bar%")))
3797                .and(col("c1").not_like(lit("%baz%"))),
3798        );
3799        // both anchored expressions (translated to equality) and unanchored
3800        assert_change(
3801            regex_match(col("c1"), lit("foo|^x$|baz")),
3802            col("c1")
3803                .like(lit("%foo%"))
3804                .or(col("c1").eq(lit("x")))
3805                .or(col("c1").like(lit("%baz%"))),
3806        );
3807        assert_change(
3808            regex_not_match(col("c1"), lit("foo|^bar$|baz")),
3809            col("c1")
3810                .not_like(lit("%foo%"))
3811                .and(col("c1").not_eq(lit("bar")))
3812                .and(col("c1").not_like(lit("%baz%"))),
3813        );
3814        // Too many patterns (MAX_REGEX_ALTERNATIONS_EXPANSION)
3815        assert_no_change(regex_match(col("c1"), lit("foo|bar|baz|blarg|bozo|etc")));
3816    }
3817
3818    #[test]
3819    fn test_simplify_not_regex_match() {
3820        let pattern = || lit("foo.*");
3821
3822        // NOT (c1 ~ pattern)  --> c1 !~ pattern
3823        assert_eq!(
3824            simplify(regex_match(col("c1"), pattern()).not()),
3825            regex_not_match(col("c1"), pattern()),
3826        );
3827        // NOT (c1 !~ pattern) --> c1 ~ pattern
3828        assert_eq!(
3829            simplify(regex_not_match(col("c1"), pattern()).not()),
3830            regex_match(col("c1"), pattern()),
3831        );
3832        // NOT (c1 ~* pattern)  --> c1 !~* pattern
3833        assert_eq!(
3834            simplify(regex_imatch(col("c1"), pattern()).not()),
3835            regex_not_imatch(col("c1"), pattern()),
3836        );
3837        // NOT (c1 !~* pattern) --> c1 ~* pattern
3838        assert_eq!(
3839            simplify(regex_not_imatch(col("c1"), pattern()).not()),
3840            regex_imatch(col("c1"), pattern()),
3841        );
3842    }
3843
3844    #[track_caller]
3845    fn assert_no_change(expr: Expr) {
3846        let optimized = simplify(expr.clone());
3847        assert_eq!(expr, optimized);
3848    }
3849
3850    #[track_caller]
3851    fn assert_change(expr: Expr, expected: Expr) {
3852        let optimized = simplify(expr);
3853        assert_eq!(optimized, expected);
3854    }
3855
3856    fn regex_match(left: Expr, right: Expr) -> Expr {
3857        Expr::BinaryExpr(BinaryExpr {
3858            left: Box::new(left),
3859            op: Operator::RegexMatch,
3860            right: Box::new(right),
3861        })
3862    }
3863
3864    fn regex_not_match(left: Expr, right: Expr) -> Expr {
3865        Expr::BinaryExpr(BinaryExpr {
3866            left: Box::new(left),
3867            op: Operator::RegexNotMatch,
3868            right: Box::new(right),
3869        })
3870    }
3871
3872    fn regex_imatch(left: Expr, right: Expr) -> Expr {
3873        Expr::BinaryExpr(BinaryExpr {
3874            left: Box::new(left),
3875            op: Operator::RegexIMatch,
3876            right: Box::new(right),
3877        })
3878    }
3879
3880    fn regex_not_imatch(left: Expr, right: Expr) -> Expr {
3881        Expr::BinaryExpr(BinaryExpr {
3882            left: Box::new(left),
3883            op: Operator::RegexNotIMatch,
3884            right: Box::new(right),
3885        })
3886    }
3887
3888    // ------------------------------
3889    // ----- Simplifier tests -------
3890    // ------------------------------
3891
3892    fn try_simplify(expr: Expr) -> Result<Expr> {
3893        let schema = expr_test_schema();
3894        let simplifier =
3895            ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build());
3896        simplifier.simplify(expr)
3897    }
3898
3899    fn coerce(expr: Expr) -> Expr {
3900        let schema = expr_test_schema();
3901        let simplifier = ExprSimplifier::new(
3902            SimplifyContext::builder()
3903                .with_schema(Arc::clone(&schema))
3904                .build(),
3905        );
3906        simplifier.coerce(expr, schema.as_ref()).unwrap()
3907    }
3908
3909    fn simplify(expr: Expr) -> Expr {
3910        try_simplify(expr).unwrap()
3911    }
3912
3913    fn simplify_no_canonicalize(expr: Expr) -> Expr {
3914        simplify_no_canonicalize_with_cycle_count(expr).0
3915    }
3916
3917    fn simplify_no_canonicalize_with_cycle_count(expr: Expr) -> (Expr, u32) {
3918        let schema = expr_test_schema();
3919        let (transformed, count) =
3920            ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build())
3921                .with_canonicalize(false)
3922                .simplify_with_cycle_count_transformed(expr)
3923                .unwrap();
3924        (transformed.data, count)
3925    }
3926
3927    fn try_simplify_with_cycle_count(expr: Expr) -> Result<(Expr, u32)> {
3928        let schema = expr_test_schema();
3929        let simplifier =
3930            ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build());
3931        let (expr, count) = simplifier.simplify_with_cycle_count_transformed(expr)?;
3932        Ok((expr.data, count))
3933    }
3934
3935    fn simplify_with_cycle_count(expr: Expr) -> (Expr, u32) {
3936        try_simplify_with_cycle_count(expr).unwrap()
3937    }
3938
3939    fn simplify_with_guarantee(
3940        expr: Expr,
3941        guarantees: Vec<(Expr, NullableInterval)>,
3942    ) -> Expr {
3943        let schema = expr_test_schema();
3944        let simplifier =
3945            ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build())
3946                .with_guarantees(guarantees);
3947        simplifier.simplify(expr).unwrap()
3948    }
3949
3950    fn expr_test_schema() -> DFSchemaRef {
3951        static EXPR_TEST_SCHEMA: LazyLock<DFSchemaRef> = LazyLock::new(|| {
3952            Arc::new(
3953                DFSchema::from_unqualified_fields(
3954                    vec![
3955                        Field::new("c1", DataType::Utf8, true),
3956                        Field::new("c2", DataType::Boolean, true),
3957                        Field::new("c3", DataType::Int64, true),
3958                        Field::new("c4", DataType::UInt32, true),
3959                        Field::new("c1_non_null", DataType::Utf8, false),
3960                        Field::new("c2_non_null", DataType::Boolean, false),
3961                        Field::new("c3_non_null", DataType::Int64, false),
3962                        Field::new("c4_non_null", DataType::UInt32, false),
3963                        Field::new("c5", DataType::FixedSizeBinary(3), true),
3964                    ]
3965                    .into(),
3966                    HashMap::new(),
3967                )
3968                .unwrap(),
3969            )
3970        });
3971        Arc::clone(&EXPR_TEST_SCHEMA)
3972    }
3973
3974    #[test]
3975    fn simplify_expr_null_comparison() {
3976        // x = null is always null
3977        assert_eq!(
3978            simplify(lit(true).eq(lit(ScalarValue::Boolean(None)))),
3979            lit(ScalarValue::Boolean(None)),
3980        );
3981
3982        // null != null is always null
3983        assert_eq!(
3984            simplify(
3985                lit(ScalarValue::Boolean(None)).not_eq(lit(ScalarValue::Boolean(None)))
3986            ),
3987            lit(ScalarValue::Boolean(None)),
3988        );
3989
3990        // x != null is always null
3991        assert_eq!(
3992            simplify(col("c2").not_eq(lit(ScalarValue::Boolean(None)))),
3993            lit(ScalarValue::Boolean(None)),
3994        );
3995
3996        // null = x is always null
3997        assert_eq!(
3998            simplify(lit(ScalarValue::Boolean(None)).eq(col("c2"))),
3999            lit(ScalarValue::Boolean(None)),
4000        );
4001    }
4002
4003    #[test]
4004    fn simplify_expr_is_not_null() {
4005        assert_eq!(
4006            simplify(Expr::IsNotNull(Box::new(col("c1")))),
4007            Expr::IsNotNull(Box::new(col("c1")))
4008        );
4009
4010        // 'c1_non_null IS NOT NULL' is always true
4011        assert_eq!(
4012            simplify(Expr::IsNotNull(Box::new(col("c1_non_null")))),
4013            lit(true)
4014        );
4015    }
4016
4017    #[test]
4018    fn simplify_expr_is_null() {
4019        assert_eq!(
4020            simplify(Expr::IsNull(Box::new(col("c1")))),
4021            Expr::IsNull(Box::new(col("c1")))
4022        );
4023
4024        // 'c1_non_null IS NULL' is always false
4025        assert_eq!(
4026            simplify(Expr::IsNull(Box::new(col("c1_non_null")))),
4027            lit(false)
4028        );
4029    }
4030
4031    #[test]
4032    fn simplify_scalar_subquery_is_null() {
4033        let possibly_empty = LogicalPlanBuilder::empty(false)
4034            .project(vec![lit(1)])
4035            .unwrap()
4036            .build()
4037            .unwrap();
4038        let possibly_empty = scalar_subquery(Arc::new(possibly_empty));
4039
4040        assert_eq!(
4041            simplify(possibly_empty.clone().is_null()),
4042            possibly_empty.is_null()
4043        );
4044
4045        let always_one = LogicalPlanBuilder::empty(true)
4046            .project(vec![lit(1)])
4047            .unwrap()
4048            .build()
4049            .unwrap();
4050        let always_one = scalar_subquery(Arc::new(always_one));
4051        assert_eq!(simplify(always_one.is_null()), lit(false));
4052    }
4053
4054    #[test]
4055    fn simplify_expr_is_unknown() {
4056        assert_eq!(simplify(col("c2").is_unknown()), col("c2").is_unknown(),);
4057
4058        // 'c2_non_null is unknown' is always false
4059        assert_eq!(simplify(col("c2_non_null").is_unknown()), lit(false));
4060    }
4061
4062    #[test]
4063    fn simplify_expr_is_not_known() {
4064        assert_eq!(
4065            simplify(col("c2").is_not_unknown()),
4066            col("c2").is_not_unknown()
4067        );
4068
4069        // 'c2_non_null is not unknown' is always true
4070        assert_eq!(simplify(col("c2_non_null").is_not_unknown()), lit(true));
4071    }
4072
4073    #[test]
4074    fn simplify_expr_eq() {
4075        let schema = expr_test_schema();
4076        assert_eq!(col("c2").get_type(&schema).unwrap(), DataType::Boolean);
4077
4078        // true = true -> true
4079        assert_eq!(simplify(lit(true).eq(lit(true))), lit(true));
4080
4081        // true = false -> false
4082        assert_eq!(simplify(lit(true).eq(lit(false))), lit(false),);
4083
4084        // c2 = true -> c2
4085        assert_eq!(simplify(col("c2").eq(lit(true))), col("c2"));
4086
4087        // c2 = false => !c2
4088        assert_eq!(simplify(col("c2").eq(lit(false))), col("c2").not(),);
4089    }
4090
4091    #[test]
4092    fn simplify_expr_eq_skip_nonboolean_type() {
4093        let schema = expr_test_schema();
4094
4095        // When one of the operand is not of boolean type, folding the
4096        // other boolean constant will change return type of
4097        // expression to non-boolean.
4098        //
4099        // Make sure c1 column to be used in tests is not boolean type
4100        assert_eq!(col("c1").get_type(&schema).unwrap(), DataType::Utf8);
4101
4102        // don't fold c1 = foo
4103        assert_eq!(simplify(col("c1").eq(lit("foo"))), col("c1").eq(lit("foo")),);
4104    }
4105
4106    #[test]
4107    fn simplify_expr_not_eq() {
4108        let schema = expr_test_schema();
4109
4110        assert_eq!(col("c2").get_type(&schema).unwrap(), DataType::Boolean);
4111
4112        // c2 != true -> !c2
4113        assert_eq!(simplify(col("c2").not_eq(lit(true))), col("c2").not(),);
4114
4115        // c2 != false -> c2
4116        assert_eq!(simplify(col("c2").not_eq(lit(false))), col("c2"),);
4117
4118        // test constant
4119        assert_eq!(simplify(lit(true).not_eq(lit(true))), lit(false),);
4120
4121        assert_eq!(simplify(lit(true).not_eq(lit(false))), lit(true),);
4122    }
4123
4124    #[test]
4125    fn simplify_expr_not_eq_skip_nonboolean_type() {
4126        let schema = expr_test_schema();
4127
4128        // when one of the operand is not of boolean type, folding the
4129        // other boolean constant will change return type of
4130        // expression to non-boolean.
4131        assert_eq!(col("c1").get_type(&schema).unwrap(), DataType::Utf8);
4132
4133        assert_eq!(
4134            simplify(col("c1").not_eq(lit("foo"))),
4135            col("c1").not_eq(lit("foo")),
4136        );
4137    }
4138
4139    #[test]
4140    fn simplify_literal_case_equality() {
4141        // CASE WHEN c2 != false THEN "ok" ELSE "not_ok"
4142        let simple_case = Expr::Case(Case::new(
4143            None,
4144            vec![(
4145                Box::new(col("c2_non_null").not_eq(lit(false))),
4146                Box::new(lit("ok")),
4147            )],
4148            Some(Box::new(lit("not_ok"))),
4149        ));
4150
4151        // CASE WHEN c2 != false THEN "ok" ELSE "not_ok" == "ok"
4152        // -->
4153        // CASE WHEN c2 != false THEN "ok" == "ok" ELSE "not_ok" == "ok"
4154        // -->
4155        // CASE WHEN c2 != false THEN true ELSE false
4156        // -->
4157        // c2
4158        assert_eq!(
4159            simplify(binary_expr(simple_case.clone(), Operator::Eq, lit("ok"),)),
4160            col("c2_non_null"),
4161        );
4162
4163        // CASE WHEN c2 != false THEN "ok" ELSE "not_ok" != "ok"
4164        // -->
4165        // NOT(CASE WHEN c2 != false THEN "ok" == "ok" ELSE "not_ok" == "ok")
4166        // -->
4167        // NOT(CASE WHEN c2 != false THEN true ELSE false)
4168        // -->
4169        // NOT(c2)
4170        assert_eq!(
4171            simplify(binary_expr(simple_case, Operator::NotEq, lit("ok"),)),
4172            not(col("c2_non_null")),
4173        );
4174
4175        let complex_case = Expr::Case(Case::new(
4176            None,
4177            vec![
4178                (
4179                    Box::new(col("c1").eq(lit("inboxed"))),
4180                    Box::new(lit("pending")),
4181                ),
4182                (
4183                    Box::new(col("c1").eq(lit("scheduled"))),
4184                    Box::new(lit("pending")),
4185                ),
4186                (
4187                    Box::new(col("c1").eq(lit("completed"))),
4188                    Box::new(lit("completed")),
4189                ),
4190                (
4191                    Box::new(col("c1").eq(lit("paused"))),
4192                    Box::new(lit("paused")),
4193                ),
4194                (Box::new(col("c2")), Box::new(lit("running"))),
4195                (
4196                    Box::new(col("c1").eq(lit("invoked")).and(col("c3").gt(lit(0)))),
4197                    Box::new(lit("backing-off")),
4198                ),
4199            ],
4200            Some(Box::new(lit("ready"))),
4201        ));
4202
4203        // Comparisons still fold into literal outputs, but later WHEN conditions must
4204        // remain conditional: they are not columns or literals.
4205        for (op, value, outputs) in [
4206            (
4207                Operator::Eq,
4208                "completed",
4209                [false, false, true, false, false, false, false],
4210            ),
4211            (
4212                Operator::NotEq,
4213                "completed",
4214                [true, true, false, true, true, true, true],
4215            ),
4216            (
4217                Operator::Eq,
4218                "running",
4219                [false, false, false, false, true, false, false],
4220            ),
4221            (
4222                Operator::Eq,
4223                "ready",
4224                [false, false, false, false, false, false, true],
4225            ),
4226            (
4227                Operator::NotEq,
4228                "ready",
4229                [true, true, true, true, true, true, false],
4230            ),
4231        ] {
4232            let Expr::Case(mut expected) = complex_case.clone() else {
4233                unreachable!()
4234            };
4235            for ((_, then), value) in expected.when_then_expr.iter_mut().zip(outputs) {
4236                **then = lit(value);
4237            }
4238            expected.else_expr = Some(Box::new(lit(outputs[6])));
4239            assert_eq!(
4240                simplify(binary_expr(complex_case.clone(), op, lit(value))),
4241                Expr::Case(expected)
4242            );
4243        }
4244    }
4245
4246    #[test]
4247    fn simplify_case_preserves_conditional_expressions() {
4248        let fallible =
4249            Expr::Cast(Cast::new(Box::new(col("c1")), DataType::Int32)).gt(lit(0_i32));
4250        let volatile = Expr::ScalarFunction(ScalarFunction::new_udf(
4251            Arc::new(ScalarUDF::new_from_impl(VolatileUdf::new())),
4252            vec![],
4253        ));
4254        for expr in [
4255            Expr::Case(Case::new(
4256                None,
4257                vec![(Box::new(fallible.clone()), Box::new(lit(false)))],
4258                Some(Box::new(lit(false))),
4259            )),
4260            Expr::Case(Case::new(
4261                None,
4262                vec![(Box::new(col("c2")), Box::new(fallible.clone()))],
4263                Some(Box::new(lit(false))),
4264            )),
4265            Expr::Case(Case::new(
4266                None,
4267                vec![(Box::new(col("c2")), Box::new(lit(true)))],
4268                Some(Box::new(fallible.clone())),
4269            )),
4270            Expr::Case(Case::new(
4271                None,
4272                vec![
4273                    (Box::new(col("c2")), Box::new(lit(false))),
4274                    (Box::new(fallible), Box::new(lit(true))),
4275                ],
4276                Some(Box::new(lit(false))),
4277            )),
4278            Expr::Case(Case::new(
4279                None,
4280                vec![(Box::new(volatile.gt(lit(0_i16))), Box::new(lit(true)))],
4281                Some(Box::new(col("c2"))),
4282            )),
4283        ] {
4284            assert_eq!(simplify(expr.clone()), expr);
4285        }
4286    }
4287
4288    #[test]
4289    fn simplify_expr_case_when_then_else() {
4290        // CASE WHEN c2 != false THEN "ok" == "not_ok" ELSE c2 == true
4291        // -->
4292        // CASE WHEN c2 THEN false ELSE c2
4293        // -->
4294        // false
4295        assert_eq!(
4296            simplify(Expr::Case(Case::new(
4297                None,
4298                vec![(
4299                    Box::new(col("c2_non_null").not_eq(lit(false))),
4300                    Box::new(lit("ok").eq(lit("not_ok"))),
4301                )],
4302                Some(Box::new(col("c2_non_null").eq(lit(true)))),
4303            ))),
4304            lit(false) // #1716
4305        );
4306
4307        // CASE WHEN c2 != false THEN "ok" == "ok" ELSE c2
4308        // -->
4309        // CASE WHEN c2 THEN true ELSE c2
4310        // -->
4311        // c2
4312        //
4313        // Need to call simplify 2x due to
4314        // https://github.com/apache/datafusion/issues/1160
4315        assert_eq!(
4316            simplify(simplify(Expr::Case(Case::new(
4317                None,
4318                vec![(
4319                    Box::new(col("c2_non_null").not_eq(lit(false))),
4320                    Box::new(lit("ok").eq(lit("ok"))),
4321                )],
4322                Some(Box::new(col("c2_non_null").eq(lit(true)))),
4323            )))),
4324            col("c2_non_null")
4325        );
4326
4327        // CASE WHEN ISNULL(c2) THEN true ELSE c2
4328        // -->
4329        // Preserve CASE because the WHEN expression is outside the conservative
4330        // column/literal subset.
4331        let expected = Expr::Case(Case::new(
4332            None,
4333            vec![(Box::new(col("c2").is_null()), Box::new(lit(true)))],
4334            Some(Box::new(col("c2"))),
4335        ));
4336        assert_eq!(
4337            simplify(simplify(Expr::Case(Case::new(
4338                None,
4339                vec![(Box::new(col("c2").is_null()), Box::new(lit(true)),)],
4340                Some(Box::new(col("c2"))),
4341            )))),
4342            expected
4343        );
4344
4345        // CASE WHEN c1 then true WHEN c2 then false ELSE true
4346        // --> c1 OR (NOT(c1) AND c2 AND FALSE) OR (NOT(c1 OR c2) AND TRUE)
4347        // --> c1 OR (NOT(c1) AND NOT(c2))
4348        // --> c1 OR NOT(c2)
4349        //
4350        // Need to call simplify 2x due to
4351        // https://github.com/apache/datafusion/issues/1160
4352        assert_eq!(
4353            simplify(simplify(Expr::Case(Case::new(
4354                None,
4355                vec![
4356                    (Box::new(col("c1_non_null")), Box::new(lit(true)),),
4357                    (Box::new(col("c2_non_null")), Box::new(lit(false)),),
4358                ],
4359                Some(Box::new(lit(true))),
4360            )))),
4361            col("c1_non_null").or(col("c1_non_null").not().and(col("c2_non_null").not()))
4362        );
4363
4364        // CASE WHEN c1 then true WHEN c2 then true ELSE false
4365        // --> c1 OR (NOT(c1) AND c2 AND TRUE) OR (NOT(c1 OR c2) AND FALSE)
4366        // --> c1 OR (NOT(c1) AND c2)
4367        // --> c1 OR c2
4368        //
4369        // Need to call simplify 2x due to
4370        // https://github.com/apache/datafusion/issues/1160
4371        assert_eq!(
4372            simplify(simplify(Expr::Case(Case::new(
4373                None,
4374                vec![
4375                    (Box::new(col("c1_non_null")), Box::new(lit(true)),),
4376                    (Box::new(col("c2_non_null")), Box::new(lit(false)),),
4377                ],
4378                Some(Box::new(lit(true))),
4379            )))),
4380            col("c1_non_null").or(col("c1_non_null").not().and(col("c2_non_null").not()))
4381        );
4382
4383        // Preserve CASE with a non-leaf WHEN condition, with or without ELSE.
4384        for expr in [
4385            Expr::Case(Case::new(
4386                None,
4387                vec![(Box::new(col("c3").gt(lit(0_i64))), Box::new(lit(true)))],
4388                None,
4389            )),
4390            Expr::Case(Case::new(
4391                None,
4392                vec![(Box::new(col("c3").gt(lit(0_i64))), Box::new(lit(true)))],
4393                Some(Box::new(lit(false))),
4394            )),
4395        ] {
4396            assert_eq!(simplify(simplify(expr.clone())), expr);
4397        }
4398    }
4399
4400    #[test]
4401    fn simplify_expr_case_when_first_true() {
4402        // CASE WHEN true THEN 1 ELSE c1 END --> 1
4403        assert_eq!(
4404            simplify(Expr::Case(Case::new(
4405                None,
4406                vec![(Box::new(lit(true)), Box::new(lit(1)),)],
4407                Some(Box::new(col("c1"))),
4408            ))),
4409            lit(1)
4410        );
4411
4412        // CASE WHEN true THEN col('a') ELSE col('b') END --> col('a')
4413        assert_eq!(
4414            simplify(Expr::Case(Case::new(
4415                None,
4416                vec![(Box::new(lit(true)), Box::new(lit("a")),)],
4417                Some(Box::new(lit("b"))),
4418            ))),
4419            lit("a")
4420        );
4421
4422        // CASE WHEN true THEN col('a') WHEN col('x') > 5 THEN col('b') ELSE col('c') END --> col('a')
4423        assert_eq!(
4424            simplify(Expr::Case(Case::new(
4425                None,
4426                vec![
4427                    (Box::new(lit(true)), Box::new(lit("a"))),
4428                    (Box::new(lit("x").gt(lit(5))), Box::new(lit("b"))),
4429                ],
4430                Some(Box::new(lit("c"))),
4431            ))),
4432            lit("a")
4433        );
4434
4435        // CASE WHEN true THEN col('a') END --> col('a') (no else clause)
4436        assert_eq!(
4437            simplify(Expr::Case(Case::new(
4438                None,
4439                vec![(Box::new(lit(true)), Box::new(lit("a")),)],
4440                None,
4441            ))),
4442            lit("a")
4443        );
4444
4445        // Negative test: CASE WHEN c2 THEN 1 ELSE 2 END should not be simplified
4446        let expr = Expr::Case(Case::new(
4447            None,
4448            vec![(Box::new(col("c2")), Box::new(lit(1)))],
4449            Some(Box::new(lit(2))),
4450        ));
4451        assert_eq!(simplify(expr.clone()), expr);
4452
4453        // Negative test: CASE WHEN false THEN 1 ELSE 2 END should not use this rule
4454        let expr = Expr::Case(Case::new(
4455            None,
4456            vec![(Box::new(lit(false)), Box::new(lit(1)))],
4457            Some(Box::new(lit(2))),
4458        ));
4459        assert_ne!(simplify(expr), lit(1));
4460
4461        // Negative test: CASE WHEN col('c1') > 5 THEN 1 ELSE 2 END should not be simplified
4462        let expr = Expr::Case(Case::new(
4463            None,
4464            vec![(Box::new(col("c1").gt(lit(5))), Box::new(lit(1)))],
4465            Some(Box::new(lit(2))),
4466        ));
4467        assert_eq!(simplify(expr.clone()), expr);
4468    }
4469
4470    #[test]
4471    fn simplify_expr_case_when_any_true() {
4472        // CASE WHEN c3 > 0 THEN 'a' WHEN true THEN 'b' ELSE 'c' END --> CASE WHEN c3 > 0 THEN 'a' ELSE 'b' END
4473        assert_eq!(
4474            simplify(Expr::Case(Case::new(
4475                None,
4476                vec![
4477                    (Box::new(col("c3").gt(lit(0))), Box::new(lit("a"))),
4478                    (Box::new(lit(true)), Box::new(lit("b"))),
4479                ],
4480                Some(Box::new(lit("c"))),
4481            ))),
4482            Expr::Case(Case::new(
4483                None,
4484                vec![(Box::new(col("c3").gt(lit(0))), Box::new(lit("a")))],
4485                Some(Box::new(lit("b"))),
4486            ))
4487        );
4488
4489        // CASE WHEN c3 > 0 THEN 'a' WHEN c4 < 0 THEN 'b' WHEN true THEN 'c' WHEN c3 = 0 THEN 'd' ELSE 'e' END
4490        // --> CASE WHEN c3 > 0 THEN 'a' WHEN c4 < 0 THEN 'b' ELSE 'c' END
4491        assert_eq!(
4492            simplify(Expr::Case(Case::new(
4493                None,
4494                vec![
4495                    (Box::new(col("c3").gt(lit(0))), Box::new(lit("a"))),
4496                    (Box::new(col("c4").lt(lit(0))), Box::new(lit("b"))),
4497                    (Box::new(lit(true)), Box::new(lit("c"))),
4498                    (Box::new(col("c3").eq(lit(0))), Box::new(lit("d"))),
4499                ],
4500                Some(Box::new(lit("e"))),
4501            ))),
4502            Expr::Case(Case::new(
4503                None,
4504                vec![
4505                    (Box::new(col("c3").gt(lit(0))), Box::new(lit("a"))),
4506                    (Box::new(col("c4").lt(lit(0))), Box::new(lit("b"))),
4507                ],
4508                Some(Box::new(lit("c"))),
4509            ))
4510        );
4511
4512        // CASE WHEN c3 > 0 THEN 1 WHEN c4 < 0 THEN 2 WHEN true THEN 3 END (no else)
4513        // --> CASE WHEN c3 > 0 THEN 1 WHEN c4 < 0 THEN 2 ELSE 3 END
4514        assert_eq!(
4515            simplify(Expr::Case(Case::new(
4516                None,
4517                vec![
4518                    (Box::new(col("c3").gt(lit(0))), Box::new(lit(1))),
4519                    (Box::new(col("c4").lt(lit(0))), Box::new(lit(2))),
4520                    (Box::new(lit(true)), Box::new(lit(3))),
4521                ],
4522                None,
4523            ))),
4524            Expr::Case(Case::new(
4525                None,
4526                vec![
4527                    (Box::new(col("c3").gt(lit(0))), Box::new(lit(1))),
4528                    (Box::new(col("c4").lt(lit(0))), Box::new(lit(2))),
4529                ],
4530                Some(Box::new(lit(3))),
4531            ))
4532        );
4533
4534        // Negative test: CASE WHEN c3 > 0 THEN c3 WHEN c4 < 0 THEN 2 ELSE 3 END should not be simplified
4535        let expr = Expr::Case(Case::new(
4536            None,
4537            vec![
4538                (Box::new(col("c3").gt(lit(0))), Box::new(col("c3"))),
4539                (Box::new(col("c4").lt(lit(0))), Box::new(lit(2))),
4540            ],
4541            Some(Box::new(lit(3))),
4542        ));
4543        assert_eq!(simplify(expr.clone()), expr);
4544    }
4545
4546    #[test]
4547    fn simplify_expr_case_when_any_false() {
4548        // CASE WHEN false THEN 'a' END --> NULL
4549        assert_eq!(
4550            simplify(Expr::Case(Case::new(
4551                None,
4552                vec![(Box::new(lit(false)), Box::new(lit("a")))],
4553                None,
4554            ))),
4555            Expr::Literal(ScalarValue::Utf8(None), None)
4556        );
4557
4558        // CASE WHEN false THEN 2 ELSE 1 END --> 1
4559        assert_eq!(
4560            simplify(Expr::Case(Case::new(
4561                None,
4562                vec![(Box::new(lit(false)), Box::new(lit(2)))],
4563                Some(Box::new(lit(1))),
4564            ))),
4565            lit(1),
4566        );
4567
4568        // CASE WHEN c3 < 10 THEN 'b' WHEN false then c3 ELSE c4 END --> CASE WHEN c3 < 10 THEN b ELSE c4 END
4569        assert_eq!(
4570            simplify(Expr::Case(Case::new(
4571                None,
4572                vec![
4573                    (Box::new(col("c3").lt(lit(10))), Box::new(lit("b"))),
4574                    (Box::new(lit(false)), Box::new(col("c3"))),
4575                ],
4576                Some(Box::new(col("c4"))),
4577            ))),
4578            Expr::Case(Case::new(
4579                None,
4580                vec![(Box::new(col("c3").lt(lit(10))), Box::new(lit("b")))],
4581                Some(Box::new(col("c4"))),
4582            ))
4583        );
4584
4585        // Negative test: CASE WHEN c3 = 4 THEN 1 ELSE 2 END should not be simplified
4586        let expr = Expr::Case(Case::new(
4587            None,
4588            vec![(Box::new(col("c3").eq(lit(4))), Box::new(lit(1)))],
4589            Some(Box::new(lit(2))),
4590        ));
4591        assert_eq!(simplify(expr.clone()), expr);
4592    }
4593
4594    #[test]
4595    fn simplify_expr_bool_or() {
4596        // col || true is always true
4597        assert_eq!(simplify(col("c2").or(lit(true))), lit(true),);
4598
4599        // col || false is always col
4600        assert_eq!(simplify(col("c2").or(lit(false))), col("c2"),);
4601
4602        // true || null is always true
4603        assert_eq!(simplify(lit(true).or(lit_bool_null())), lit(true),);
4604
4605        // null || true is always true
4606        assert_eq!(simplify(lit_bool_null().or(lit(true))), lit(true),);
4607
4608        // false || null is always null
4609        assert_eq!(simplify(lit(false).or(lit_bool_null())), lit_bool_null(),);
4610
4611        // null || false is always null
4612        assert_eq!(simplify(lit_bool_null().or(lit(false))), lit_bool_null(),);
4613
4614        // ( c1 BETWEEN Int32(0) AND Int32(10) ) OR Boolean(NULL)
4615        // it can be either NULL or  TRUE depending on the value of `c1 BETWEEN Int32(0) AND Int32(10)`
4616        // and should not be rewritten
4617        let expr = col("c1").between(lit(0), lit(10));
4618        let expr = expr.or(lit_bool_null());
4619        let result = simplify(expr);
4620
4621        let expected_expr = or(
4622            and(col("c1").gt_eq(lit(0)), col("c1").lt_eq(lit(10))),
4623            lit_bool_null(),
4624        );
4625        assert_eq!(expected_expr, result);
4626    }
4627
4628    #[test]
4629    fn simplify_inlist() {
4630        assert_eq!(simplify(in_list(col("c1"), vec![], false)), lit(false));
4631        assert_eq!(simplify(in_list(col("c1"), vec![], true)), lit(true));
4632
4633        // null in (...)  --> null
4634        assert_eq!(
4635            simplify(in_list(lit_bool_null(), vec![col("c1"), lit(1)], false)),
4636            lit_bool_null()
4637        );
4638
4639        // null not in (...)  --> null
4640        assert_eq!(
4641            simplify(in_list(lit_bool_null(), vec![col("c1"), lit(1)], true)),
4642            lit_bool_null()
4643        );
4644
4645        assert_eq!(
4646            simplify(in_list(col("c1"), vec![lit(1)], false)),
4647            col("c1").eq(lit(1))
4648        );
4649        assert_eq!(
4650            simplify(in_list(col("c1"), vec![lit(1)], true)),
4651            col("c1").not_eq(lit(1))
4652        );
4653
4654        // more complex expressions can be simplified if list contains
4655        // one element only
4656        assert_eq!(
4657            simplify(in_list(col("c1") * lit(10), vec![lit(2)], false)),
4658            (col("c1") * lit(10)).eq(lit(2))
4659        );
4660
4661        assert_eq!(
4662            simplify(in_list(col("c1"), vec![lit(1), lit(2)], false)),
4663            col("c1").eq(lit(1)).or(col("c1").eq(lit(2)))
4664        );
4665        assert_eq!(
4666            simplify(in_list(col("c1"), vec![lit(1), lit(2)], true)),
4667            col("c1").not_eq(lit(1)).and(col("c1").not_eq(lit(2)))
4668        );
4669
4670        let subquery = Arc::new(test_table_scan_with_name("test").unwrap());
4671        assert_eq!(
4672            simplify(in_list(
4673                col("c1"),
4674                vec![scalar_subquery(Arc::clone(&subquery))],
4675                false
4676            )),
4677            in_subquery(col("c1"), Arc::clone(&subquery))
4678        );
4679        assert_eq!(
4680            simplify(in_list(
4681                col("c1"),
4682                vec![scalar_subquery(Arc::clone(&subquery))],
4683                true
4684            )),
4685            not_in_subquery(col("c1"), subquery)
4686        );
4687
4688        let subquery1 =
4689            scalar_subquery(Arc::new(test_table_scan_with_name("test1").unwrap()));
4690        let subquery2 =
4691            scalar_subquery(Arc::new(test_table_scan_with_name("test2").unwrap()));
4692
4693        // c1 NOT IN (<subquery1>, <subquery2>) -> c1 != <subquery1> AND c1 != <subquery2>
4694        assert_eq!(
4695            simplify(in_list(
4696                col("c1"),
4697                vec![subquery1.clone(), subquery2.clone()],
4698                true
4699            )),
4700            col("c1")
4701                .not_eq(subquery1.clone())
4702                .and(col("c1").not_eq(subquery2.clone()))
4703        );
4704
4705        // c1 IN (<subquery1>, <subquery2>) -> c1 == <subquery1> OR c1 == <subquery2>
4706        assert_eq!(
4707            simplify(in_list(
4708                col("c1"),
4709                vec![subquery1.clone(), subquery2.clone()],
4710                false
4711            )),
4712            col("c1").eq(subquery1).or(col("c1").eq(subquery2))
4713        );
4714
4715        // 1. c1_non_null IN (1,2,3,4) AND c1_non_null IN (5,6,7,8) -> false
4716        let expr = in_list(
4717            col("c1_non_null"),
4718            vec![lit(1), lit(2), lit(3), lit(4)],
4719            false,
4720        )
4721        .and(in_list(
4722            col("c1_non_null"),
4723            vec![lit(5), lit(6), lit(7), lit(8)],
4724            false,
4725        ));
4726        assert_eq!(simplify(expr), lit(false));
4727
4728        // Preserve the NULL branch when the tested expression is nullable.
4729        let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], false).and(
4730            in_list(col("c1"), vec![lit(5), lit(6), lit(7), lit(8)], false),
4731        );
4732        assert_eq!(simplify(expr), col("c1").is_null().and(lit_bool_null()));
4733
4734        // 2. c1 IN (1,2,3,4) AND c1 IN (4,5,6,7) -> c1 = 4
4735        let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], false).and(
4736            in_list(col("c1"), vec![lit(4), lit(5), lit(6), lit(7)], false),
4737        );
4738        assert_eq!(simplify(expr), col("c1").eq(lit(4)));
4739
4740        // 3. c1_non_null NOT IN (1, 2, 3, 4) OR c1_non_null NOT IN (5, 6, 7, 8) -> true
4741        let expr = in_list(
4742            col("c1_non_null"),
4743            vec![lit(1), lit(2), lit(3), lit(4)],
4744            true,
4745        )
4746        .or(in_list(
4747            col("c1_non_null"),
4748            vec![lit(5), lit(6), lit(7), lit(8)],
4749            true,
4750        ));
4751        assert_eq!(simplify(expr), lit(true));
4752
4753        // Preserve the NULL branch when the tested expression is nullable.
4754        let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).or(
4755            in_list(col("c1"), vec![lit(5), lit(6), lit(7), lit(8)], true),
4756        );
4757        assert_eq!(simplify(expr), col("c1").is_not_null().or(lit_bool_null()));
4758
4759        // 3.5 c1 NOT IN (1, 2, 3, 4) OR c1 NOT IN (4, 5, 6, 7) -> c1 != 4 (4 overlaps)
4760        let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).or(
4761            in_list(col("c1"), vec![lit(4), lit(5), lit(6), lit(7)], true),
4762        );
4763        assert_eq!(simplify(expr), col("c1").not_eq(lit(4)));
4764
4765        // 4. c1 NOT IN (1,2,3,4) AND c1 NOT IN (4,5,6,7) -> c1 NOT IN (1,2,3,4,5,6,7)
4766        let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).and(
4767            in_list(col("c1"), vec![lit(4), lit(5), lit(6), lit(7)], true),
4768        );
4769        assert_eq!(
4770            simplify(expr),
4771            in_list(
4772                col("c1"),
4773                vec![lit(1), lit(2), lit(3), lit(4), lit(5), lit(6), lit(7)],
4774                true
4775            )
4776        );
4777
4778        // 5. c1 IN (1,2,3,4) OR c1 IN (2,3,4,5) -> c1 IN (1,2,3,4,5)
4779        let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], false).or(
4780            in_list(col("c1"), vec![lit(2), lit(3), lit(4), lit(5)], false),
4781        );
4782        assert_eq!(
4783            simplify(expr),
4784            in_list(
4785                col("c1"),
4786                vec![lit(1), lit(2), lit(3), lit(4), lit(5)],
4787                false
4788            )
4789        );
4790
4791        // 6. c1_non_null IN (1,2,3) AND c1_non_null NOT IN (1,2,3,4,5) -> false
4792        let expr = in_list(col("c1_non_null"), vec![lit(1), lit(2), lit(3)], false).and(
4793            in_list(
4794                col("c1_non_null"),
4795                vec![lit(1), lit(2), lit(3), lit(4), lit(5)],
4796                true,
4797            ),
4798        );
4799        assert_eq!(simplify(expr), lit(false));
4800
4801        // Preserve the NULL branch when the tested expression is nullable.
4802        let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3)], false).and(in_list(
4803            col("c1"),
4804            vec![lit(1), lit(2), lit(3), lit(4), lit(5)],
4805            true,
4806        ));
4807        assert_eq!(simplify(expr), col("c1").is_null().and(lit_bool_null()));
4808
4809        // 7. c1 NOT IN (1,2,3,4) AND c1 IN (1,2,3,4,5) -> c1 = 5
4810        let expr =
4811            in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).and(in_list(
4812                col("c1"),
4813                vec![lit(1), lit(2), lit(3), lit(4), lit(5)],
4814                false,
4815            ));
4816        assert_eq!(simplify(expr), col("c1").eq(lit(5)));
4817
4818        // 8. c1 IN (1,2,3,4) AND c1 NOT IN (5,6,7,8) -> c1 IN (1,2,3,4)
4819        let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], false).and(
4820            in_list(col("c1"), vec![lit(5), lit(6), lit(7), lit(8)], true),
4821        );
4822        assert_eq!(
4823            simplify(expr),
4824            in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], false)
4825        );
4826
4827        // inlist with more than two expressions
4828        // c1 IN (1,2,3,4,5,6) AND c1 IN (1,3,5,6) AND c1 IN (3,6) -> c1 = 3 OR c1 = 6
4829        let expr = in_list(
4830            col("c1"),
4831            vec![lit(1), lit(2), lit(3), lit(4), lit(5), lit(6)],
4832            false,
4833        )
4834        .and(in_list(
4835            col("c1"),
4836            vec![lit(1), lit(3), lit(5), lit(6)],
4837            false,
4838        ))
4839        .and(in_list(col("c1"), vec![lit(3), lit(6)], false));
4840        assert_eq!(
4841            simplify(expr),
4842            col("c1").eq(lit(3)).or(col("c1").eq(lit(6)))
4843        );
4844
4845        // c1 NOT IN (1,2,3,4) AND c1 IN (5,6,7,8) AND c1 NOT IN (3,4,5,6) AND c1 IN (8,9,10) -> c1 = 8
4846        let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).and(
4847            in_list(col("c1"), vec![lit(5), lit(6), lit(7), lit(8)], false)
4848                .and(in_list(
4849                    col("c1"),
4850                    vec![lit(3), lit(4), lit(5), lit(6)],
4851                    true,
4852                ))
4853                .and(in_list(col("c1"), vec![lit(8), lit(9), lit(10)], false)),
4854        );
4855        assert_eq!(simplify(expr), col("c1").eq(lit(8)));
4856
4857        // Contains non-InList expression
4858        // c1 NOT IN (1,2,3,4) OR c1 != 5 OR c1 NOT IN (6,7,8,9) -> c1 NOT IN (1,2,3,4) OR c1 != 5 OR c1 NOT IN (6,7,8,9)
4859        let expr =
4860            in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).or(col("c1")
4861                .not_eq(lit(5))
4862                .or(in_list(
4863                    col("c1"),
4864                    vec![lit(6), lit(7), lit(8), lit(9)],
4865                    true,
4866                )));
4867        // TODO: Further simplify this expression
4868        // https://github.com/apache/datafusion/issues/8970
4869        // assert_eq!(simplify(expr.clone()), lit(true));
4870        assert_eq!(simplify(expr.clone()), expr);
4871    }
4872
4873    fn assert_inlist_simplification_result(
4874        expr: Expr,
4875        batch: &RecordBatch,
4876        expected: Vec<bool>,
4877    ) -> Result<()> {
4878        let schema = batch.schema().to_dfschema_ref()?;
4879        let simplifier = ExprSimplifier::new(
4880            SimplifyContext::builder()
4881                .with_schema(Arc::clone(&schema))
4882                .build(),
4883        );
4884        let original = simplifier.coerce(expr, &schema)?;
4885        let simplified = simplifier.simplify(original.clone())?;
4886        let props = ExecutionProps::new();
4887        let evaluate = |expr: &Expr| {
4888            create_physical_expr(
4889                expr,
4890                &schema,
4891                &props,
4892                &PhysicalPlanningContext::default(),
4893            )?
4894            .evaluate(batch)?
4895            .into_array(batch.num_rows())
4896        };
4897        let original_result = evaluate(&original)?;
4898        let actual = evaluate(&simplified)?;
4899        assert_eq!(original_result.as_ref(), actual.as_ref());
4900        assert_eq!(actual.as_boolean(), &BooleanArray::from(expected));
4901        Ok(())
4902    }
4903
4904    #[test]
4905    fn simplify_inlist_runtime_set_operations() -> Result<()> {
4906        let schema = Arc::new(Schema::new(vec![
4907            Field::new("x", DataType::Int32, false),
4908            Field::new("a", DataType::Int32, false),
4909            Field::new("b", DataType::Int32, false),
4910        ]));
4911        let batch = RecordBatch::try_new(
4912            schema,
4913            vec![
4914                Arc::new(Int32Array::from(vec![1, 2, 3])),
4915                Arc::new(Int32Array::from(vec![1, 1, 3])),
4916                Arc::new(Int32Array::from(vec![1, 2, 4])),
4917            ],
4918        )?;
4919        let left = |negated| {
4920            in_list(col("x"), vec![col("a"), lit(2), lit(10), lit(11)], negated)
4921        };
4922        let right = |negated| {
4923            in_list(col("x"), vec![col("b"), lit(5), lit(12), lit(13)], negated)
4924        };
4925
4926        // Structurally different, non-null columns can hold equal values.
4927        for (expr, expected) in [
4928            (left(false).and(right(false)), vec![true, true, false]),
4929            (left(false).and(right(true)), vec![false, false, true]),
4930            (left(true).and(right(false)), vec![false, false, false]),
4931            (left(true).or(right(true)), vec![false, false, true]),
4932            // Union remains valid for nonvolatile runtime expressions.
4933            (left(false).or(right(false)), vec![true, true, true]),
4934            (left(true).and(right(true)), vec![false, false, false]),
4935        ] {
4936            assert_inlist_simplification_result(expr, &batch, expected)?;
4937        }
4938
4939        // Coercion must precede structural comparison of mixed integer literals.
4940        let expr = in_list(col("x"), vec![lit(1i32), lit(2), lit(10), lit(11)], false)
4941            .and(in_list(
4942                col("x"),
4943                vec![lit(1i64), lit(3i64), lit(12i64), lit(13i64)],
4944                false,
4945            ));
4946        assert_inlist_simplification_result(expr, &batch, vec![true, false, false])
4947    }
4948
4949    #[test]
4950    fn simplify_inlist_signed_zero() -> Result<()> {
4951        for data_type in [DataType::Float16, DataType::Float32, DataType::Float64] {
4952            let values =
4953                arrow::compute::cast(&Float64Array::from(vec![0.0, -0.0]), &data_type)?;
4954            let literals = |values: &[f64]| {
4955                values
4956                    .iter()
4957                    .map(|&value| {
4958                        ScalarValue::Float64(Some(value))
4959                            .cast_to(&data_type)
4960                            .map(lit)
4961                    })
4962                    .collect::<Result<Vec<_>>>()
4963            };
4964            let left_list = literals(&[0.0, 1.0, 2.0, 3.0])?;
4965            let right_list = literals(&[-0.0, 4.0, 5.0, 6.0])?;
4966            let retains_short_lists =
4967                matches!(data_type, DataType::Float32 | DataType::Float64);
4968            let schema = Arc::new(Schema::new(vec![Field::new("x", data_type, false)]));
4969            let batch = RecordBatch::try_new(schema, vec![values])?;
4970            let schema = batch.schema().to_dfschema_ref()?;
4971            let simplifier = ExprSimplifier::new(
4972                SimplifyContext::builder()
4973                    .with_schema(Arc::clone(&schema))
4974                    .build(),
4975            )
4976            .with_canonicalize(false);
4977            // Cover both inlined comparisons and lists that reach the set rewrites.
4978            assert!(left_list.len() > THRESHOLD_INLINE_INLIST);
4979            assert!(right_list.len() > THRESHOLD_INLINE_INLIST);
4980            for list_len in [2, left_list.len()] {
4981                let left =
4982                    |negated| in_list(col("x"), left_list[..list_len].to_vec(), negated);
4983                let right =
4984                    |negated| in_list(col("x"), right_list[..list_len].to_vec(), negated);
4985                for (expr, expected) in [
4986                    (left(false).and(right(false)), vec![true, true]),
4987                    (left(false).and(right(true)), vec![false, false]),
4988                    (left(true).and(right(false)), vec![false, false]),
4989                    (left(true).or(right(true)), vec![false, false]),
4990                ] {
4991                    let simplified = simplifier.simplify(expr.clone())?;
4992                    if list_len > THRESHOLD_INLINE_INLIST || retains_short_lists {
4993                        // Floating-point literals must bypass structural set rewrites.
4994                        assert_eq!(simplified, expr);
4995                    } else {
4996                        let actual = create_physical_expr(
4997                            &simplified,
4998                            &schema,
4999                            &ExecutionProps::new(),
5000                            &PhysicalPlanningContext::default(),
5001                        )?
5002                        .evaluate(&batch)?
5003                        .into_array(batch.num_rows())?;
5004                        assert_eq!(actual.as_boolean(), &BooleanArray::from(expected));
5005                    }
5006                }
5007            }
5008        }
5009        Ok(())
5010    }
5011
5012    #[test]
5013    fn simplify_inlist_preserves_volatile_evaluations() {
5014        let fun = Arc::new(ScalarUDF::new_from_impl(VolatileUdf::new()));
5015        let volatile = Expr::ScalarFunction(ScalarFunction::new_udf(fun, vec![]));
5016        let left = |negated| {
5017            in_list(
5018                volatile.clone(),
5019                vec![lit(1), lit(2), lit(3), lit(4)],
5020                negated,
5021            )
5022        };
5023        let right = |negated| {
5024            in_list(
5025                volatile.clone(),
5026                vec![lit(3), lit(4), lit(5), lit(6)],
5027                negated,
5028            )
5029        };
5030        for expr in [
5031            left(false).and(right(false)),
5032            left(false).and(right(true)),
5033            left(true).and(right(false)),
5034            left(true).or(right(true)),
5035            left(true).and(right(true)),
5036        ] {
5037            assert_eq!(simplify_no_canonicalize(expr.clone()), expr);
5038        }
5039
5040        // Union deduplication must not remove a repeated volatile list item.
5041        for negated in [false, true] {
5042            let left = in_list(
5043                col("c1"),
5044                vec![volatile.clone(), lit(1), lit(2), lit(3)],
5045                negated,
5046            );
5047            let right = in_list(
5048                col("c1"),
5049                vec![volatile.clone(), lit(4), lit(5), lit(6)],
5050                negated,
5051            );
5052            let expr = if negated {
5053                left.and(right)
5054            } else {
5055                left.or(right)
5056            };
5057            assert_eq!(simplify_no_canonicalize(expr.clone()), expr);
5058        }
5059    }
5060
5061    #[test]
5062    fn simplify_short_inlist_types() {
5063        for (data_type, retain_short) in [
5064            (DataType::Int32, true),
5065            (DataType::Int64, true),
5066            (DataType::UInt64, true),
5067            (DataType::Float32, true),
5068            (DataType::Float64, true),
5069            (DataType::FixedSizeBinary(1), true),
5070            (DataType::FixedSizeBinary(2), true),
5071            (DataType::FixedSizeBinary(4), true),
5072            (DataType::FixedSizeBinary(8), true),
5073            (DataType::FixedSizeBinary(16), true),
5074            (DataType::Float16, false),
5075            (DataType::FixedSizeBinary(3), false),
5076            (DataType::Utf8View, false),
5077            (
5078                DataType::Dictionary(
5079                    Box::new(DataType::Int8),
5080                    Box::new(DataType::Float64),
5081                ),
5082                false,
5083            ),
5084        ] {
5085            let values = (1..=3)
5086                .map(|value| {
5087                    lit(match &data_type {
5088                        DataType::FixedSizeBinary(width) => ScalarValue::FixedSizeBinary(
5089                            *width,
5090                            Some(vec![value; *width as usize]),
5091                        ),
5092                        DataType::Utf8View => {
5093                            ScalarValue::Utf8View(Some(value.to_string()))
5094                        }
5095                        _ => ScalarValue::Int32(Some(i32::from(value)))
5096                            .cast_to(&data_type)
5097                            .unwrap(),
5098                    })
5099                })
5100                .collect::<Vec<_>>();
5101            let schema = Schema::new(vec![Field::new("value", data_type.clone(), true)])
5102                .to_dfschema_ref()
5103                .unwrap();
5104            let simplifier = ExprSimplifier::new(
5105                SimplifyContext::builder().with_schema(schema).build(),
5106            );
5107            for list_len in [2, 3] {
5108                for negated in [false, true] {
5109                    let expr =
5110                        in_list(col("value"), values[..list_len].to_vec(), negated);
5111                    let simplified = simplifier.simplify(expr.clone()).unwrap();
5112                    if retain_short {
5113                        assert_eq!(simplified, expr, "{data_type:?}");
5114                    } else {
5115                        let op = if negated { Operator::And } else { Operator::Or };
5116                        assert!(
5117                            matches!(simplified, Expr::BinaryExpr(binary) if binary.op == op),
5118                            "{data_type:?}, list_len={list_len}, negated={negated}"
5119                        );
5120                    }
5121                }
5122            }
5123        }
5124    }
5125
5126    #[test]
5127    fn simplify_short_inlist_coerced_literals() {
5128        for negated in [false, true] {
5129            let expr = in_list(col("c3"), vec![lit(1_i32), lit(2_i32)], negated);
5130            let expected = in_list(col("c3"), vec![lit(1_i64), lit(2_i64)], negated);
5131            assert_eq!(simplify(coerce(expr)), expected);
5132        }
5133    }
5134
5135    #[test]
5136    fn simplify_inlist_set_operation_propagates_nullability_errors() {
5137        let info = SimplifyContext::builder()
5138            .with_schema(expr_test_schema())
5139            .build();
5140        let valid = InList {
5141            expr: Box::new(col("c1")),
5142            list: vec![lit("a")],
5143            negated: false,
5144        };
5145
5146        let invalid_list_item = InList {
5147            expr: Box::new(col("c1")),
5148            list: vec![col("missing")],
5149            negated: false,
5150        };
5151        let error =
5152            simplify_inlist_set_operation(&info, &invalid_list_item, &valid, lit(false))
5153                .unwrap_err();
5154        assert_contains!(error.to_string(), "No field named missing");
5155
5156        let invalid_tested_expr = InList {
5157            expr: Box::new(col("missing")),
5158            list: vec![lit("a")],
5159            negated: false,
5160        };
5161        let error = simplify_inlist_set_operation(
5162            &info,
5163            &invalid_tested_expr,
5164            &valid,
5165            lit(false),
5166        )
5167        .unwrap_err();
5168        assert_contains!(error.to_string(), "No field named missing");
5169    }
5170
5171    #[test]
5172    fn simplify_inlist_set_operation_preserves_null_result() {
5173        let info = SimplifyContext::builder()
5174            .with_schema(expr_test_schema())
5175            .build();
5176        let left = InList {
5177            expr: Box::new(col("c1")),
5178            list: vec![lit("a")],
5179            negated: false,
5180        };
5181        let right = InList {
5182            expr: Box::new(col("c1")),
5183            list: vec![lit("b")],
5184            negated: false,
5185        };
5186
5187        assert_eq!(
5188            simplify_inlist_set_operation(&info, &left, &right, lit_bool_null()).unwrap(),
5189            Some(lit_bool_null())
5190        );
5191    }
5192
5193    #[test]
5194    fn simplify_null_in_empty_inlist() {
5195        // `NULL::boolean IN ()` == `NULL::boolean IN (SELECT foo FROM empty)` == false
5196        let expr = in_list(lit_bool_null(), vec![], false);
5197        assert_eq!(simplify(expr), lit(false));
5198
5199        // `NULL::boolean NOT IN ()` == `NULL::boolean NOT IN (SELECT foo FROM empty)` == true
5200        let expr = in_list(lit_bool_null(), vec![], true);
5201        assert_eq!(simplify(expr), lit(true));
5202
5203        // `NULL IN ()` == `NULL IN (SELECT foo FROM empty)` == false
5204        let null_null = || Expr::Literal(ScalarValue::Null, None);
5205        let expr = in_list(null_null(), vec![], false);
5206        assert_eq!(simplify(expr), lit(false));
5207
5208        // `NULL NOT IN ()` == `NULL NOT IN (SELECT foo FROM empty)` == true
5209        let expr = in_list(null_null(), vec![], true);
5210        assert_eq!(simplify(expr), lit(true));
5211    }
5212
5213    #[test]
5214    fn just_simplifier_simplify_null_in_empty_inlist() {
5215        let simplify = |expr: Expr| -> Expr {
5216            let schema = expr_test_schema();
5217            let info = SimplifyContext::builder().with_schema(schema).build();
5218            let simplifier = &mut Simplifier::new(&info);
5219            expr.rewrite(simplifier)
5220                .expect("Failed to simplify expression")
5221                .data
5222        };
5223
5224        // `NULL::boolean IN ()` == `NULL::boolean IN (SELECT foo FROM empty)` == false
5225        let expr = in_list(lit_bool_null(), vec![], false);
5226        assert_eq!(simplify(expr), lit(false));
5227
5228        // `NULL::boolean NOT IN ()` == `NULL::boolean NOT IN (SELECT foo FROM empty)` == true
5229        let expr = in_list(lit_bool_null(), vec![], true);
5230        assert_eq!(simplify(expr), lit(true));
5231
5232        // `NULL IN ()` == `NULL IN (SELECT foo FROM empty)` == false
5233        let null_null = || Expr::Literal(ScalarValue::Null, None);
5234        let expr = in_list(null_null(), vec![], false);
5235        assert_eq!(simplify(expr), lit(false));
5236
5237        // `NULL NOT IN ()` == `NULL NOT IN (SELECT foo FROM empty)` == true
5238        let expr = in_list(null_null(), vec![], true);
5239        assert_eq!(simplify(expr), lit(true));
5240    }
5241
5242    #[test]
5243    fn simplify_large_or() {
5244        let expr = (0..5)
5245            .map(|i| col("c1").eq(lit(i)))
5246            .fold(lit(false), |acc, e| acc.or(e));
5247        assert_eq!(
5248            simplify(expr),
5249            in_list(col("c1"), (0..5).map(lit).collect(), false),
5250        );
5251    }
5252
5253    #[test]
5254    fn simplify_expr_bool_and() {
5255        // col & true is always col
5256        assert_eq!(simplify(col("c2").and(lit(true))), col("c2"),);
5257        // col & false is always false
5258        assert_eq!(simplify(col("c2").and(lit(false))), lit(false),);
5259
5260        // true && null is always null
5261        assert_eq!(simplify(lit(true).and(lit_bool_null())), lit_bool_null(),);
5262
5263        // null && true is always null
5264        assert_eq!(simplify(lit_bool_null().and(lit(true))), lit_bool_null(),);
5265
5266        // false && null is always false
5267        assert_eq!(simplify(lit(false).and(lit_bool_null())), lit(false),);
5268
5269        // null && false is always false
5270        assert_eq!(simplify(lit_bool_null().and(lit(false))), lit(false),);
5271
5272        // c1 BETWEEN Int32(0) AND Int32(10) AND Boolean(NULL)
5273        // it can be either NULL or FALSE depending on the value of `c1 BETWEEN Int32(0) AND Int32(10)`
5274        // and the Boolean(NULL) should remain
5275        let expr = col("c1").between(lit(0), lit(10));
5276        let expr = expr.and(lit_bool_null());
5277        let result = simplify(expr);
5278
5279        let expected_expr = and(
5280            and(col("c1").gt_eq(lit(0)), col("c1").lt_eq(lit(10))),
5281            lit_bool_null(),
5282        );
5283        assert_eq!(expected_expr, result);
5284    }
5285
5286    #[test]
5287    fn simplify_expr_between() {
5288        // c2 between 3 and 4 is c2 >= 3 and c2 <= 4
5289        let expr = col("c2").between(lit(3), lit(4));
5290        assert_eq!(
5291            simplify(expr),
5292            and(col("c2").gt_eq(lit(3)), col("c2").lt_eq(lit(4)))
5293        );
5294
5295        // c2 not between 3 and 4 is c2 < 3 or c2 > 4
5296        let expr = col("c2").not_between(lit(3), lit(4));
5297        assert_eq!(
5298            simplify(expr),
5299            or(col("c2").lt(lit(3)), col("c2").gt(lit(4)))
5300        );
5301    }
5302
5303    #[test]
5304    fn test_like_and_ilike() {
5305        let null = lit(ScalarValue::Utf8(None));
5306
5307        // expr [NOT] [I]LIKE NULL
5308        let expr = col("c1").like(null.clone());
5309        assert_eq!(simplify(expr), lit_bool_null());
5310
5311        let expr = col("c1").not_like(null.clone());
5312        assert_eq!(simplify(expr), lit_bool_null());
5313
5314        let expr = col("c1").ilike(null.clone());
5315        assert_eq!(simplify(expr), lit_bool_null());
5316
5317        let expr = col("c1").not_ilike(null.clone());
5318        assert_eq!(simplify(expr), lit_bool_null());
5319
5320        // expr [NOT] [I]LIKE '%'
5321        let expr = col("c1").like(lit("%"));
5322        assert_eq!(simplify(expr), if_not_null(col("c1"), true));
5323
5324        let expr = col("c1").not_like(lit("%"));
5325        assert_eq!(simplify(expr), if_not_null(col("c1"), false));
5326
5327        let expr = col("c1").ilike(lit("%"));
5328        assert_eq!(simplify(expr), if_not_null(col("c1"), true));
5329
5330        let expr = col("c1").not_ilike(lit("%"));
5331        assert_eq!(simplify(expr), if_not_null(col("c1"), false));
5332
5333        // expr [NOT] [I]LIKE '%%'
5334        let expr = col("c1").like(lit("%%"));
5335        assert_eq!(simplify(expr), if_not_null(col("c1"), true));
5336
5337        let expr = col("c1").not_like(lit("%%"));
5338        assert_eq!(simplify(expr), if_not_null(col("c1"), false));
5339
5340        let expr = col("c1").ilike(lit("%%"));
5341        assert_eq!(simplify(expr), if_not_null(col("c1"), true));
5342
5343        let expr = col("c1").not_ilike(lit("%%"));
5344        assert_eq!(simplify(expr), if_not_null(col("c1"), false));
5345
5346        // not_null_expr [NOT] [I]LIKE '%'
5347        let expr = col("c1_non_null").like(lit("%"));
5348        assert_eq!(simplify(expr), lit(true));
5349
5350        let expr = col("c1_non_null").not_like(lit("%"));
5351        assert_eq!(simplify(expr), lit(false));
5352
5353        let expr = col("c1_non_null").ilike(lit("%"));
5354        assert_eq!(simplify(expr), lit(true));
5355
5356        let expr = col("c1_non_null").not_ilike(lit("%"));
5357        assert_eq!(simplify(expr), lit(false));
5358
5359        // not_null_expr [NOT] [I]LIKE '%%'
5360        let expr = col("c1_non_null").like(lit("%%"));
5361        assert_eq!(simplify(expr), lit(true));
5362
5363        let expr = col("c1_non_null").not_like(lit("%%"));
5364        assert_eq!(simplify(expr), lit(false));
5365
5366        let expr = col("c1_non_null").ilike(lit("%%"));
5367        assert_eq!(simplify(expr), lit(true));
5368
5369        let expr = col("c1_non_null").not_ilike(lit("%%"));
5370        assert_eq!(simplify(expr), lit(false));
5371
5372        // null_constant [NOT] [I]LIKE '%'
5373        let expr = null.clone().like(lit("%"));
5374        assert_eq!(simplify(expr), lit_bool_null());
5375
5376        let expr = null.clone().not_like(lit("%"));
5377        assert_eq!(simplify(expr), lit_bool_null());
5378
5379        let expr = null.clone().ilike(lit("%"));
5380        assert_eq!(simplify(expr), lit_bool_null());
5381
5382        let expr = null.clone().not_ilike(lit("%"));
5383        assert_eq!(simplify(expr), lit_bool_null());
5384
5385        // null_constant [NOT] [I]LIKE '%%'
5386        let expr = null.clone().like(lit("%%"));
5387        assert_eq!(simplify(expr), lit_bool_null());
5388
5389        let expr = null.clone().not_like(lit("%%"));
5390        assert_eq!(simplify(expr), lit_bool_null());
5391
5392        let expr = null.clone().ilike(lit("%%"));
5393        assert_eq!(simplify(expr), lit_bool_null());
5394
5395        let expr = null.clone().not_ilike(lit("%%"));
5396        assert_eq!(simplify(expr), lit_bool_null());
5397
5398        // null_constant [NOT] [I]LIKE 'a%'
5399        let expr = null.clone().like(lit("a%"));
5400        assert_eq!(simplify(expr), lit_bool_null());
5401
5402        let expr = null.clone().not_like(lit("a%"));
5403        assert_eq!(simplify(expr), lit_bool_null());
5404
5405        let expr = null.clone().ilike(lit("a%"));
5406        assert_eq!(simplify(expr), lit_bool_null());
5407
5408        let expr = null.clone().not_ilike(lit("a%"));
5409        assert_eq!(simplify(expr), lit_bool_null());
5410
5411        // expr [NOT] [I]LIKE with pattern without wildcards
5412        let expr = col("c1").like(lit("a"));
5413        assert_eq!(simplify(expr), col("c1").eq(lit("a")));
5414        let expr = col("c1").not_like(lit("a"));
5415        assert_eq!(simplify(expr), col("c1").not_eq(lit("a")));
5416        let expr = col("c1").like(lit("a_"));
5417        assert_eq!(simplify(expr), col("c1").like(lit("a_")));
5418        let expr = col("c1").not_like(lit("a_"));
5419        assert_eq!(simplify(expr), col("c1").not_like(lit("a_")));
5420
5421        let expr = col("c1").ilike(lit("a"));
5422        assert_eq!(simplify(expr), col("c1").ilike(lit("a")));
5423        let expr = col("c1").not_ilike(lit("a"));
5424        assert_eq!(simplify(expr), col("c1").not_ilike(lit("a")));
5425    }
5426
5427    #[test]
5428    fn test_simplify_with_guarantee() {
5429        // (c3 >= 3) AND (c4 + 2 < 10 OR (c1 NOT IN ("a", "b")))
5430        let expr_x = col("c3").gt(lit(3_i64));
5431        let expr_y = (col("c4") + lit(2_u32)).lt(lit(10_u32));
5432        let expr_z = col("c1").in_list(vec![lit("a"), lit("b")], true);
5433        let expr = expr_x.clone().and(expr_y.or(expr_z));
5434
5435        // All guaranteed null
5436        let guarantees = vec![
5437            (col("c3"), NullableInterval::from(ScalarValue::Int64(None))),
5438            (col("c4"), NullableInterval::from(ScalarValue::UInt32(None))),
5439            (col("c1"), NullableInterval::from(ScalarValue::Utf8(None))),
5440        ];
5441
5442        let output = simplify_with_guarantee(expr.clone(), guarantees);
5443        assert_eq!(output, lit_bool_null());
5444
5445        // All guaranteed false
5446        let guarantees = vec![
5447            (
5448                col("c3"),
5449                NullableInterval::NotNull {
5450                    values: Interval::make(Some(0_i64), Some(2_i64)).unwrap(),
5451                },
5452            ),
5453            (
5454                col("c4"),
5455                NullableInterval::from(ScalarValue::UInt32(Some(9))),
5456            ),
5457            (col("c1"), NullableInterval::from(ScalarValue::from("a"))),
5458        ];
5459        let output = simplify_with_guarantee(expr.clone(), guarantees);
5460        assert_eq!(output, lit(false));
5461
5462        // Guaranteed false or null -> no change.
5463        let guarantees = vec![
5464            (
5465                col("c3"),
5466                NullableInterval::MaybeNull {
5467                    values: Interval::make(Some(0_i64), Some(2_i64)).unwrap(),
5468                },
5469            ),
5470            (
5471                col("c4"),
5472                NullableInterval::MaybeNull {
5473                    values: Interval::make(Some(9_u32), Some(9_u32)).unwrap(),
5474                },
5475            ),
5476            (
5477                col("c1"),
5478                NullableInterval::NotNull {
5479                    values: Interval::try_new(
5480                        ScalarValue::from("d"),
5481                        ScalarValue::from("f"),
5482                    )
5483                    .unwrap(),
5484                },
5485            ),
5486        ];
5487        let output = simplify_with_guarantee(expr.clone(), guarantees);
5488        assert_eq!(&output, &expr_x);
5489
5490        // Sufficient true guarantees
5491        let guarantees = vec![
5492            (
5493                col("c3"),
5494                NullableInterval::from(ScalarValue::Int64(Some(9))),
5495            ),
5496            (
5497                col("c4"),
5498                NullableInterval::from(ScalarValue::UInt32(Some(3))),
5499            ),
5500        ];
5501        let output = simplify_with_guarantee(expr.clone(), guarantees);
5502        assert_eq!(output, lit(true));
5503
5504        // Only partially simplify
5505        let guarantees = vec![(
5506            col("c4"),
5507            NullableInterval::from(ScalarValue::UInt32(Some(3))),
5508        )];
5509        let output = simplify_with_guarantee(expr, guarantees);
5510        assert_eq!(&output, &expr_x);
5511    }
5512
5513    #[test]
5514    fn test_expression_partial_simplify_1() {
5515        // (1 + 2) + (4 / 0) -> 3 + (4 / 0)
5516        let expr = (lit(1) + lit(2)) + (lit(4) / lit(0));
5517        let expected = (lit(3)) + (lit(4) / lit(0));
5518
5519        assert_eq!(simplify(expr), expected);
5520    }
5521
5522    #[test]
5523    fn test_expression_partial_simplify_2() {
5524        // (1 > 2) and (4 / 0) -> false
5525        let expr = (lit(1).gt(lit(2))).and(lit(4) / lit(0));
5526        let expected = lit(false);
5527
5528        assert_eq!(simplify(expr), expected);
5529    }
5530
5531    #[test]
5532    fn test_simplify_cycles() {
5533        // TRUE
5534        let expr = lit(true);
5535        let expected = lit(true);
5536        let (expr, num_iter) = simplify_with_cycle_count(expr);
5537        assert_eq!(expr, expected);
5538        assert_eq!(num_iter, 1);
5539
5540        // (true != NULL) OR (5 > 10)
5541        let expr = lit(true).not_eq(lit_bool_null()).or(lit(5).gt(lit(10)));
5542        let expected = lit_bool_null();
5543        let (expr, num_iter) = simplify_with_cycle_count(expr);
5544        assert_eq!(expr, expected);
5545        assert_eq!(num_iter, 2);
5546
5547        // NOTE: this currently does not simplify
5548        // (((c4 - 10) + 10) *100) / 100
5549        let expr = (((col("c4") - lit(10)) + lit(10)) * lit(100)) / lit(100);
5550        let expected = expr.clone();
5551        let (expr, num_iter) = simplify_with_cycle_count(expr);
5552        assert_eq!(expr, expected);
5553        assert_eq!(num_iter, 1);
5554
5555        // ((c4<1 or c3<2) and c3_non_null<3) and false
5556        let expr = col("c4")
5557            .lt(lit(1))
5558            .or(col("c3").lt(lit(2)))
5559            .and(col("c3_non_null").lt(lit(3)))
5560            .and(lit(false));
5561        let expected = lit(false);
5562        let (expr, num_iter) = simplify_with_cycle_count(expr);
5563        assert_eq!(expr, expected);
5564        assert_eq!(num_iter, 2);
5565    }
5566
5567    fn boolean_test_schema() -> DFSchemaRef {
5568        static BOOLEAN_TEST_SCHEMA: LazyLock<DFSchemaRef> = LazyLock::new(|| {
5569            Schema::new(vec![
5570                Field::new("A", DataType::Boolean, false),
5571                Field::new("B", DataType::Boolean, false),
5572                Field::new("C", DataType::Boolean, false),
5573                Field::new("D", DataType::Boolean, false),
5574            ])
5575            .to_dfschema_ref()
5576            .unwrap()
5577        });
5578        Arc::clone(&BOOLEAN_TEST_SCHEMA)
5579    }
5580
5581    #[test]
5582    fn simplify_common_factor_conjunction_in_disjunction() {
5583        let schema = boolean_test_schema();
5584        let simplifier =
5585            ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build());
5586
5587        let a = || col("A");
5588        let b = || col("B");
5589        let c = || col("C");
5590        let d = || col("D");
5591
5592        // (A AND B) OR (A AND C) -> A AND (B OR C)
5593        let expr = a().and(b()).or(a().and(c()));
5594        let expected = a().and(b().or(c()));
5595
5596        assert_eq!(expected, simplifier.simplify(expr).unwrap());
5597
5598        // (A AND B) OR (A AND C) OR (A AND D) -> A AND (B OR C OR D)
5599        let expr = a().and(b()).or(a().and(c())).or(a().and(d()));
5600        let expected = a().and(b().or(c()).or(d()));
5601        assert_eq!(expected, simplifier.simplify(expr).unwrap());
5602
5603        // A OR (B AND C AND A) -> A
5604        let expr = a().or(b().and(c().and(a())));
5605        let expected = a();
5606        assert_eq!(expected, simplifier.simplify(expr).unwrap());
5607    }
5608
5609    #[test]
5610    fn test_simplify_udaf() {
5611        let udaf = AggregateUDF::new_from_impl(SimplifyMockUdaf::new_with_simplify());
5612        let aggregate_function_expr =
5613            Expr::AggregateFunction(expr::AggregateFunction::new_udf(
5614                udaf.into(),
5615                vec![],
5616                false,
5617                None,
5618                vec![],
5619                None,
5620            ));
5621
5622        let expected = col("result_column");
5623        assert_eq!(simplify(aggregate_function_expr), expected);
5624
5625        let udaf = AggregateUDF::new_from_impl(SimplifyMockUdaf::new_without_simplify());
5626        let aggregate_function_expr =
5627            Expr::AggregateFunction(expr::AggregateFunction::new_udf(
5628                udaf.into(),
5629                vec![],
5630                false,
5631                None,
5632                vec![],
5633                None,
5634            ));
5635
5636        let expected = aggregate_function_expr.clone();
5637        assert_eq!(simplify(aggregate_function_expr), expected);
5638    }
5639
5640    /// A Mock UDAF which defines `simplify` to be used in tests
5641    /// related to UDAF simplification
5642    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
5643    struct SimplifyMockUdaf {
5644        simplify: bool,
5645    }
5646
5647    impl SimplifyMockUdaf {
5648        /// make simplify method return new expression
5649        fn new_with_simplify() -> Self {
5650            Self { simplify: true }
5651        }
5652        /// make simplify method return no change
5653        fn new_without_simplify() -> Self {
5654            Self { simplify: false }
5655        }
5656    }
5657
5658    impl AggregateUDFImpl for SimplifyMockUdaf {
5659        fn name(&self) -> &str {
5660            "mock_simplify"
5661        }
5662
5663        fn signature(&self) -> &Signature {
5664            unimplemented!()
5665        }
5666
5667        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
5668            unimplemented!("not needed for tests")
5669        }
5670
5671        fn accumulator(
5672            &self,
5673            _acc_args: AccumulatorArgs,
5674        ) -> Result<Box<dyn Accumulator>> {
5675            unimplemented!("not needed for tests")
5676        }
5677
5678        fn groups_accumulator_supported(&self, _args: AccumulatorArgs) -> bool {
5679            unimplemented!("not needed for testing")
5680        }
5681
5682        fn create_groups_accumulator(
5683            &self,
5684            _args: AccumulatorArgs,
5685        ) -> Result<Box<dyn GroupsAccumulator>> {
5686            unimplemented!("not needed for testing")
5687        }
5688
5689        fn simplify(&self) -> Option<AggregateFunctionSimplification> {
5690            if self.simplify {
5691                Some(Box::new(|_, _| Ok(col("result_column"))))
5692            } else {
5693                None
5694            }
5695        }
5696    }
5697
5698    #[test]
5699    fn test_simplify_udwf() {
5700        let udwf = WindowFunctionDefinition::WindowUDF(
5701            WindowUDF::new_from_impl(SimplifyMockUdwf::new_with_simplify()).into(),
5702        );
5703        let window_function_expr = Expr::from(WindowFunction::new(udwf, vec![]));
5704
5705        let expected = col("result_column");
5706        assert_eq!(simplify(window_function_expr), expected);
5707
5708        let udwf = WindowFunctionDefinition::WindowUDF(
5709            WindowUDF::new_from_impl(SimplifyMockUdwf::new_without_simplify()).into(),
5710        );
5711        let window_function_expr = Expr::from(WindowFunction::new(udwf, vec![]));
5712
5713        let expected = window_function_expr.clone();
5714        assert_eq!(simplify(window_function_expr), expected);
5715    }
5716
5717    /// A Mock UDWF which defines `simplify` to be used in tests
5718    /// related to UDWF simplification
5719    #[derive(Debug, Clone, PartialEq, Eq, Hash)]
5720    struct SimplifyMockUdwf {
5721        simplify: bool,
5722    }
5723
5724    impl SimplifyMockUdwf {
5725        /// make simplify method return new expression
5726        fn new_with_simplify() -> Self {
5727            Self { simplify: true }
5728        }
5729        /// make simplify method return no change
5730        fn new_without_simplify() -> Self {
5731            Self { simplify: false }
5732        }
5733    }
5734
5735    impl WindowUDFImpl for SimplifyMockUdwf {
5736        fn name(&self) -> &str {
5737            "mock_simplify"
5738        }
5739
5740        fn signature(&self) -> &Signature {
5741            unimplemented!()
5742        }
5743
5744        fn simplify(&self) -> Option<WindowFunctionSimplification> {
5745            if self.simplify {
5746                Some(Box::new(|_, _| Ok(col("result_column"))))
5747            } else {
5748                None
5749            }
5750        }
5751
5752        fn partition_evaluator(
5753            &self,
5754            _partition_evaluator_args: PartitionEvaluatorArgs,
5755        ) -> Result<Box<dyn PartitionEvaluator>> {
5756            unimplemented!("not needed for tests")
5757        }
5758
5759        fn field(&self, _field_args: WindowUDFFieldArgs) -> Result<FieldRef> {
5760            unimplemented!("not needed for tests")
5761        }
5762
5763        fn limit_effect(&self, _args: &[Arc<dyn PhysicalExpr>]) -> LimitEffect {
5764            LimitEffect::Unknown
5765        }
5766    }
5767    #[derive(Debug, PartialEq, Eq, Hash)]
5768    struct VolatileUdf {
5769        signature: Signature,
5770    }
5771
5772    impl VolatileUdf {
5773        pub fn new() -> Self {
5774            Self {
5775                signature: Signature::exact(vec![], Volatility::Volatile),
5776            }
5777        }
5778    }
5779    impl ScalarUDFImpl for VolatileUdf {
5780        fn name(&self) -> &str {
5781            "VolatileUdf"
5782        }
5783
5784        fn signature(&self) -> &Signature {
5785            &self.signature
5786        }
5787
5788        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
5789            Ok(DataType::Int16)
5790        }
5791
5792        fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
5793            panic!("dummy - not implemented")
5794        }
5795    }
5796
5797    #[test]
5798    fn test_optimize_volatile_conditions() {
5799        let fun = Arc::new(ScalarUDF::new_from_impl(VolatileUdf::new()));
5800        let rand = Expr::ScalarFunction(ScalarFunction::new_udf(fun, vec![]));
5801        {
5802            let expr = rand
5803                .clone()
5804                .eq(lit(0))
5805                .or(col("column1").eq(lit(2)).and(rand.clone().eq(lit(0))));
5806
5807            assert_eq!(simplify(expr.clone()), expr);
5808        }
5809
5810        {
5811            let expr = col("column1")
5812                .eq(lit(2))
5813                .or(col("column1").eq(lit(2)).and(rand.clone().eq(lit(0))));
5814
5815            assert_eq!(simplify(expr), col("column1").eq(lit(2)));
5816        }
5817
5818        {
5819            let expr = (col("column1").eq(lit(2)).and(rand.clone().eq(lit(0)))).or(col(
5820                "column1",
5821            )
5822            .eq(lit(2))
5823            .and(rand.clone().eq(lit(0))));
5824
5825            assert_eq!(
5826                simplify(expr),
5827                col("column1")
5828                    .eq(lit(2))
5829                    .and((rand.clone().eq(lit(0))).or(rand.clone().eq(lit(0))))
5830            );
5831        }
5832    }
5833
5834    #[test]
5835    fn simplify_fixed_size_binary_eq_lit() {
5836        let bytes = [1u8, 2, 3].as_slice();
5837
5838        // The expression starts simple.
5839        let expr = col("c5").eq(lit(bytes));
5840
5841        // The type coercer introduces a cast.
5842        let coerced = coerce(expr.clone());
5843        let schema = expr_test_schema();
5844        assert_eq!(
5845            coerced,
5846            col("c5")
5847                .cast_to(&DataType::Binary, schema.as_ref())
5848                .unwrap()
5849                .eq(lit(bytes))
5850        );
5851
5852        // The simplifier removes the cast.
5853        assert_eq!(
5854            simplify(coerced),
5855            col("c5").eq(Expr::Literal(
5856                ScalarValue::FixedSizeBinary(3, Some(bytes.to_vec()),),
5857                None
5858            ))
5859        );
5860    }
5861
5862    #[test]
5863    fn simplify_cast_literal() {
5864        // Test that CAST(literal) expressions are evaluated at plan time
5865
5866        // CAST(123 AS Int64) should become 123i64
5867        let expr = Expr::Cast(Cast::new(Box::new(lit(123i32)), DataType::Int64));
5868        let expected = lit(123i64);
5869        assert_eq!(simplify(expr), expected);
5870
5871        // CAST(1761630189642 AS Timestamp(Nanosecond, Some("+00:00")))
5872        // Integer to timestamp cast
5873        let expr = Expr::Cast(Cast::new(
5874            Box::new(lit(1761630189642i64)),
5875            DataType::Timestamp(
5876                arrow::datatypes::TimeUnit::Nanosecond,
5877                Some("+00:00".into()),
5878            ),
5879        ));
5880        // Should evaluate to a timestamp literal
5881        let result = simplify(expr);
5882        match result {
5883            Expr::Literal(ScalarValue::TimestampNanosecond(Some(val), tz), _) => {
5884                assert_eq!(val, 1761630189642i64);
5885                assert_eq!(tz.as_deref(), Some("+00:00"));
5886            }
5887            other => panic!("Expected TimestampNanosecond literal, got: {other:?}"),
5888        }
5889
5890        // Test CAST of invalid string to timestamp - should return an error at plan time
5891        // This represents the case from the issue: CAST(Utf8("1761630189642") AS Timestamp)
5892        // "1761630189642" is NOT a valid timestamp string format
5893        let expr = Expr::Cast(Cast::new(
5894            Box::new(lit("1761630189642")),
5895            DataType::Timestamp(
5896                arrow::datatypes::TimeUnit::Nanosecond,
5897                Some("+00:00".into()),
5898            ),
5899        ));
5900
5901        // The simplification should now fail with an error at plan time
5902        let schema = test_schema();
5903        let simplifier =
5904            ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build());
5905        let result = simplifier.simplify(expr);
5906        assert!(result.is_err(), "Expected error for invalid cast");
5907        let err_msg = result.unwrap_err().to_string();
5908        assert_contains!(err_msg, "Error parsing timestamp");
5909    }
5910
5911    fn if_not_null(expr: Expr, then: bool) -> Expr {
5912        Expr::Case(Case {
5913            expr: Some(expr.is_not_null().into()),
5914            when_then_expr: vec![(lit(true).into(), lit(then).into())],
5915            else_expr: None,
5916        })
5917    }
5918
5919    // --------------------------------
5920    // --- Struct Cast Tests -----
5921    // --------------------------------
5922
5923    /// Helper to create a `Struct` literal cast expression from `source_fields` and `target_fields`.
5924    fn make_struct_cast_expr(source_fields: Fields, target_fields: Fields) -> Expr {
5925        // Create 1-row struct array (not 0-row) so it can be evaluated by simplifier
5926        let arrays: Vec<Arc<dyn Array>> = vec![
5927            Arc::new(Int32Array::from(vec![Some(1)])),
5928            Arc::new(Int32Array::from(vec![Some(2)])),
5929        ];
5930        let struct_array = StructArray::try_new(source_fields, arrays, None).unwrap();
5931
5932        Expr::Cast(Cast::new(
5933            Box::new(Expr::Literal(
5934                ScalarValue::Struct(Arc::new(struct_array)),
5935                None,
5936            )),
5937            DataType::Struct(target_fields),
5938        ))
5939    }
5940
5941    #[test]
5942    fn test_struct_cast_different_field_counts_not_foldable() {
5943        // Test that struct casts with different field counts are NOT marked as foldable
5944        // When field counts differ, const-folding should not be attempted
5945
5946        let source_fields = Fields::from(vec![
5947            Arc::new(Field::new("a", DataType::Int32, true)),
5948            Arc::new(Field::new("b", DataType::Int32, true)),
5949        ]);
5950
5951        let target_fields = Fields::from(vec![
5952            Arc::new(Field::new("x", DataType::Int32, true)),
5953            Arc::new(Field::new("y", DataType::Int32, true)),
5954            Arc::new(Field::new("z", DataType::Int32, true)),
5955        ]);
5956
5957        let expr = make_struct_cast_expr(source_fields, target_fields);
5958
5959        let simplifier = ExprSimplifier::new(
5960            SimplifyContext::builder()
5961                .with_schema(test_schema())
5962                .build(),
5963        );
5964
5965        // The cast should remain unchanged since field counts differ
5966        let result = simplifier.simplify(expr.clone()).unwrap();
5967        // Ensure const-folding was not attempted (the expression remains exactly the same)
5968        assert_eq!(
5969            result, expr,
5970            "Struct cast with different field counts should remain unchanged (no const-folding)"
5971        );
5972    }
5973
5974    #[test]
5975    fn test_struct_cast_same_field_count_foldable() {
5976        // Test that struct casts with same field counts can be considered for const-folding
5977
5978        let source_fields = Fields::from(vec![
5979            Arc::new(Field::new("a", DataType::Int32, true)),
5980            Arc::new(Field::new("b", DataType::Int32, true)),
5981        ]);
5982
5983        let target_fields = Fields::from(vec![
5984            Arc::new(Field::new("a", DataType::Int32, true)),
5985            Arc::new(Field::new("b", DataType::Int32, true)),
5986        ]);
5987
5988        let expr = make_struct_cast_expr(source_fields, target_fields);
5989
5990        let simplifier = ExprSimplifier::new(
5991            SimplifyContext::builder()
5992                .with_schema(test_schema())
5993                .build(),
5994        );
5995
5996        // The cast should be simplified
5997        let result = simplifier.simplify(expr.clone()).unwrap();
5998        // Struct casts with same field count should be const-folded to a literal
5999        assert!(matches!(result, Expr::Literal(_, _)));
6000        // Ensure the simplifier made a change (not identical to original)
6001        assert_ne!(
6002            result, expr,
6003            "Struct cast with same field count should be simplified (not identical to input)"
6004        );
6005    }
6006
6007    #[test]
6008    fn test_struct_cast_different_names_same_count() {
6009        // Test struct cast with same field count but different names
6010        // Field count matches; simplification should be skipped because names do not overlap
6011
6012        let source_fields = Fields::from(vec![
6013            Arc::new(Field::new("a", DataType::Int32, true)),
6014            Arc::new(Field::new("b", DataType::Int32, true)),
6015        ]);
6016
6017        let target_fields = Fields::from(vec![
6018            Arc::new(Field::new("x", DataType::Int32, true)),
6019            Arc::new(Field::new("y", DataType::Int32, true)),
6020        ]);
6021
6022        let expr = make_struct_cast_expr(source_fields, target_fields);
6023
6024        let simplifier = ExprSimplifier::new(
6025            SimplifyContext::builder()
6026                .with_schema(test_schema())
6027                .build(),
6028        );
6029
6030        // The cast should remain unchanged because there is no name overlap
6031        let result = simplifier.simplify(expr.clone()).unwrap();
6032        assert_eq!(
6033            result, expr,
6034            "Struct cast with different names but same field count should not be simplified"
6035        );
6036    }
6037
6038    #[test]
6039    fn test_struct_cast_empty_array_not_foldable() {
6040        // Test that struct casts with 0-row (empty) struct arrays are NOT const-folded
6041        // The simplifier uses a 1-row input batch, which causes dimension mismatches
6042        // when evaluating 0-row struct literals
6043
6044        let source_fields = Fields::from(vec![
6045            Arc::new(Field::new("a", DataType::Int32, true)),
6046            Arc::new(Field::new("b", DataType::Int32, true)),
6047        ]);
6048
6049        let target_fields = Fields::from(vec![
6050            Arc::new(Field::new("a", DataType::Int32, true)),
6051            Arc::new(Field::new("b", DataType::Int32, true)),
6052        ]);
6053
6054        // Create a 0-row (empty) struct array
6055        let arrays: Vec<Arc<dyn Array>> = vec![
6056            Arc::new(Int32Array::new(vec![].into(), None)),
6057            Arc::new(Int32Array::new(vec![].into(), None)),
6058        ];
6059        let struct_array = StructArray::try_new(source_fields, arrays, None).unwrap();
6060
6061        let expr = Expr::Cast(Cast::new(
6062            Box::new(Expr::Literal(
6063                ScalarValue::Struct(Arc::new(struct_array)),
6064                None,
6065            )),
6066            DataType::Struct(target_fields),
6067        ));
6068
6069        let simplifier = ExprSimplifier::new(
6070            SimplifyContext::builder()
6071                .with_schema(test_schema())
6072                .build(),
6073        );
6074
6075        // The cast should remain unchanged since the struct array is empty (0-row)
6076        let result = simplifier.simplify(expr.clone()).unwrap();
6077        assert_eq!(
6078            result, expr,
6079            "Struct cast with empty (0-row) array should remain unchanged"
6080        );
6081    }
6082}