Skip to main content

datafusion_physical_expr/utils/
guarantee.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//! [`LiteralGuarantee`] predicate analysis to determine if a column is a
6//! constant.
7
8use crate::utils::split_disjunction;
9use crate::{PhysicalExpr, split_conjunction};
10use arrow::array::{Array, RecordBatch};
11use datafusion_common::{Column, HashMap, ScalarValue};
12use datafusion_expr::{Operator, Volatility};
13use std::collections::HashSet;
14use std::fmt::{self, Display, Formatter};
15use std::sync::Arc;
16
17/// Represents a guarantee that must be true for a boolean expression to
18/// evaluate to `true`.
19///
20/// The guarantee takes the form of a column and a set of literal (constant)
21/// [`ScalarValue`]s. For the expression to evaluate to `true`, the column *must
22/// satisfy* the guarantee(s).
23///
24/// To satisfy the guarantee, depending on [`Guarantee`], the values in the
25/// column must either:
26///
27/// 1. be ONLY one of that set
28/// 2. NOT be ANY of that set
29///
30/// # Uses `LiteralGuarantee`s
31///
32/// `LiteralGuarantee`s can be used to simplify filter expressions and skip data
33/// files (e.g. row groups in parquet files) by proving expressions can not
34/// possibly evaluate to `true`. For example, if we have a guarantee that `a`
35/// must be in (`1`) for a filter to evaluate to `true`, then we can skip any
36/// partition where we know that `a` never has the value of `1`.
37///
38/// **Important**: If a `LiteralGuarantee` is not satisfied, the relevant
39/// expression is *guaranteed* to evaluate to `false` or `null`. **However**,
40/// the opposite does not hold. Even if all `LiteralGuarantee`s are satisfied,
41/// that does **not** guarantee that the predicate will actually evaluate to
42/// `true`: it may still evaluate to `true`, `false` or `null`.
43///
44/// # Creating `LiteralGuarantee`s
45///
46/// Use [`LiteralGuarantee::analyze`] to extract literal guarantees from a
47/// filter predicate.
48///
49/// # Details
50/// A guarantee can be one of two forms:
51///
52/// 1. The column must be one the values for the predicate to be `true`. If the
53///    column takes on any other value, the predicate can not evaluate to `true`.
54///    For example,
55///    `(a = 1)`, `(a = 1 OR a = 2)` or `a IN (1, 2, 3)`
56///
57/// 2. The column must NOT be one of the values for the predicate to be `true`.
58///    If the column can ONLY take one of these values, the predicate can not
59///    evaluate to `true`. For example,
60///    `(a != 1)`, `(a != 1 AND a != 2)` or `a NOT IN (1, 2, 3)`
61#[derive(Debug, Clone, PartialEq)]
62pub struct LiteralGuarantee {
63    pub column: Column,
64    pub guarantee: Guarantee,
65    pub literals: HashSet<ScalarValue>,
66}
67
68/// What is guaranteed about the values for a [`LiteralGuarantee`]?
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70pub enum Guarantee {
71    /// Guarantee that the expression is `true` if `column` is one of the values. If
72    /// `column` is not one of the values, the expression can not be `true`.
73    In,
74    /// Guarantee that the expression is `true` if `column` is not ANY of the
75    /// values. If `column` only takes one of these values, the expression can
76    /// not be `true`.
77    NotIn,
78}
79
80impl LiteralGuarantee {
81    /// Create a new instance of the guarantee if the provided operator is
82    /// supported. Returns None otherwise. See [`LiteralGuarantee::analyze`] to
83    /// create these structures from an predicate (boolean expression).
84    #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key
85    fn new<'a>(
86        column_name: impl Into<String>,
87        guarantee: Guarantee,
88        literals: impl IntoIterator<Item = &'a ScalarValue>,
89    ) -> Self {
90        let literals: HashSet<_> = literals.into_iter().cloned().collect();
91
92        Self {
93            column: Column::from_name(column_name),
94            guarantee,
95            literals,
96        }
97    }
98
99    /// Return a list of [`LiteralGuarantee`]s that must be satisfied for `expr`
100    /// to evaluate to `true`.
101    ///
102    /// If more than one `LiteralGuarantee` is returned, they must **all** hold
103    /// for the expression to possibly be `true`. If any is not satisfied, the
104    /// expression is guaranteed to be `null` or `false`.
105    ///
106    /// # Notes:
107    /// 1. `expr` must be a boolean expression or inlist expression.
108    /// 2. `expr` is not simplified prior to analysis.
109    pub fn analyze(expr: &Arc<dyn PhysicalExpr>) -> Vec<LiteralGuarantee> {
110        // split conjunction: <expr> AND <expr> AND ...
111        split_conjunction(expr)
112            .into_iter()
113            // for an `AND` conjunction to be true, all terms individually must be true
114            .fold(GuaranteeBuilder::new(), |builder, expr| {
115                if let Some(cel) = ColOpLit::try_new(expr) {
116                    builder.aggregate_conjunct(&cel)
117                } else if let Some(inlist) =
118                    expr.downcast_ref::<crate::expressions::InListExpr>()
119                {
120                    if let Some(inlist) = ColInList::try_new(inlist) {
121                        builder.aggregate_multi_conjunct(
122                            inlist.col,
123                            inlist.guarantee,
124                            inlist.list.iter().map(|lit| lit.value()),
125                        )
126                    } else if let Some(projected) = project_struct_in_list(inlist) {
127                        projected
128                            .into_iter()
129                            .fold(builder, |builder, (col, values)| {
130                                builder.aggregate_multi_conjunct(
131                                    col,
132                                    Guarantee::In,
133                                    &values,
134                                )
135                            })
136                    } else {
137                        builder
138                    }
139                } else {
140                    // split disjunction: <expr> OR <expr> OR ...
141                    let disjunctions = split_disjunction(expr);
142
143                    // We are trying to add a guarantee that a column must be
144                    // in/not in a particular set of values for the expression
145                    // to evaluate to true.
146                    //
147                    // A disjunction is true, if at least one of the terms is be
148                    // true.
149                    //
150                    // Thus, we can infer a guarantee if all terms are of the
151                    // form `(col <op> literal) OR (col <op> literal) OR ...`.
152                    //
153                    // For example, we can infer that `a = 1 OR a = 2 OR a = 3`
154                    // is guaranteed to be true ONLY if a is in (`1`, `2` or `3`).
155                    //
156                    // However, for something like  `a = 1 OR a = 2 OR a < 0` we
157                    // **can't** guarantee that the predicate is only true if a
158                    // is in (`1`, `2`), as it could also be true if `a` were less
159                    // than zero.
160                    let terms = disjunctions
161                        .iter()
162                        .filter_map(|expr| ColOpLit::try_new(expr))
163                        .collect::<Vec<_>>();
164
165                    // if all terms are 'col <op> literal' with the same column
166                    // and operation we can infer any guarantees
167                    //
168                    // For those like (a != foo AND (a != bar OR a != baz)).
169                    // We can't combine the (a != bar OR a != baz) part, but
170                    // it also doesn't invalidate our knowledge that a !=
171                    // foo is required for the expression to be true.
172                    // So we can only create a multi value guarantee for `=`
173                    // (or a single value). (e.g. ignore `a != foo OR a != bar`)
174                    let first_term = terms.first();
175                    if !terms.is_empty()
176                        && terms.len() == disjunctions.len()
177                        && terms.iter().all(|term| {
178                            term.col.name() == first_term.unwrap().col.name()
179                                && term.guarantee == Guarantee::In
180                        })
181                    {
182                        builder.aggregate_multi_conjunct(
183                            first_term.unwrap().col,
184                            Guarantee::In,
185                            terms.iter().map(|term| term.lit.value()),
186                        )
187                    } else {
188                        // Handle disjunctions with conjunctions like (a = 1 AND b = 2) OR (a = 2 AND b = 3)
189                        // Extract termsets from each disjunction
190                        // if in each termset, they have same column, and the guarantee is In,
191                        // we can infer a guarantee for the column
192                        // e.g. (a = 1 AND b = 2) OR (a = 2 AND b = 3) is `a IN (1, 2) AND b IN (2, 3)`
193                        // otherwise, we can't infer a guarantee
194                        let termsets: Vec<Vec<ColOpLitOrInList>> = disjunctions
195                            .iter()
196                            .map(|expr| {
197                                split_conjunction(expr)
198                                    .into_iter()
199                                    .filter_map(ColOpLitOrInList::try_new)
200                                    .filter(|term| term.guarantee() == Guarantee::In)
201                                    .collect()
202                            })
203                            .collect();
204
205                        // Early return if any termset is empty (can't infer guarantees)
206                        if termsets.iter().any(|terms| terms.is_empty()) {
207                            return builder;
208                        }
209
210                        // Find columns that appear in all termsets
211                        let common_cols = find_common_columns(&termsets);
212                        if common_cols.is_empty() {
213                            return builder;
214                        }
215
216                        // Build guarantees for common columns
217                        let mut builder = builder;
218                        for col in common_cols {
219                            let literals: Vec<_> = termsets
220                                .iter()
221                                .filter_map(|terms| {
222                                    terms.iter().find(|term| term.col() == col).map(
223                                        |term| {
224                                            term.lits().into_iter().map(|lit| lit.value())
225                                        },
226                                    )
227                                })
228                                .flatten()
229                                .collect();
230
231                            builder = builder.aggregate_multi_conjunct(
232                                col,
233                                Guarantee::In,
234                                literals,
235                            );
236                        }
237
238                        builder
239                    }
240                }
241            })
242            .build()
243    }
244}
245
246impl Display for LiteralGuarantee {
247    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
248        let mut sorted_literals: Vec<_> =
249            self.literals.iter().map(|lit| lit.to_string()).collect();
250        sorted_literals.sort();
251        match self.guarantee {
252            Guarantee::In => write!(
253                f,
254                "{} in ({})",
255                self.column.name,
256                sorted_literals.join(", ")
257            ),
258            Guarantee::NotIn => write!(
259                f,
260                "{} not in ({})",
261                self.column.name,
262                sorted_literals.join(", ")
263            ),
264        }
265    }
266}
267
268/// Combines conjuncts (aka terms `AND`ed together) into [`LiteralGuarantee`]s,
269/// preserving insert order
270#[derive(Debug, Default)]
271struct GuaranteeBuilder<'a> {
272    /// List of guarantees that have been created so far
273    /// if we have determined a subsequent conjunct invalidates a guarantee
274    /// e.g. `a = foo AND a = bar` then the relevant guarantee will be None
275    guarantees: Vec<Option<LiteralGuarantee>>,
276
277    /// Key is the (column name, guarantee type)
278    /// Value is the index into `guarantees`
279    map: HashMap<(&'a crate::expressions::Column, Guarantee), usize>,
280}
281
282impl<'a> GuaranteeBuilder<'a> {
283    fn new() -> Self {
284        Default::default()
285    }
286
287    /// Aggregate a new single `AND col <op> literal` term to this builder
288    /// combining with existing guarantees if possible.
289    ///
290    /// # Examples
291    /// * `AND (a = 1)`: `a` is guaranteed to be 1
292    /// * `AND (a != 1)`: a is guaranteed to not be 1
293    fn aggregate_conjunct(self, col_op_lit: &ColOpLit<'a>) -> Self {
294        self.aggregate_multi_conjunct(
295            col_op_lit.col,
296            col_op_lit.guarantee,
297            [col_op_lit.lit.value()],
298        )
299    }
300
301    /// Aggregates a new single column, multi literal term to this builder
302    /// combining with previously known guarantees if possible.
303    ///
304    /// # Examples
305    /// For the following examples, we can guarantee the expression is `true` if:
306    /// * `AND (a = 1 OR a = 2 OR a = 3)`: a is in (1, 2, or 3)
307    /// * `AND (a IN (1,2,3))`: a is in (1, 2, or 3)
308    /// * `AND (a != 1 OR a != 2 OR a != 3)`: a is not in (1, 2, or 3)
309    /// * `AND (a NOT IN (1,2,3))`: a is not in (1, 2, or 3)
310    #[allow(clippy::allow_attributes, clippy::mutable_key_type)] // ScalarValue has interior mutability but is intentionally used as hash key
311    fn aggregate_multi_conjunct<'b>(
312        mut self,
313        col: &'a crate::expressions::Column,
314        guarantee: Guarantee,
315        new_values: impl IntoIterator<Item = &'b ScalarValue>,
316    ) -> Self {
317        let key = (col, guarantee);
318        if let Some(index) = self.map.get(&key) {
319            // already have a guarantee for this column
320            let entry = &mut self.guarantees[*index];
321
322            let Some(existing) = entry else {
323                // determined the previous guarantee for this column has been
324                // invalidated, nothing to do
325                return self;
326            };
327
328            // Combine conjuncts if we have `a != foo AND a != bar`. `a = foo
329            // AND a = bar` doesn't make logical sense so we don't optimize this
330            // case
331            match existing.guarantee {
332                // knew that the column could not be a set of values
333                //
334                // For example, if we previously had `a != 5` and now we see
335                // another `AND a != 6` we know that a must not be either 5 or 6
336                // for the expression to be true
337                Guarantee::NotIn => {
338                    let new_values: HashSet<_> = new_values.into_iter().collect();
339                    existing.literals.extend(new_values.into_iter().cloned());
340                }
341                Guarantee::In => {
342                    let intersection = new_values
343                        .into_iter()
344                        .filter(|new_value| existing.literals.contains(*new_value))
345                        .collect::<Vec<_>>();
346                    // for an In guarantee, if the intersection is not empty,  we can extend the guarantee
347                    // e.g. `a IN (1,2,3) AND a IN (2,3,4)` is `a IN (2,3)`
348                    // otherwise, we invalidate the guarantee
349                    // e.g. `a IN (1,2,3) AND a IN (4,5,6)` is `a IN ()`, which is invalid
350                    if !intersection.is_empty() {
351                        existing.literals = intersection.into_iter().cloned().collect();
352                    } else {
353                        // at least one was not, so invalidate the guarantee
354                        *entry = None;
355                    }
356                }
357            }
358        } else {
359            // This is a new guarantee
360            let new_values: HashSet<_> = new_values.into_iter().collect();
361
362            let guarantee = LiteralGuarantee::new(col.name(), guarantee, new_values);
363            // add it to the list of guarantees
364            self.guarantees.push(Some(guarantee));
365            self.map.insert(key, self.guarantees.len() - 1);
366        }
367
368        self
369    }
370
371    /// Return all guarantees that have been created so far
372    fn build(self) -> Vec<LiteralGuarantee> {
373        // filter out any guarantees that have been invalidated
374        self.guarantees.into_iter().flatten().collect()
375    }
376}
377
378/// Project necessary per-column guarantees; the original predicate retains tuple correlation.
379fn project_struct_in_list(
380    inlist: &crate::expressions::InListExpr,
381) -> Option<Vec<(&crate::expressions::Column, Vec<ScalarValue>)>> {
382    if inlist.negated() || inlist.is_empty() {
383        return None;
384    }
385    let expr = inlist.expr().downcast_ref::<crate::ScalarFunctionExpr>()?;
386    let literal_args = expr
387        .args()
388        .iter()
389        .map(|arg| {
390            arg.downcast_ref::<crate::expressions::Literal>()
391                .map(|lit| lit.value().clone())
392        })
393        .collect::<Vec<_>>();
394    let mapping = expr.fun().struct_field_mapping(&literal_args)?;
395    if mapping.field_accessor.signature().volatility != Volatility::Immutable {
396        return None;
397    }
398    let tuples = inlist
399        .list()
400        .iter()
401        .map(|value| {
402            let literal = value.downcast_ref::<crate::expressions::Literal>()?;
403            let ScalarValue::Struct(array) = literal.value() else {
404                return None;
405            };
406            (array.len() == 1).then_some(literal.value())
407        })
408        .collect::<Option<Vec<_>>>()?;
409    // Null tuples cannot make a positive IN predicate true.
410    let tuples = ScalarValue::iter_to_array(
411        tuples.into_iter().filter(|tuple| !tuple.is_null()).cloned(),
412    )
413    .ok()?;
414    let batch = RecordBatch::try_from_iter([("tuple", tuples)]).ok()?;
415
416    let mut projected = Vec::new();
417    for (accessor_args, source_index) in mapping.fields {
418        let column = expr
419            .args()
420            .get(source_index)?
421            .downcast_ref::<crate::expressions::Column>()?;
422        let mut args: Vec<Arc<dyn PhysicalExpr>> =
423            vec![Arc::new(crate::expressions::Column::new("tuple", 0))];
424        args.extend(accessor_args.into_iter().map(crate::expressions::lit));
425        let accessor = crate::ScalarFunctionExpr::try_new(
426            Arc::clone(&mapping.field_accessor),
427            args,
428            batch.schema_ref(),
429            Arc::new(expr.config_options().clone()),
430        )
431        .ok()?;
432        let array = accessor
433            .evaluate(&batch)
434            .ok()?
435            .into_array_of_size(batch.num_rows())
436            .ok()?;
437        let mut values = Vec::new();
438        for index in 0..array.len() {
439            let value = ScalarValue::try_from_array(array.as_ref(), index).ok()?;
440            let value = match value {
441                ScalarValue::Dictionary(_, value) => *value,
442                value => value,
443            };
444            if value.is_null() {
445                values.clear();
446                break;
447            }
448            values.push(value);
449        }
450        if !values.is_empty() {
451            projected.push((column, values));
452        }
453    }
454    Some(projected)
455}
456
457/// Represents a single `col [not]in literal` expression
458struct ColOpLit<'a> {
459    col: &'a crate::expressions::Column,
460    guarantee: Guarantee,
461    lit: &'a crate::expressions::Literal,
462}
463
464impl<'a> ColOpLit<'a> {
465    /// Returns Some(ColOpLit) if the expression is either:
466    /// 1. `col <op> literal`
467    /// 2. `literal <op> col`
468    /// 3. operator is `=` or `!=`
469    ///
470    /// Returns None otherwise
471    fn try_new(expr: &'a Arc<dyn PhysicalExpr>) -> Option<Self> {
472        let binary_expr = expr.downcast_ref::<crate::expressions::BinaryExpr>()?;
473
474        let (left, op, right) =
475            (binary_expr.left(), binary_expr.op(), binary_expr.right());
476        let guarantee = match op {
477            Operator::Eq => Guarantee::In,
478            Operator::NotEq => Guarantee::NotIn,
479            _ => return None,
480        };
481        // col <op> literal
482        if let (Some(col), Some(lit)) = (
483            left.downcast_ref::<crate::expressions::Column>(),
484            right.downcast_ref::<crate::expressions::Literal>(),
485        ) {
486            Some(Self {
487                col,
488                guarantee,
489                lit,
490            })
491        }
492        // literal <op> col
493        else if let (Some(lit), Some(col)) = (
494            left.downcast_ref::<crate::expressions::Literal>(),
495            right.downcast_ref::<crate::expressions::Column>(),
496        ) {
497            Some(Self {
498                col,
499                guarantee,
500                lit,
501            })
502        } else {
503            None
504        }
505    }
506}
507
508/// Represents a single `col [not]in literal` expression
509struct ColInList<'a> {
510    col: &'a crate::expressions::Column,
511    guarantee: Guarantee,
512    list: Vec<&'a crate::expressions::Literal>,
513}
514
515impl<'a> ColInList<'a> {
516    /// Returns Some(ColInList) if the expression is either:
517    /// 1. `col <op> (literal1, literal2, ...)`
518    /// 3. operator is `in` or `not in`
519    ///
520    /// Returns None otherwise
521    fn try_new(inlist: &'a crate::expressions::InListExpr) -> Option<Self> {
522        let col = inlist.expr().downcast_ref::<crate::expressions::Column>()?;
523
524        let literals = inlist
525            .list()
526            .iter()
527            .map(|e| e.downcast_ref::<crate::expressions::Literal>())
528            .collect::<Option<Vec<_>>>()?;
529
530        let guarantee = if inlist.negated() {
531            Guarantee::NotIn
532        } else {
533            Guarantee::In
534        };
535
536        Some(Self {
537            col,
538            guarantee,
539            list: literals,
540        })
541    }
542}
543
544/// Represents a single `col [not]in literal` expression or a single `col <op> literal` expression
545enum ColOpLitOrInList<'a> {
546    ColOpLit(ColOpLit<'a>),
547    ColInList(ColInList<'a>),
548}
549
550impl<'a> ColOpLitOrInList<'a> {
551    fn try_new(expr: &'a Arc<dyn PhysicalExpr>) -> Option<Self> {
552        match expr.downcast_ref::<crate::expressions::InListExpr>() {
553            Some(inlist) => Some(Self::ColInList(ColInList::try_new(inlist)?)),
554            None => ColOpLit::try_new(expr).map(Self::ColOpLit),
555        }
556    }
557
558    fn guarantee(&self) -> Guarantee {
559        match self {
560            Self::ColOpLit(col_op_lit) => col_op_lit.guarantee,
561            Self::ColInList(col_in_list) => col_in_list.guarantee,
562        }
563    }
564
565    fn col(&self) -> &'a crate::expressions::Column {
566        match self {
567            Self::ColOpLit(col_op_lit) => col_op_lit.col,
568            Self::ColInList(col_in_list) => col_in_list.col,
569        }
570    }
571
572    fn lits(&self) -> Vec<&'a crate::expressions::Literal> {
573        match self {
574            Self::ColOpLit(col_op_lit) => vec![col_op_lit.lit],
575            Self::ColInList(col_in_list) => col_in_list.list.clone(),
576        }
577    }
578}
579
580/// Find columns that appear in all termsets
581fn find_common_columns<'a>(
582    termsets: &[Vec<ColOpLitOrInList<'a>>],
583) -> Vec<&'a crate::expressions::Column> {
584    if termsets.is_empty() {
585        return Vec::new();
586    }
587
588    // Start with columns from the first termset
589    let mut common_cols: HashSet<_> = termsets[0].iter().map(|term| term.col()).collect();
590
591    // check if any common_col in one termset occur many times
592    // e.g. (a = 1 AND a = 2) OR (a = 2 AND b = 3), should not infer a guarantee
593    // TODO: for above case, we can infer a IN (2) AND b IN (3)
594    if common_cols.len() != termsets[0].len() {
595        return Vec::new();
596    }
597
598    // Intersect with columns from remaining termsets
599    let mut termset_cols: HashSet<&crate::expressions::Column> = HashSet::new();
600    for termset in termsets.iter().skip(1) {
601        termset_cols.clear();
602        termset_cols.extend(termset.iter().map(|term| term.col()));
603        if termset_cols.len() != termset.len() {
604            return Vec::new();
605        }
606        common_cols.retain(|col| termset_cols.contains(col));
607    }
608
609    common_cols.into_iter().collect()
610}
611
612#[cfg(test)]
613mod test {
614    use std::sync::LazyLock;
615
616    use super::*;
617    use crate::planner::logical2physical;
618
619    use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
620    use datafusion_expr::expr_fn::*;
621    use datafusion_expr::{Expr, lit};
622
623    use itertools::Itertools;
624
625    #[test]
626    fn test_literal() {
627        // a single literal offers no guarantee
628        test_analyze(lit(true), vec![])
629    }
630
631    #[test]
632    fn test_single() {
633        // a = "foo"
634        test_analyze(col("a").eq(lit("foo")), vec![in_guarantee("a", ["foo"])]);
635        // "foo" = a
636        test_analyze(lit("foo").eq(col("a")), vec![in_guarantee("a", ["foo"])]);
637        // a != "foo"
638        test_analyze(
639            col("a").not_eq(lit("foo")),
640            vec![not_in_guarantee("a", ["foo"])],
641        );
642        // "foo" != a
643        test_analyze(
644            lit("foo").not_eq(col("a")),
645            vec![not_in_guarantee("a", ["foo"])],
646        );
647    }
648
649    #[test]
650    fn test_conjunction_single_column() {
651        // b = 1 AND b = 2. This is impossible. Ideally this expression could be simplified to false
652        test_analyze(col("b").eq(lit(1)).and(col("b").eq(lit(2))), vec![]);
653        // b = 1 AND b != 2 . In theory, this could be simplified to `b = 1`.
654        test_analyze(
655            col("b").eq(lit(1)).and(col("b").not_eq(lit(2))),
656            vec![
657                // can only be true of b is 1 and b is not 2 (even though it is redundant)
658                in_guarantee("b", [1]),
659                not_in_guarantee("b", [2]),
660            ],
661        );
662        // b != 1 AND b = 2. In theory, this could be simplified to `b = 2`.
663        test_analyze(
664            col("b").not_eq(lit(1)).and(col("b").eq(lit(2))),
665            vec![
666                // can only be true of b is not 1 and b is 2 (even though it is redundant)
667                not_in_guarantee("b", [1]),
668                in_guarantee("b", [2]),
669            ],
670        );
671        // b != 1 AND b != 2
672        test_analyze(
673            col("b").not_eq(lit(1)).and(col("b").not_eq(lit(2))),
674            vec![not_in_guarantee("b", [1, 2])],
675        );
676        // b != 1 AND b != 2 and b != 3
677        test_analyze(
678            col("b")
679                .not_eq(lit(1))
680                .and(col("b").not_eq(lit(2)))
681                .and(col("b").not_eq(lit(3))),
682            vec![not_in_guarantee("b", [1, 2, 3])],
683        );
684        // b != 1 AND b = 2 and b != 3. Can only be true if b is 2 and b is not in (1, 3)
685        test_analyze(
686            col("b")
687                .not_eq(lit(1))
688                .and(col("b").eq(lit(2)))
689                .and(col("b").not_eq(lit(3))),
690            vec![not_in_guarantee("b", [1, 3]), in_guarantee("b", [2])],
691        );
692        // b != 1 AND b != 2 and b = 3 (in theory could determine b = 3)
693        test_analyze(
694            col("b")
695                .not_eq(lit(1))
696                .and(col("b").not_eq(lit(2)))
697                .and(col("b").eq(lit(3))),
698            vec![not_in_guarantee("b", [1, 2]), in_guarantee("b", [3])],
699        );
700        // b != 1 AND b != 2 and b > 3 (to be true, b can't be either 1 or 2
701        test_analyze(
702            col("b")
703                .not_eq(lit(1))
704                .and(col("b").not_eq(lit(2)))
705                .and(col("b").gt(lit(3))),
706            vec![not_in_guarantee("b", [1, 2])],
707        );
708    }
709
710    #[test]
711    fn test_conjunction_multi_column() {
712        // a = "foo" AND b = 1
713        test_analyze(
714            col("a").eq(lit("foo")).and(col("b").eq(lit(1))),
715            vec![
716                // should find both column guarantees
717                in_guarantee("a", ["foo"]),
718                in_guarantee("b", [1]),
719            ],
720        );
721        // a != "foo" AND b != 1
722        test_analyze(
723            col("a").not_eq(lit("foo")).and(col("b").not_eq(lit(1))),
724            // should find both column guarantees
725            vec![not_in_guarantee("a", ["foo"]), not_in_guarantee("b", [1])],
726        );
727        // a = "foo" AND a = "bar"
728        test_analyze(
729            col("a").eq(lit("foo")).and(col("a").eq(lit("bar"))),
730            // this predicate is impossible ( can't be both foo and bar),
731            vec![],
732        );
733        // a = "foo" AND b != "bar"
734        test_analyze(
735            col("a").eq(lit("foo")).and(col("a").not_eq(lit("bar"))),
736            vec![in_guarantee("a", ["foo"]), not_in_guarantee("a", ["bar"])],
737        );
738        // a != "foo" AND a != "bar"
739        test_analyze(
740            col("a").not_eq(lit("foo")).and(col("a").not_eq(lit("bar"))),
741            // know it isn't "foo" or "bar"
742            vec![not_in_guarantee("a", ["foo", "bar"])],
743        );
744        // a != "foo" AND a != "bar" and a != "baz"
745        test_analyze(
746            col("a")
747                .not_eq(lit("foo"))
748                .and(col("a").not_eq(lit("bar")))
749                .and(col("a").not_eq(lit("baz"))),
750            // know it isn't "foo" or "bar" or "baz"
751            vec![not_in_guarantee("a", ["foo", "bar", "baz"])],
752        );
753        // a = "foo" AND a = "foo"
754        let expr = col("a").eq(lit("foo"));
755        test_analyze(expr.clone().and(expr), vec![in_guarantee("a", ["foo"])]);
756        // b > 5 AND b = 10 (should get an b = 10 guarantee)
757        test_analyze(
758            col("b").gt(lit(5)).and(col("b").eq(lit(10))),
759            vec![in_guarantee("b", [10])],
760        );
761        // b > 10 AND b = 10 (this is impossible)
762        test_analyze(
763            col("b").gt(lit(10)).and(col("b").eq(lit(10))),
764            vec![
765                //  if b isn't 10, it can not be true (though the expression actually can never be true)
766                in_guarantee("b", [10]),
767            ],
768        );
769        // a != "foo" and (a != "bar" OR a != "baz")
770        test_analyze(
771            col("a")
772                .not_eq(lit("foo"))
773                .and(col("a").not_eq(lit("bar")).or(col("a").not_eq(lit("baz")))),
774            // a is not foo (we can't represent other knowledge about a)
775            vec![not_in_guarantee("a", ["foo"])],
776        );
777    }
778
779    #[test]
780    fn test_conjunction_and_disjunction_single_column() {
781        // b != 1 AND (b > 2)
782        test_analyze(
783            col("b").not_eq(lit(1)).and(col("b").gt(lit(2))),
784            vec![
785                // for the expression to be true, b can not be one
786                not_in_guarantee("b", [1]),
787            ],
788        );
789
790        // b = 1 AND (b = 2 OR b = 3). Could be simplified to false.
791        test_analyze(
792            col("b")
793                .eq(lit(1))
794                .and(col("b").eq(lit(2)).or(col("b").eq(lit(3)))),
795            vec![
796                // in theory, b must be 1 and one of 2,3 for this expression to be true
797                // which is a logical contradiction
798            ],
799        );
800    }
801
802    #[test]
803    fn test_disjunction_single_column() {
804        // b = 1 OR b = 2
805        test_analyze(
806            col("b").eq(lit(1)).or(col("b").eq(lit(2))),
807            vec![in_guarantee("b", [1, 2])],
808        );
809        // b != 1 OR b = 2
810        test_analyze(col("b").not_eq(lit(1)).or(col("b").eq(lit(2))), vec![]);
811        // b = 1 OR b != 2
812        test_analyze(col("b").eq(lit(1)).or(col("b").not_eq(lit(2))), vec![]);
813        // b != 1 OR b != 2
814        test_analyze(col("b").not_eq(lit(1)).or(col("b").not_eq(lit(2))), vec![]);
815        // b != 1 OR b != 2 OR b = 3 -- in theory could guarantee that b = 3
816        test_analyze(
817            col("b")
818                .not_eq(lit(1))
819                .or(col("b").not_eq(lit(2)))
820                .or(lit("b").eq(lit(3))),
821            vec![],
822        );
823        // b = 1 OR b = 2 OR b = 3
824        test_analyze(
825            col("b")
826                .eq(lit(1))
827                .or(col("b").eq(lit(2)))
828                .or(col("b").eq(lit(3))),
829            vec![in_guarantee("b", [1, 2, 3])],
830        );
831        // b = 1 OR b = 2 OR b > 3 -- can't guarantee that the expression is only true if a is in (1, 2)
832        test_analyze(
833            col("b")
834                .eq(lit(1))
835                .or(col("b").eq(lit(2)))
836                .or(lit("b").eq(lit(3))),
837            vec![],
838        );
839    }
840
841    #[test]
842    fn test_disjunction_multi_column() {
843        // a = "foo" OR b = 1
844        test_analyze(
845            col("a").eq(lit("foo")).or(col("b").eq(lit(1))),
846            // no can't have a single column guarantee (if a = "foo" then b != 1) etc
847            vec![],
848        );
849        // a != "foo" OR b != 1
850        test_analyze(
851            col("a").not_eq(lit("foo")).or(col("b").not_eq(lit(1))),
852            // No single column guarantee
853            vec![],
854        );
855        // a = "foo" OR a = "bar"
856        test_analyze(
857            col("a").eq(lit("foo")).or(col("a").eq(lit("bar"))),
858            vec![in_guarantee("a", ["foo", "bar"])],
859        );
860        // a = "foo" OR a = "foo"
861        test_analyze(
862            col("a").eq(lit("foo")).or(col("a").eq(lit("foo"))),
863            vec![in_guarantee("a", ["foo"])],
864        );
865        // a != "foo" OR a != "bar"
866        test_analyze(
867            col("a").not_eq(lit("foo")).or(col("a").not_eq(lit("bar"))),
868            // can't represent knowledge about a in this case
869            vec![],
870        );
871        // a = "foo" OR a = "bar" OR a = "baz"
872        test_analyze(
873            col("a")
874                .eq(lit("foo"))
875                .or(col("a").eq(lit("bar")))
876                .or(col("a").eq(lit("baz"))),
877            vec![in_guarantee("a", ["foo", "bar", "baz"])],
878        );
879        // (a = "foo" OR a = "bar") AND (a = "baz)"
880        test_analyze(
881            (col("a").eq(lit("foo")).or(col("a").eq(lit("bar"))))
882                .and(col("a").eq(lit("baz"))),
883            // this could potentially be represented as 2 constraints with a more
884            // sophisticated analysis
885            vec![],
886        );
887        // (a = "foo" OR a = "bar") AND (b = 1)
888        test_analyze(
889            (col("a").eq(lit("foo")).or(col("a").eq(lit("bar"))))
890                .and(col("b").eq(lit(1))),
891            vec![in_guarantee("a", ["foo", "bar"]), in_guarantee("b", [1])],
892        );
893        // (a = "foo" OR a = "bar") OR (b = 1)
894        test_analyze(
895            col("a")
896                .eq(lit("foo"))
897                .or(col("a").eq(lit("bar")))
898                .or(col("b").eq(lit(1))),
899            // can't represent knowledge about a or b in this case
900            vec![],
901        );
902    }
903
904    #[test]
905    fn test_single_inlist() {
906        // b IN (1, 2, 3)
907        test_analyze(
908            col("b").in_list(vec![lit(1), lit(2), lit(3)], false),
909            vec![in_guarantee("b", [1, 2, 3])],
910        );
911        // b NOT IN (1, 2, 3)
912        test_analyze(
913            col("b").in_list(vec![lit(1), lit(2), lit(3)], true),
914            vec![not_in_guarantee("b", [1, 2, 3])],
915        );
916        // b IN (1,2,3,4...24)
917        test_analyze(
918            col("b").in_list((1..25).map(lit).collect_vec(), false),
919            vec![in_guarantee("b", 1..25)],
920        );
921    }
922
923    #[test]
924    fn test_struct_inlist_guarantees() {
925        use crate::expressions::InListExpr;
926        use arrow::array::{ArrayRef, Int32Array, StringArray, StructArray};
927        use arrow::buffer::NullBuffer;
928
929        let make_expr = |strings: ArrayRef, nulls: Option<NullBuffer>, negated| {
930            let schema = Schema::new(vec![
931                Field::new("a", strings.data_type().clone(), true),
932                Field::new("b", DataType::Int32, true),
933            ]);
934            let expr = logical2physical(
935                &datafusion_functions::core::r#struct().call(vec![col("a"), col("b")]),
936                &schema,
937            );
938            let DataType::Struct(fields) = expr.data_type(&schema).unwrap() else {
939                unreachable!()
940            };
941            let values = Arc::new(StructArray::new(
942                fields,
943                vec![strings, Arc::new(Int32Array::from(vec![1, 2, 3]))],
944                nulls,
945            ));
946            Arc::new(
947                InListExpr::try_new_from_array(expr, values, negated, &schema).unwrap(),
948            ) as Arc<dyn PhysicalExpr>
949        };
950        let strings: ArrayRef = Arc::new(StringArray::from(vec!["foo", "foo", "bar"]));
951        assert_eq!(
952            LiteralGuarantee::analyze(&make_expr(Arc::clone(&strings), None, false)),
953            vec![
954                in_guarantee("a", ["foo", "bar"]),
955                in_guarantee("b", [1, 2, 3])
956            ]
957        );
958        assert!(
959            LiteralGuarantee::analyze(&make_expr(Arc::clone(&strings), None, true))
960                .is_empty()
961        );
962        assert!(
963            LiteralGuarantee::analyze(&make_expr(
964                Arc::clone(&strings),
965                Some(vec![false, false, false].into()),
966                false
967            ))
968            .is_empty()
969        );
970        assert_eq!(
971            LiteralGuarantee::analyze(&make_expr(
972                strings,
973                Some(vec![false, true, true].into()),
974                false
975            )),
976            vec![in_guarantee("a", ["foo", "bar"]), in_guarantee("b", [2, 3])]
977        );
978
979        let strings = StringArray::from(vec![Some("foo"), None, Some("bar")]);
980        let dictionary =
981            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
982        for data_type in [DataType::Utf8, dictionary] {
983            let strings = arrow::compute::cast(&strings, &data_type).unwrap();
984            assert_eq!(
985                LiteralGuarantee::analyze(&make_expr(strings, None, false)),
986                vec![in_guarantee("b", [1, 2, 3])]
987            );
988        }
989        let strings = arrow::compute::cast(
990            &StringArray::from(vec!["foo", "foo", "bar"]),
991            &DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
992        )
993        .unwrap();
994        assert_eq!(
995            LiteralGuarantee::analyze(&make_expr(strings, None, false)),
996            vec![
997                in_guarantee("a", ["foo", "bar"]),
998                in_guarantee("b", [1, 2, 3])
999            ]
1000        );
1001
1002        // Named fields map to nonconsecutive arguments, in a different column order.
1003        let tuple = RecordBatch::try_from_iter([
1004            ("right", Arc::new(Int32Array::from(vec![1])) as ArrayRef),
1005            ("left", Arc::new(StringArray::from(vec!["foo"])) as ArrayRef),
1006        ])
1007        .unwrap();
1008        let expr = datafusion_functions::core::named_struct().call(vec![
1009            lit("right"),
1010            col("b"),
1011            lit("left"),
1012            col("a"),
1013        ]);
1014        test_analyze(
1015            expr.in_list(
1016                vec![lit(ScalarValue::Struct(Arc::new(StructArray::from(tuple))))],
1017                false,
1018            ),
1019            vec![in_guarantee("a", ["foo"]), in_guarantee("b", [1])],
1020        );
1021
1022        let tuples = [(1, 10), (2, 20)]
1023            .into_iter()
1024            .map(|(left, right)| {
1025                let tuple = RecordBatch::try_from_iter([
1026                    ("x", Arc::new(Int32Array::from(vec![left])) as ArrayRef),
1027                    ("x", Arc::new(Int32Array::from(vec![right])) as ArrayRef),
1028                ])
1029                .unwrap();
1030                lit(ScalarValue::Struct(Arc::new(StructArray::from(tuple))))
1031            })
1032            .collect();
1033        let expr = datafusion_functions::core::named_struct().call(vec![
1034            lit("x"),
1035            col("b"),
1036            lit("x"),
1037            col("c"),
1038        ]);
1039        test_analyze(expr.in_list(tuples, false), vec![]);
1040    }
1041
1042    #[test]
1043    fn test_inlist_conjunction() {
1044        // b IN (1, 2, 3) AND b IN (2, 3, 4)
1045        test_analyze(
1046            col("b")
1047                .in_list(vec![lit(1), lit(2), lit(3)], false)
1048                .and(col("b").in_list(vec![lit(2), lit(3), lit(4)], false)),
1049            vec![in_guarantee("b", [2, 3])],
1050        );
1051        // b NOT IN (1, 2, 3) AND b IN (2, 3, 4)
1052        test_analyze(
1053            col("b")
1054                .in_list(vec![lit(1), lit(2), lit(3)], true)
1055                .and(col("b").in_list(vec![lit(2), lit(3), lit(4)], false)),
1056            vec![
1057                not_in_guarantee("b", [1, 2, 3]),
1058                in_guarantee("b", [2, 3, 4]),
1059            ],
1060        );
1061        // b NOT IN (1, 2, 3) AND b NOT IN (2, 3, 4)
1062        test_analyze(
1063            col("b")
1064                .in_list(vec![lit(1), lit(2), lit(3)], true)
1065                .and(col("b").in_list(vec![lit(2), lit(3), lit(4)], true)),
1066            vec![not_in_guarantee("b", [1, 2, 3, 4])],
1067        );
1068        // b IN (1, 2, 3) AND b = 4
1069        test_analyze(
1070            col("b")
1071                .in_list(vec![lit(1), lit(2), lit(3)], false)
1072                .and(col("b").eq(lit(4))),
1073            vec![],
1074        );
1075        // b IN (1, 2, 3) AND b = 2
1076        test_analyze(
1077            col("b")
1078                .in_list(vec![lit(1), lit(2), lit(3)], false)
1079                .and(col("b").eq(lit(2))),
1080            vec![in_guarantee("b", [2])],
1081        );
1082        // b IN (1, 2, 3) AND b != 2
1083        test_analyze(
1084            col("b")
1085                .in_list(vec![lit(1), lit(2), lit(3)], false)
1086                .and(col("b").not_eq(lit(2))),
1087            vec![in_guarantee("b", [1, 2, 3]), not_in_guarantee("b", [2])],
1088        );
1089        // b NOT IN (1, 2, 3) AND b != 4
1090        test_analyze(
1091            col("b")
1092                .in_list(vec![lit(1), lit(2), lit(3)], true)
1093                .and(col("b").not_eq(lit(4))),
1094            vec![not_in_guarantee("b", [1, 2, 3, 4])],
1095        );
1096        // b NOT IN (1, 2, 3) AND b != 2
1097        test_analyze(
1098            col("b")
1099                .in_list(vec![lit(1), lit(2), lit(3)], true)
1100                .and(col("b").not_eq(lit(2))),
1101            vec![not_in_guarantee("b", [1, 2, 3])],
1102        );
1103    }
1104
1105    #[test]
1106    fn test_inlist_with_disjunction() {
1107        // b IN (1, 2, 3) AND (b = 3 OR b = 4)
1108        test_analyze(
1109            col("b")
1110                .in_list(vec![lit(1), lit(2), lit(3)], false)
1111                .and(col("b").eq(lit(3)).or(col("b").eq(lit(4)))),
1112            vec![in_guarantee("b", [3])],
1113        );
1114        // b IN (1, 2, 3) AND (b = 4 OR b = 5)
1115        test_analyze(
1116            col("b")
1117                .in_list(vec![lit(1), lit(2), lit(3)], false)
1118                .and(col("b").eq(lit(4)).or(col("b").eq(lit(5)))),
1119            vec![],
1120        );
1121        // b NOT IN (1, 2, 3) AND (b = 3 OR b = 4)
1122        test_analyze(
1123            col("b")
1124                .in_list(vec![lit(1), lit(2), lit(3)], true)
1125                .and(col("b").eq(lit(3)).or(col("b").eq(lit(4)))),
1126            vec![not_in_guarantee("b", [1, 2, 3]), in_guarantee("b", [3, 4])],
1127        );
1128        // b IN (1, 2, 3) OR b = 2
1129        test_analyze(
1130            col("b")
1131                .in_list(vec![lit(1), lit(2), lit(3)], false)
1132                .or(col("b").eq(lit(2))),
1133            vec![in_guarantee("b", [1, 2, 3])],
1134        );
1135        // b IN (1, 2, 3) OR b != 3
1136        test_analyze(
1137            col("b")
1138                .in_list(vec![lit(1), lit(2), lit(3)], false)
1139                .or(col("b").not_eq(lit(3))),
1140            vec![],
1141        );
1142    }
1143
1144    #[test]
1145    fn test_disjunction_and_conjunction_multi_column() {
1146        // (a = "foo" AND b = 1) OR (a = "bar" AND b = 2)
1147        test_analyze(
1148            (col("a").eq(lit("foo")).and(col("b").eq(lit(1))))
1149                .or(col("a").eq(lit("bar")).and(col("b").eq(lit(2)))),
1150            vec![in_guarantee("a", ["foo", "bar"]), in_guarantee("b", [1, 2])],
1151        );
1152        // (a = "foo" AND b = 1) OR (a = "bar" AND b = 2) OR (b = 3)
1153        test_analyze(
1154            (col("a").eq(lit("foo")).and(col("b").eq(lit(1))))
1155                .or(col("a").eq(lit("bar")).and(col("b").eq(lit(2))))
1156                .or(col("b").eq(lit(3))),
1157            vec![in_guarantee("b", [1, 2, 3])],
1158        );
1159        // (a = "foo" AND b = 1) OR (a = "bar" AND b = 2) OR (c = 3)
1160        test_analyze(
1161            (col("a").eq(lit("foo")).and(col("b").eq(lit(1))))
1162                .or(col("a").eq(lit("bar")).and(col("b").eq(lit(2))))
1163                .or(col("c").eq(lit(3))),
1164            vec![],
1165        );
1166        // (a = "foo" AND b > 1) OR (a = "bar" AND b = 2)
1167        test_analyze(
1168            (col("a").eq(lit("foo")).and(col("b").gt(lit(1))))
1169                .or(col("a").eq(lit("bar")).and(col("b").eq(lit(2)))),
1170            vec![in_guarantee("a", ["foo", "bar"])],
1171        );
1172        // (a = "foo" AND b = 1) OR (b = 1 AND c = 2) OR (c = 3 AND a = "bar")
1173        test_analyze(
1174            (col("a").eq(lit("foo")).and(col("b").eq(lit(1))))
1175                .or(col("b").eq(lit(1)).and(col("c").eq(lit(2))))
1176                .or(col("c").eq(lit(3)).and(col("a").eq(lit("bar")))),
1177            vec![],
1178        );
1179        // (a = "foo" AND a = "bar") OR (a = "good" AND b = 1)
1180        // TODO: this should be `a IN ("good") AND b IN (1)`
1181        test_analyze(
1182            (col("a").eq(lit("foo")).and(col("a").eq(lit("bar"))))
1183                .or(col("a").eq(lit("good")).and(col("b").eq(lit(1)))),
1184            vec![],
1185        );
1186        // (a = "foo" AND a = "foo") OR (a = "good" AND b = 1)
1187        // TODO: this should be `a IN ("foo", "good")`
1188        test_analyze(
1189            (col("a").eq(lit("foo")).and(col("a").eq(lit("foo"))))
1190                .or(col("a").eq(lit("good")).and(col("b").eq(lit(1)))),
1191            vec![],
1192        );
1193        // (a = "foo" AND b = 3) OR (b = 4 AND b = 1) OR (b = 2 AND a = "bar")
1194        test_analyze(
1195            (col("a").eq(lit("foo")).and(col("b").eq(lit(3))))
1196                .or(col("b").eq(lit(4)).and(col("b").eq(lit(1))))
1197                .or(col("b").eq(lit(2)).and(col("a").eq(lit("bar")))),
1198            vec![],
1199        );
1200        // (b = 1 AND b > 3) OR (a = "foo" AND b = 4)
1201        test_analyze(
1202            (col("b").eq(lit(1)).and(col("b").gt(lit(3))))
1203                .or(col("a").eq(lit("foo")).and(col("b").eq(lit(4)))),
1204            // if b isn't 1 or 4, it can not be true (though the expression actually can never be true)
1205            vec![in_guarantee("b", [1, 4])],
1206        );
1207        // (a = "foo" AND b = 1) OR (a != "bar" AND b = 2)
1208        test_analyze(
1209            (col("a").eq(lit("foo")).and(col("b").eq(lit(1))))
1210                .or(col("a").not_eq(lit("bar")).and(col("b").eq(lit(2)))),
1211            vec![in_guarantee("b", [1, 2])],
1212        );
1213        // (a = "foo" AND b = 1) OR (a LIKE "%bar" AND b = 2)
1214        test_analyze(
1215            (col("a").eq(lit("foo")).and(col("b").eq(lit(1))))
1216                .or(col("a").like(lit("%bar")).and(col("b").eq(lit(2)))),
1217            vec![in_guarantee("b", [1, 2])],
1218        );
1219        // (a IN ("foo", "bar") AND b = 5) OR (a IN ("foo", "bar") AND b = 6)
1220        test_analyze(
1221            (col("a")
1222                .in_list(vec![lit("foo"), lit("bar")], false)
1223                .and(col("b").eq(lit(5))))
1224            .or(col("a")
1225                .in_list(vec![lit("foo"), lit("bar")], false)
1226                .and(col("b").eq(lit(6)))),
1227            vec![in_guarantee("a", ["foo", "bar"]), in_guarantee("b", [5, 6])],
1228        );
1229        // (a IN ("foo", "bar") AND b = 5) OR (a IN ("foo") AND b = 6)
1230        test_analyze(
1231            (col("a")
1232                .in_list(vec![lit("foo"), lit("bar")], false)
1233                .and(col("b").eq(lit(5))))
1234            .or(col("a")
1235                .in_list(vec![lit("foo")], false)
1236                .and(col("b").eq(lit(6)))),
1237            vec![in_guarantee("a", ["foo", "bar"]), in_guarantee("b", [5, 6])],
1238        );
1239        // (a NOT IN ("foo", "bar") AND b = 5) OR (a NOT IN ("foo") AND b = 6)
1240        test_analyze(
1241            (col("a")
1242                .in_list(vec![lit("foo"), lit("bar")], true)
1243                .and(col("b").eq(lit(5))))
1244            .or(col("a")
1245                .in_list(vec![lit("foo")], true)
1246                .and(col("b").eq(lit(6)))),
1247            vec![in_guarantee("b", [5, 6])],
1248        );
1249    }
1250
1251    /// Tests that analyzing expr results in the expected guarantees
1252    fn test_analyze(expr: Expr, expected: Vec<LiteralGuarantee>) {
1253        println!("Begin analyze of {expr}");
1254        let schema = schema();
1255        let physical_expr = logical2physical(&expr, &schema);
1256
1257        let actual = LiteralGuarantee::analyze(&physical_expr)
1258            .into_iter()
1259            .sorted_by_key(|g| g.column.name().to_string())
1260            .collect::<Vec<_>>();
1261        assert_eq!(
1262            expected, actual,
1263            "expr: {expr}\
1264               \n\nexpected: {expected:#?}\
1265               \n\nactual: {actual:#?}\
1266               \n\nexpr: {expr:#?}\
1267               \n\nphysical_expr: {physical_expr:#?}"
1268        );
1269    }
1270
1271    /// Guarantee that the expression is true if the column is one of the specified values
1272    fn in_guarantee<'a, I, S>(column: &str, literals: I) -> LiteralGuarantee
1273    where
1274        I: IntoIterator<Item = S>,
1275        S: Into<ScalarValue> + 'a,
1276    {
1277        let literals: Vec<_> = literals.into_iter().map(|s| s.into()).collect();
1278        LiteralGuarantee::new(column, Guarantee::In, literals.iter())
1279    }
1280
1281    /// Guarantee that the expression is true if the column is NOT any of the specified values
1282    fn not_in_guarantee<'a, I, S>(column: &str, literals: I) -> LiteralGuarantee
1283    where
1284        I: IntoIterator<Item = S>,
1285        S: Into<ScalarValue> + 'a,
1286    {
1287        let literals: Vec<_> = literals.into_iter().map(|s| s.into()).collect();
1288        LiteralGuarantee::new(column, Guarantee::NotIn, literals.iter())
1289    }
1290
1291    // Schema for testing
1292    fn schema() -> SchemaRef {
1293        static SCHEMA: LazyLock<SchemaRef> = LazyLock::new(|| {
1294            Arc::new(Schema::new(vec![
1295                Field::new("a", DataType::Utf8, false),
1296                Field::new("b", DataType::Int32, false),
1297                Field::new("c", DataType::Int32, false),
1298            ]))
1299        });
1300        Arc::clone(&SCHEMA)
1301    }
1302}