Skip to main content

datafusion_optimizer/simplify_expressions/
simplify_predicates.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//! Simplifies predicates by reducing redundant or overlapping conditions.
6//!
7//! This module provides functionality to optimize logical predicates used in query planning
8//! by eliminating redundant conditions, thus reducing the number of predicates to evaluate.
9//! Unlike the simplifier in `simplify_expressions/simplify_exprs.rs`, which focuses on
10//! general expression simplification (e.g., constant folding and algebraic simplifications),
11//! this module specifically targets predicate optimization by handling containment relationships.
12//! For example, it can simplify `x > 5 AND x > 6` to just `x > 6`, as the latter condition
13//! encompasses the former, resulting in fewer checks during query execution.
14//! Conjunctions that no value can satisfy, such as `x > 6 AND x < 5`, are replaced with
15//! `false` so that later rules can prune the plan they filter.
16
17use super::utils::{is_false, is_null};
18use datafusion_common::{Column, DataFusionError, Result, ScalarValue, internal_err};
19use datafusion_expr::utils::{
20    conjunction, disjunction, split_binary_owned, split_conjunction_owned,
21};
22use datafusion_expr::{BinaryExpr, Expr, Operator, lit};
23use indexmap::IndexSet;
24use std::cmp::Ordering;
25use std::collections::BTreeMap;
26
27const MAX_DISJUNCTION_WORK: usize = 4096;
28const MAX_DISJUNCTION_DEPTH: usize = 32;
29
30/// Simplifies a list of predicates by removing redundancies.
31///
32/// This function takes a vector of predicate expressions and groups them by the column they reference.
33/// Predicates that reference a single column and are comparison operations (e.g., >, >=, <, <=, =, !=)
34/// are analyzed to remove redundant conditions. For instance, `x > 5 AND x > 6` is simplified to
35/// `x > 6`. Predicates that contradict each other, such as `x > 6 AND x < 5`, reduce the whole
36/// conjunction to `false`. Other predicates that do not fit this pattern are retained as-is.
37/// Comparisons in an enclosing conjunction also constrain each branch of an `OR`:
38/// `x >= 10 AND (x < 3 OR x < 7)` cannot be true. This simplification preserves
39/// which rows pass a filter, rather than Boolean values in projection expressions.
40///
41/// # Arguments
42/// * `predicates` - A vector of `Expr` representing the predicates to simplify.
43///
44/// # Returns
45/// A `Result` containing a vector of simplified `Expr` predicates.
46pub fn simplify_predicates(predicates: Vec<Expr>) -> Result<Vec<Expr>> {
47    let mut remaining = MAX_DISJUNCTION_WORK;
48    simplify_with_context(predicates, &[], 0, &mut remaining)
49}
50
51/// Only descend through positive AND/OR expressions. In particular, replacing a
52/// nullable, unsatisfiable predicate with false below NOT would change its truth set.
53/// Keep assumptions outside the expressions they simplify, and never distribute
54/// conjunctions over disjunctions. The budget bounds repeated comparison work.
55fn simplify_with_context(
56    predicates: Vec<Expr>,
57    assumptions: &[Expr],
58    depth: usize,
59    remaining: &mut usize,
60) -> Result<Vec<Expr>> {
61    let predicates = simplify_conjunction(predicates)?;
62    if predicates.iter().any(is_false) {
63        return Ok(always_false());
64    }
65    let has_disjunction = predicates.iter().any(|expr| {
66        matches!(
67            expr,
68            Expr::BinaryExpr(BinaryExpr {
69                op: Operator::Or,
70                ..
71            })
72        )
73    });
74    if assumptions.is_empty() && !has_disjunction {
75        return Ok(predicates);
76    }
77    let cost = assumptions.len().saturating_add(predicates.len());
78    if depth >= MAX_DISJUNCTION_DEPTH || cost > *remaining {
79        return Ok(predicates);
80    }
81    *remaining -= cost;
82
83    let context = assumptions
84        .iter()
85        .chain(predicates.iter().filter(|expr| is_column_comparison(expr)))
86        .cloned()
87        .collect();
88    let context = simplify_conjunction(context)?;
89    if context.iter().any(is_false) {
90        return Ok(always_false());
91    }
92
93    let mut result = Vec::with_capacity(predicates.len());
94    for predicate in predicates {
95        let predicate = simplify_disjunction(predicate, &context, depth, remaining)?;
96        if is_false(&predicate) {
97            return Ok(always_false());
98        }
99        result.push(predicate);
100    }
101    Ok(result)
102}
103
104fn simplify_disjunction(
105    predicate: Expr,
106    assumptions: &[Expr],
107    depth: usize,
108    remaining: &mut usize,
109) -> Result<Expr> {
110    if !matches!(
111        predicate,
112        Expr::BinaryExpr(BinaryExpr {
113            op: Operator::Or,
114            ..
115        })
116    ) {
117        return Ok(predicate);
118    }
119    let mut simplify_branch = |branch| {
120        let original = split_conjunction_owned(branch);
121        let predicates =
122            simplify_with_context(original.clone(), assumptions, depth + 1, remaining)?;
123        // Grouping comparisons by column can merely permute an AND branch.
124        // Preserve its evaluation order when no predicates were simplified.
125        let predicates = if original.len() == predicates.len()
126            && original != predicates
127            && original.iter().collect::<IndexSet<_>>()
128                == predicates.iter().collect::<IndexSet<_>>()
129        {
130            original
131        } else {
132            predicates
133        };
134        Ok::<_, DataFusionError>(conjunction(predicates).unwrap_or_else(|| lit(true)))
135    };
136    // Flatten OR chains so the depth limit counts AND/OR nesting, not disjuncts.
137    let mut branches = Vec::new();
138    for branch in split_binary_owned(predicate, Operator::Or) {
139        let branch = simplify_branch(branch)?;
140        if !is_false(&branch) {
141            branches.push(branch);
142        }
143    }
144    Ok(disjunction(branches).unwrap_or_else(|| lit(false)))
145}
146
147fn is_column_comparison(expr: &Expr) -> bool {
148    matches!(expr,
149        Expr::BinaryExpr(BinaryExpr { left, op, right })
150            if matches!(op, Operator::Eq | Operator::NotEq | Operator::Lt
151                | Operator::LtEq | Operator::Gt | Operator::GtEq)
152            && ((matches!(left.as_ref(), Expr::Column(_)) && right.as_literal().is_some())
153                || (matches!(right.as_ref(), Expr::Column(_)) && left.as_literal().is_some()))
154    )
155}
156
157fn simplify_conjunction(predicates: Vec<Expr>) -> Result<Vec<Expr>> {
158    // Early return for simple cases
159    if predicates.len() <= 1 {
160        return Ok(predicates);
161    }
162
163    // Group predicates by their column reference
164    let mut column_predicates: BTreeMap<Column, Vec<Expr>> = BTreeMap::new();
165    let mut other_predicates = Vec::with_capacity(predicates.len());
166
167    for pred in predicates {
168        match pred {
169            Expr::BinaryExpr(BinaryExpr { left, op, right })
170                if matches!(
171                    op,
172                    Operator::Gt
173                        | Operator::GtEq
174                        | Operator::Lt
175                        | Operator::LtEq
176                        | Operator::Eq
177                        | Operator::NotEq
178                ) && !is_null(&left)
179                    && !is_null(&right)
180                    && right
181                        .as_literal()
182                        .or_else(|| left.as_literal())
183                        .is_some_and(|literal| !literal.data_type().is_nested()) =>
184            {
185                if let (Some(col), Some(_)) =
186                    (extract_column_from_expr(&left), right.as_literal())
187                {
188                    let mut right = right;
189                    normalize_literal(right.as_mut());
190                    column_predicates
191                        .entry(col)
192                        .or_default()
193                        .push(Expr::BinaryExpr(BinaryExpr { left, op, right }));
194                } else if let (Some(_), Some(col), Some(swapped_op)) = (
195                    left.as_literal(),
196                    extract_column_from_expr(&right),
197                    op.swap(),
198                ) {
199                    // Put the literal on the right so that predicates differing only in
200                    // operand order compare equal below
201                    let mut left = left;
202                    normalize_literal(left.as_mut());
203                    column_predicates
204                        .entry(col)
205                        .or_default()
206                        .push(Expr::BinaryExpr(BinaryExpr {
207                            left: right,
208                            op: swapped_op,
209                            right: left,
210                        }));
211                } else {
212                    other_predicates.push(Expr::BinaryExpr(BinaryExpr {
213                        left,
214                        op,
215                        right,
216                    }));
217                }
218            }
219            _ => other_predicates.push(pred),
220        }
221    }
222
223    // Process each column's predicates to remove redundancies
224    let mut result = other_predicates;
225    for (_, preds) in column_predicates {
226        // Literals of one column that cannot be ordered against each other carry no
227        // information we can use, so keep the predicates as they were written
228        let simplified = match simplify_column_predicates(preds.clone()) {
229            Ok(simplified) => simplified,
230            Err(_) => preds,
231        };
232        if simplified.iter().any(is_false) {
233            return Ok(always_false());
234        }
235        result.extend(simplified);
236    }
237
238    Ok(result)
239}
240
241/// Simplifies predicates related to a single column.
242///
243/// This function processes a list of predicates that all reference the same column and
244/// simplifies them based on their operators. It groups predicates into greater-than (>, >=),
245/// less-than (<, <=), equality (=) and inequality (!=) categories, then selects the most
246/// restrictive condition in each category to reduce redundancy. For example, among `x > 5`
247/// and `x > 6`, only `x > 6` is retained as it is more restrictive.
248///
249/// The reduced conditions are then compared with each other. An equality subsumes every
250/// other condition it satisfies, an inequality is dropped once a bound already excludes its
251/// value, and conditions that cannot hold at the same time, such as `x > 6 AND x < 5`,
252/// reduce the whole list to a single `false` literal.
253///
254/// # Arguments
255/// * `predicates` - A vector of `Expr` representing predicates for a single column.
256///
257/// # Returns
258/// A `Result` containing a vector of simplified `Expr` predicates for the column.
259fn simplify_column_predicates(predicates: Vec<Expr>) -> Result<Vec<Expr>> {
260    if predicates.len() <= 1 {
261        return Ok(predicates);
262    }
263
264    // Group by operator type, but combining similar operators
265    let mut greater_predicates = Vec::new(); // Combines > and >=
266    let mut less_predicates = Vec::new(); // Combines < and <=
267    let mut eq_predicates = Vec::new();
268    let mut not_eq_predicates = Vec::new();
269
270    for pred in predicates {
271        match &pred {
272            Expr::BinaryExpr(BinaryExpr { op, .. }) => match op {
273                Operator::Gt | Operator::GtEq => greater_predicates.push(pred),
274                Operator::Lt | Operator::LtEq => less_predicates.push(pred),
275                Operator::Eq => eq_predicates.push(pred),
276                Operator::NotEq => not_eq_predicates.push(pred),
277                _ => unreachable!("Unexpected operator: {}", op),
278            },
279            _ => unreachable!("Unexpected predicate {}", pred.to_string()),
280        }
281    }
282
283    // Reduce each direction to its most restrictive bound: the highest value for the
284    // greater-than-style predicates and the lowest value for the less-than-style ones.
285    let lower_bound = find_most_restrictive_predicate(&greater_predicates, true)?;
286    let upper_bound = find_most_restrictive_predicate(&less_predicates, false)?;
287
288    if let Some(eq_predicate) = eq_predicates.pop() {
289        let (_, value) = op_and_literal(&eq_predicate)?;
290
291        // An equality pins the column to a single value, so it subsumes every other
292        // predicate on that column: either the value satisfies them, which makes them
293        // redundant, or it does not and no row can pass the conjunction.
294        if !satisfies_all(
295            value,
296            eq_predicates
297                .iter()
298                .chain(not_eq_predicates.iter())
299                .chain(lower_bound.iter())
300                .chain(upper_bound.iter()),
301        )? {
302            return Ok(always_false());
303        }
304        return Ok(vec![eq_predicate]);
305    }
306
307    // Bounds that leave no room for any value cannot be satisfied together
308    if let (Some(lower), Some(upper)) = (&lower_bound, &upper_bound)
309        && is_empty_range(lower, upper)?
310    {
311        return Ok(always_false());
312    }
313
314    // An inequality is redundant once a bound already excludes the value it rules out
315    let mut result = Vec::new();
316    for not_eq_predicate in not_eq_predicates {
317        let (_, value) = op_and_literal(&not_eq_predicate)?;
318        if satisfies_all(value, lower_bound.iter().chain(upper_bound.iter()))? {
319            result.push(not_eq_predicate);
320        }
321    }
322
323    result.extend(lower_bound);
324    result.extend(upper_bound);
325
326    Ok(result)
327}
328
329/// Determines whether a lower and an upper bound leave no value that satisfies both.
330///
331/// For example `x > 5 AND x < 3` can never be true, and neither can `x > 1 AND x < 1`
332/// because both comparisons are strict. `x >= 1 AND x <= 1` on the other hand is
333/// satisfied by `x = 1`.
334///
335/// # Arguments
336/// * `lower` - A predicate using `>` or `>=`.
337/// * `upper` - A predicate using `<` or `<=`.
338///
339/// # Returns
340/// A `Result` containing `true` if the two bounds contradict each other.
341fn is_empty_range(lower: &Expr, upper: &Expr) -> Result<bool> {
342    let (lower_op, lower_value) = op_and_literal(lower)?;
343    let (upper_op, upper_value) = op_and_literal(upper)?;
344
345    Ok(match lower_value.try_cmp(upper_value)? {
346        Ordering::Less => false,
347        Ordering::Greater => true,
348        Ordering::Equal => lower_op == Operator::Gt || upper_op == Operator::Lt,
349    })
350}
351
352/// Determines whether a row whose column equals `value` passes all of `predicates`.
353///
354/// # Arguments
355/// * `value` - The literal the column is known to be equal to.
356/// * `predicates` - Predicates on that same column, each of the form `column <op> literal`.
357///
358/// # Returns
359/// A `Result` containing `false` as soon as one of the predicates rejects `value`.
360fn satisfies_all<'a>(
361    value: &ScalarValue,
362    predicates: impl IntoIterator<Item = &'a Expr>,
363) -> Result<bool> {
364    for predicate in predicates {
365        let (op, bound) = op_and_literal(predicate)?;
366        let ordering = value.try_cmp(bound)?;
367        let satisfied = match op {
368            Operator::Gt => ordering == Ordering::Greater,
369            Operator::GtEq => ordering != Ordering::Less,
370            Operator::Lt => ordering == Ordering::Less,
371            Operator::LtEq => ordering != Ordering::Greater,
372            Operator::Eq => ordering == Ordering::Equal,
373            Operator::NotEq => ordering != Ordering::Equal,
374            _ => return internal_err!("Unexpected operator: {op}"),
375        };
376        if !satisfied {
377            return Ok(false);
378        }
379    }
380
381    Ok(true)
382}
383
384/// Extracts the operator and the literal of a `column <op> literal` predicate.
385///
386/// [`simplify_predicates`] normalizes the predicates it groups by column so that the
387/// literal is always the right operand, so any other shape is an internal error.
388///
389/// # Arguments
390/// * `predicate` - A reference to an `Expr` to destructure.
391///
392/// # Returns
393/// A `Result` holding the operator and the literal the predicate compares against.
394fn op_and_literal(predicate: &Expr) -> Result<(Operator, &ScalarValue)> {
395    if let Expr::BinaryExpr(BinaryExpr { op, right, .. }) = predicate
396        && let Some(literal) = right.as_literal()
397    {
398        Ok((*op, literal))
399    } else {
400        internal_err!("Unexpected predicate {predicate}")
401    }
402}
403
404/// The executor folds `-0.0` into `0.0` before comparing floats (see
405/// `datafusion_physical_expr_common::datum::apply_cmp`), while
406/// [`ScalarValue::try_cmp`] orders `-0.0` below `0.0`. Fold it here too so the
407/// decisions in this module match what the filter will evaluate.
408fn normalize_literal(expr: &mut Expr) {
409    if let Expr::Literal(value, _) = expr {
410        let original = std::mem::replace(value, ScalarValue::Null);
411        *value = original.normalize();
412    }
413}
414
415/// Builds the predicate list of a conjunction that no row can satisfy.
416fn always_false() -> Vec<Expr> {
417    vec![lit(false)]
418}
419
420/// Finds the most restrictive predicate from a list based on literal values.
421///
422/// This function iterates through a list of predicates to identify the most restrictive one
423/// by comparing their literal values. For greater-than predicates, the highest value is most
424/// restrictive, while for less-than predicates, the lowest value is most restrictive.
425///
426/// # Arguments
427/// * `predicates` - A slice of `Expr` representing predicates to compare.
428/// * `find_greater` - A boolean indicating whether to find the highest value (true for >, >=)
429///   or the lowest value (false for <, <=).
430///
431/// # Returns
432/// A `Result` containing an `Option<Expr>` with the most restrictive predicate, if any.
433fn find_most_restrictive_predicate(
434    predicates: &[Expr],
435    find_greater: bool,
436) -> Result<Option<Expr>> {
437    if predicates.is_empty() {
438        return Ok(None);
439    }
440
441    let mut most_restrictive_idx = 0;
442    let mut best_value: Option<&ScalarValue> = None;
443
444    for (idx, pred) in predicates.iter().enumerate() {
445        if let Expr::BinaryExpr(BinaryExpr { left, op, right }) = pred {
446            // Extract the literal value based on which side has it
447            let scalar_value = match (right.as_literal(), left.as_literal()) {
448                (Some(scalar), _) => Some(scalar),
449                (_, Some(scalar)) => Some(scalar),
450                _ => None,
451            };
452
453            if let Some(scalar) = scalar_value {
454                if let Some(current_best) = best_value {
455                    let comparison = scalar.try_cmp(current_best)?;
456                    let is_better = if find_greater {
457                        comparison == Ordering::Greater
458                            || (comparison == Ordering::Equal && op == &Operator::Gt)
459                    } else {
460                        comparison == Ordering::Less
461                            || (comparison == Ordering::Equal && op == &Operator::Lt)
462                    };
463
464                    if is_better {
465                        best_value = Some(scalar);
466                        most_restrictive_idx = idx;
467                    }
468                } else {
469                    best_value = Some(scalar);
470                    most_restrictive_idx = idx;
471                }
472            }
473        }
474    }
475
476    Ok(Some(predicates[most_restrictive_idx].clone()))
477}
478
479/// Extracts a column reference from an expression, if present.
480///
481/// This function checks if the given expression is a column reference or contains one,
482/// such as within a cast operation. It returns the `Column` if found.
483///
484/// # Arguments
485/// * `expr` - A reference to an `Expr` to inspect for a column reference.
486///
487/// # Returns
488/// An `Option<Column>` containing the column reference if found, otherwise `None`.
489fn extract_column_from_expr(expr: &Expr) -> Option<Column> {
490    match expr {
491        Expr::Column(col) => Some(col.clone()),
492        _ => None,
493    }
494}
495
496#[cfg(test)]
497mod tests {
498    use super::*;
499    use arrow::datatypes::DataType;
500    use datafusion_expr::{cast, col, lit};
501
502    #[test]
503    fn test_context_budget_exhaustion_is_conservative() -> Result<()> {
504        let bound = col("x").gt_eq(lit(10));
505        let disjunction = col("x").lt(lit(3)).or(col("x").lt(lit(7)));
506        let predicates = vec![bound.clone(), disjunction.clone()];
507        let result = simplify_with_context(predicates.clone(), &[], 0, &mut 0)?;
508        assert_eq!(result.len(), 2);
509        assert!(result.contains(&bound));
510        assert!(result.contains(&disjunction));
511        assert_eq!(simplify_predicates(predicates)?, vec![lit(false)]);
512        Ok(())
513    }
514
515    #[test]
516    fn test_context_depth_limit_is_conservative() -> Result<()> {
517        let disjunction = col("x").lt(lit(3)).or(col("x").lt(lit(7)));
518        let mut remaining = MAX_DISJUNCTION_WORK;
519        let result = simplify_with_context(
520            vec![disjunction.clone()],
521            &[col("x").gt_eq(lit(10))],
522            MAX_DISJUNCTION_DEPTH,
523            &mut remaining,
524        )?;
525        assert_eq!(result, vec![disjunction]);
526        Ok(())
527    }
528
529    #[test]
530    fn test_simplify_predicates_with_cast() {
531        // Test that predicates on cast expressions are not grouped with predicates on the raw column
532        // a < 5 AND CAST(a AS varchar) < 'abc' AND a < 6
533        // Should simplify to:
534        // a < 5 AND CAST(a AS varchar) < 'abc'
535
536        let predicates = vec![
537            col("a").lt(lit(5i32)),
538            cast(col("a"), DataType::Utf8).lt(lit("abc")),
539            col("a").lt(lit(6i32)),
540        ];
541
542        let result = simplify_predicates(predicates).unwrap();
543
544        // Should have 2 predicates: a < 5 and CAST(a AS varchar) < 'abc'
545        assert_eq!(result.len(), 2);
546
547        // Check that the cast predicate is preserved
548        let has_cast_predicate = result.iter().any(|p| {
549            matches!(p, Expr::BinaryExpr(BinaryExpr { 
550                left, 
551                op: Operator::Lt, 
552                right 
553            }) if matches!(left.as_ref(), Expr::Cast(_)) && right == &Box::new(lit("abc")))
554        });
555        assert!(has_cast_predicate, "Cast predicate should be preserved");
556
557        // Check that we have the more restrictive column predicate (a < 5)
558        let has_column_predicate = result.iter().any(|p| {
559            matches!(p, Expr::BinaryExpr(BinaryExpr { 
560                left, 
561                op: Operator::Lt, 
562                right 
563            }) if left == &Box::new(col("a")) && right == &Box::new(lit(5i32)))
564        });
565        assert!(has_column_predicate, "Should have a < 5 predicate");
566    }
567
568    #[test]
569    fn test_extract_column_ignores_cast() {
570        // Test that extract_column_from_expr does not extract columns from cast expressions
571        let cast_expr = cast(col("a"), DataType::Utf8);
572        assert_eq!(extract_column_from_expr(&cast_expr), None);
573
574        // Test that it still extracts from direct column references
575        let col_expr = col("a");
576        assert_eq!(extract_column_from_expr(&col_expr), Some(Column::from("a")));
577    }
578
579    #[test]
580    fn test_eq_predicates_are_matched_regardless_of_operand_order() {
581        // a = 5 AND 5 = a is a single condition, not a contradiction
582        let predicates = vec![col("a").eq(lit(5i32)), lit(5i32).eq(col("a"))];
583
584        let result = simplify_predicates(predicates).unwrap();
585
586        assert_eq!(result, vec![col("a").eq(lit(5i32))]);
587    }
588
589    #[test]
590    fn test_strict_bound_wins_when_literal_is_on_the_left() {
591        // a >= 5 AND 5 < a is a > 5; keeping a >= 5 would let a = 5 through
592        let predicates = vec![col("a").gt_eq(lit(5i32)), lit(5i32).lt(col("a"))];
593
594        let result = simplify_predicates(predicates).unwrap();
595
596        assert_eq!(result, vec![col("a").gt(lit(5i32))]);
597    }
598
599    #[test]
600    fn test_simplify_predicates_direct_columns_only() {
601        // Test that only predicates on direct columns are simplified together
602        let predicates = vec![
603            col("a").lt(lit(5i32)),
604            col("a").lt(lit(3i32)),
605            col("b").gt(lit(10i32)),
606            col("b").gt(lit(20i32)),
607        ];
608
609        let result = simplify_predicates(predicates).unwrap();
610
611        // Should have 2 predicates: a < 3 and b > 20 (most restrictive for each column)
612        assert_eq!(result.len(), 2);
613
614        // Check for a < 3
615        let has_a_predicate = result.iter().any(|p| {
616            matches!(p, Expr::BinaryExpr(BinaryExpr { 
617                left, 
618                op: Operator::Lt, 
619                right 
620            }) if left == &Box::new(col("a")) && right == &Box::new(lit(3i32)))
621        });
622        assert!(has_a_predicate, "Should have a < 3 predicate");
623
624        // Check for b > 20
625        let has_b_predicate = result.iter().any(|p| {
626            matches!(p, Expr::BinaryExpr(BinaryExpr { 
627                left, 
628                op: Operator::Gt, 
629                right 
630            }) if left == &Box::new(col("b")) && right == &Box::new(lit(20i32)))
631        });
632        assert!(has_b_predicate, "Should have b > 20 predicate");
633    }
634
635    #[test]
636    fn test_equality_subsumes_predicates_it_satisfies() {
637        // The value a is pinned to passes every other predicate, so only a = 5 is left
638        for predicates in [
639            vec![
640                col("a").eq(lit(5i32)),
641                col("a").gt(lit(3i32)),
642                col("a").lt_eq(lit(5i32)),
643                col("a").not_eq(lit(6i32)),
644            ],
645            vec![col("a").eq(lit(5i32)), col("a").gt_eq(lit(5i32))],
646        ] {
647            let result = simplify_predicates(predicates.clone()).unwrap();
648
649            assert_eq!(result, vec![col("a").eq(lit(5i32))], "for {predicates:?}");
650        }
651    }
652
653    #[test]
654    fn test_equality_rejected_by_another_predicate_is_unsatisfiable() {
655        // Each of these pins a to a value that the other predicate excludes
656        for predicates in [
657            vec![col("a").eq(lit(5i32)), col("a").eq(lit(6i32))],
658            vec![col("a").eq(lit(5i32)), col("a").not_eq(lit(5i32))],
659            vec![col("a").eq(lit(5i32)), col("a").gt(lit(5i32))],
660            vec![col("a").eq(lit(5i32)), col("a").gt_eq(lit(6i32))],
661            vec![col("a").eq(lit(5i32)), col("a").lt(lit(3i32))],
662            vec![col("a").eq(lit(5i32)), col("a").lt_eq(lit(3i32))],
663        ] {
664            let result = simplify_predicates(predicates.clone()).unwrap();
665
666            assert_eq!(result, vec![lit(false)], "for {predicates:?}");
667        }
668    }
669
670    #[test]
671    fn test_disjoint_bounds_are_unsatisfiable() {
672        // The strict bounds exclude the value they share, so none of these can hold
673        for predicates in [
674            vec![col("a").gt(lit(5i32)), col("a").lt(lit(3i32))],
675            vec![col("a").gt(lit(1i32)), col("a").lt(lit(1i32))],
676            vec![col("a").gt_eq(lit(1i32)), col("a").lt(lit(1i32))],
677            vec![col("a").gt(lit(1i32)), col("a").lt_eq(lit(1i32))],
678        ] {
679            let result = simplify_predicates(predicates.clone()).unwrap();
680
681            assert_eq!(result, vec![lit(false)], "for {predicates:?}");
682        }
683    }
684
685    #[test]
686    fn test_satisfiable_bounds_are_kept() {
687        // The second case only leaves a = 1, but both bounds are inclusive so it holds
688        for predicates in [
689            vec![col("a").gt(lit(1i32)), col("a").lt(lit(9i32))],
690            vec![col("a").gt_eq(lit(1i32)), col("a").lt_eq(lit(1i32))],
691        ] {
692            let result = simplify_predicates(predicates.clone()).unwrap();
693
694            assert_eq!(result, predicates, "for {predicates:?}");
695        }
696    }
697
698    #[test]
699    fn test_unsatisfiable_column_discards_other_predicates() {
700        // Nothing can make the conjunction true once one column contradicts itself
701        let predicates = vec![
702            col("b").gt(lit(0i32)),
703            col("a").gt(lit(5i32)),
704            col("a").lt(lit(3i32)),
705        ];
706
707        let result = simplify_predicates(predicates).unwrap();
708
709        assert_eq!(result, vec![lit(false)]);
710    }
711
712    #[test]
713    fn test_not_eq_excluded_by_a_bound_is_removed() {
714        // a > 10 already rules out a = 5
715        let predicates = vec![col("a").gt(lit(10i32)), col("a").not_eq(lit(5i32))];
716
717        let result = simplify_predicates(predicates).unwrap();
718
719        assert_eq!(result, vec![col("a").gt(lit(10i32))]);
720    }
721
722    #[test]
723    fn test_not_eq_inside_the_bounds_is_kept() {
724        // 5 is within a > 1, so the inequality still filters rows
725        let predicates = vec![col("a").gt(lit(1i32)), col("a").not_eq(lit(5i32))];
726
727        let result = simplify_predicates(predicates).unwrap();
728
729        assert_eq!(
730            result,
731            vec![col("a").not_eq(lit(5i32)), col("a").gt(lit(1i32))]
732        );
733    }
734
735    #[test]
736    fn test_signed_zero_literals_are_normalized() {
737        let predicates = vec![col("f").eq(lit(-0.0_f64)), col("f").gt_eq(lit(0.0_f64))];
738
739        let result = simplify_predicates(predicates).unwrap();
740
741        assert_eq!(result, vec![col("f").eq(lit(0.0_f64))]);
742    }
743
744    #[test]
745    fn test_null_comparisons_are_left_alone() {
746        // Comparisons with NULL are never true, so they carry no bound to reason
747        // about. Treating NULL as an ordinary value would drop `a > NULL` for being
748        // less restrictive than `a > 5`, or drop `a != NULL` for being excluded by
749        // `a > 5`, and either would let rows through that must be filtered out.
750        for predicates in [
751            vec![
752                col("a").gt(lit(ScalarValue::Int32(None))),
753                col("a").gt(lit(5i32)),
754            ],
755            vec![
756                col("a").not_eq(lit(ScalarValue::Int32(None))),
757                col("a").gt(lit(5i32)),
758            ],
759            vec![
760                col("a").gt(lit(ScalarValue::Int32(None))),
761                col("a").lt(lit(3i32)),
762            ],
763            vec![
764                col("a").gt(lit(ScalarValue::Int32(None))),
765                col("a").lt(lit(ScalarValue::Int32(None))),
766            ],
767        ] {
768            let result = simplify_predicates(predicates.clone()).unwrap();
769
770            assert_eq!(result, predicates, "for {predicates:?}");
771        }
772    }
773}