1use 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#[derive(Debug, Clone, PartialEq)]
62pub struct LiteralGuarantee {
63 pub column: Column,
64 pub guarantee: Guarantee,
65 pub literals: HashSet<ScalarValue>,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70pub enum Guarantee {
71 In,
74 NotIn,
78}
79
80impl LiteralGuarantee {
81 #[allow(clippy::allow_attributes, clippy::mutable_key_type)] 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 pub fn analyze(expr: &Arc<dyn PhysicalExpr>) -> Vec<LiteralGuarantee> {
110 split_conjunction(expr)
112 .into_iter()
113 .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 let disjunctions = split_disjunction(expr);
142
143 let terms = disjunctions
161 .iter()
162 .filter_map(|expr| ColOpLit::try_new(expr))
163 .collect::<Vec<_>>();
164
165 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 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 if termsets.iter().any(|terms| terms.is_empty()) {
207 return builder;
208 }
209
210 let common_cols = find_common_columns(&termsets);
212 if common_cols.is_empty() {
213 return builder;
214 }
215
216 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#[derive(Debug, Default)]
271struct GuaranteeBuilder<'a> {
272 guarantees: Vec<Option<LiteralGuarantee>>,
276
277 map: HashMap<(&'a crate::expressions::Column, Guarantee), usize>,
280}
281
282impl<'a> GuaranteeBuilder<'a> {
283 fn new() -> Self {
284 Default::default()
285 }
286
287 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 #[allow(clippy::allow_attributes, clippy::mutable_key_type)] 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 let entry = &mut self.guarantees[*index];
321
322 let Some(existing) = entry else {
323 return self;
326 };
327
328 match existing.guarantee {
332 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 if !intersection.is_empty() {
351 existing.literals = intersection.into_iter().cloned().collect();
352 } else {
353 *entry = None;
355 }
356 }
357 }
358 } else {
359 let new_values: HashSet<_> = new_values.into_iter().collect();
361
362 let guarantee = LiteralGuarantee::new(col.name(), guarantee, new_values);
363 self.guarantees.push(Some(guarantee));
365 self.map.insert(key, self.guarantees.len() - 1);
366 }
367
368 self
369 }
370
371 fn build(self) -> Vec<LiteralGuarantee> {
373 self.guarantees.into_iter().flatten().collect()
375 }
376}
377
378fn 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 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
457struct ColOpLit<'a> {
459 col: &'a crate::expressions::Column,
460 guarantee: Guarantee,
461 lit: &'a crate::expressions::Literal,
462}
463
464impl<'a> ColOpLit<'a> {
465 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 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 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
508struct 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 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
544enum 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
580fn 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 let mut common_cols: HashSet<_> = termsets[0].iter().map(|term| term.col()).collect();
590
591 if common_cols.len() != termsets[0].len() {
595 return Vec::new();
596 }
597
598 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 test_analyze(lit(true), vec![])
629 }
630
631 #[test]
632 fn test_single() {
633 test_analyze(col("a").eq(lit("foo")), vec![in_guarantee("a", ["foo"])]);
635 test_analyze(lit("foo").eq(col("a")), vec![in_guarantee("a", ["foo"])]);
637 test_analyze(
639 col("a").not_eq(lit("foo")),
640 vec![not_in_guarantee("a", ["foo"])],
641 );
642 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 test_analyze(col("b").eq(lit(1)).and(col("b").eq(lit(2))), vec![]);
653 test_analyze(
655 col("b").eq(lit(1)).and(col("b").not_eq(lit(2))),
656 vec![
657 in_guarantee("b", [1]),
659 not_in_guarantee("b", [2]),
660 ],
661 );
662 test_analyze(
664 col("b").not_eq(lit(1)).and(col("b").eq(lit(2))),
665 vec![
666 not_in_guarantee("b", [1]),
668 in_guarantee("b", [2]),
669 ],
670 );
671 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 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 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 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 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 test_analyze(
714 col("a").eq(lit("foo")).and(col("b").eq(lit(1))),
715 vec![
716 in_guarantee("a", ["foo"]),
718 in_guarantee("b", [1]),
719 ],
720 );
721 test_analyze(
723 col("a").not_eq(lit("foo")).and(col("b").not_eq(lit(1))),
724 vec![not_in_guarantee("a", ["foo"]), not_in_guarantee("b", [1])],
726 );
727 test_analyze(
729 col("a").eq(lit("foo")).and(col("a").eq(lit("bar"))),
730 vec![],
732 );
733 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 test_analyze(
740 col("a").not_eq(lit("foo")).and(col("a").not_eq(lit("bar"))),
741 vec![not_in_guarantee("a", ["foo", "bar"])],
743 );
744 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 vec![not_in_guarantee("a", ["foo", "bar", "baz"])],
752 );
753 let expr = col("a").eq(lit("foo"));
755 test_analyze(expr.clone().and(expr), vec![in_guarantee("a", ["foo"])]);
756 test_analyze(
758 col("b").gt(lit(5)).and(col("b").eq(lit(10))),
759 vec![in_guarantee("b", [10])],
760 );
761 test_analyze(
763 col("b").gt(lit(10)).and(col("b").eq(lit(10))),
764 vec![
765 in_guarantee("b", [10]),
767 ],
768 );
769 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 vec![not_in_guarantee("a", ["foo"])],
776 );
777 }
778
779 #[test]
780 fn test_conjunction_and_disjunction_single_column() {
781 test_analyze(
783 col("b").not_eq(lit(1)).and(col("b").gt(lit(2))),
784 vec![
785 not_in_guarantee("b", [1]),
787 ],
788 );
789
790 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 ],
799 );
800 }
801
802 #[test]
803 fn test_disjunction_single_column() {
804 test_analyze(
806 col("b").eq(lit(1)).or(col("b").eq(lit(2))),
807 vec![in_guarantee("b", [1, 2])],
808 );
809 test_analyze(col("b").not_eq(lit(1)).or(col("b").eq(lit(2))), vec![]);
811 test_analyze(col("b").eq(lit(1)).or(col("b").not_eq(lit(2))), vec![]);
813 test_analyze(col("b").not_eq(lit(1)).or(col("b").not_eq(lit(2))), vec![]);
815 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 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 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 test_analyze(
845 col("a").eq(lit("foo")).or(col("b").eq(lit(1))),
846 vec![],
848 );
849 test_analyze(
851 col("a").not_eq(lit("foo")).or(col("b").not_eq(lit(1))),
852 vec![],
854 );
855 test_analyze(
857 col("a").eq(lit("foo")).or(col("a").eq(lit("bar"))),
858 vec![in_guarantee("a", ["foo", "bar"])],
859 );
860 test_analyze(
862 col("a").eq(lit("foo")).or(col("a").eq(lit("foo"))),
863 vec![in_guarantee("a", ["foo"])],
864 );
865 test_analyze(
867 col("a").not_eq(lit("foo")).or(col("a").not_eq(lit("bar"))),
868 vec![],
870 );
871 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 test_analyze(
881 (col("a").eq(lit("foo")).or(col("a").eq(lit("bar"))))
882 .and(col("a").eq(lit("baz"))),
883 vec![],
886 );
887 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 test_analyze(
895 col("a")
896 .eq(lit("foo"))
897 .or(col("a").eq(lit("bar")))
898 .or(col("b").eq(lit(1))),
899 vec![],
901 );
902 }
903
904 #[test]
905 fn test_single_inlist() {
906 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 vec![in_guarantee("b", [1, 4])],
1206 );
1207 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 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 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 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 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 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 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 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 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}