1use arrow::{
8 array::{Array, AsArray, new_null_array},
9 datatypes::{DataType, Field, Schema},
10 record_batch::RecordBatch,
11};
12use std::borrow::Cow;
13use std::collections::HashSet;
14use std::ops::Not;
15use std::sync::Arc;
16use std::sync::LazyLock;
17
18use datafusion_common::config::ConfigOptions;
19use datafusion_common::float_semantics::has_float_leaf;
20use datafusion_common::nested_struct::has_one_of_more_common_fields;
21use datafusion_common::{
22 DFSchema, DataFusionError, Result, ScalarValue, exec_datafusion_err, internal_err,
23};
24use datafusion_common::{
25 HashMap,
26 cast::{as_large_list_array, as_list_array},
27 metadata::FieldMetadata,
28 tree_node::{Transformed, TransformedResult, TreeNode, TreeNodeRewriter},
29};
30use datafusion_expr::expr::HigherOrderFunction;
31use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
32use datafusion_expr::{
33 BinaryExpr, Case, ColumnarValue, Expr, ExprSchemable, Like, Operator, Volatility,
34 and, binary::BinaryTypeCoercer, lit, or, preimage::PreimageResult,
35};
36use datafusion_expr::{
37 Cast, TryCast,
38 simplify::{ExprSimplifyResult, REGEX_PLANNING_SIZE_LIMIT_BYTES},
39};
40use datafusion_expr::{expr::ScalarFunction, interval_arithmetic::NullableInterval};
41use datafusion_expr::{
42 expr::{InList, InSubquery},
43 utils::{iter_conjunction, iter_conjunction_owned},
44};
45use datafusion_physical_expr::{create_physical_expr, execution_props::ExecutionProps};
46
47use super::inlist_simplifier::ShortenInListSimplifier;
48use super::utils::*;
49use crate::simplify_expressions::SimplifyContext;
50use crate::simplify_expressions::cast_preimage::{
51 rewrite_cast_predicate_for_binary, rewrite_cast_predicate_for_inlist,
52 supports_cast_predicate_for_binary, supports_cast_predicate_for_inlist,
53};
54use crate::simplify_expressions::regex::simplify_regex_expr;
55use crate::{
56 analyzer::type_coercion::TypeCoercionRewriter,
57 simplify_expressions::udf_preimage::rewrite_with_preimage,
58};
59use datafusion_expr::expr_rewriter::rewrite_with_guarantees_map;
60use indexmap::IndexSet;
61use regex::{Error as RegexError, Regex, RegexBuilder};
62
63pub struct ExprSimplifier {
95 info: SimplifyContext,
96 guarantees: Vec<(Expr, NullableInterval)>,
99 canonicalize: bool,
102 max_simplifier_cycles: u32,
104}
105
106pub const THRESHOLD_INLINE_INLIST: usize = 3;
113pub const DEFAULT_MAX_SIMPLIFIER_CYCLES: u32 = 3;
114
115impl ExprSimplifier {
116 pub fn new(info: SimplifyContext) -> Self {
121 Self {
122 info,
123 guarantees: vec![],
124 canonicalize: true,
125 max_simplifier_cycles: DEFAULT_MAX_SIMPLIFIER_CYCLES,
126 }
127 }
128
129 pub fn simplify(&self, expr: Expr) -> Result<Expr> {
172 Ok(self.simplify_with_cycle_count_transformed(expr)?.0.data)
173 }
174
175 pub fn simplify_with_cycle_count_transformed(
188 &self,
189 mut expr: Expr,
190 ) -> Result<(Transformed<Expr>, u32)> {
191 let mut simplifier = Simplifier::new(&self.info);
192 let config_options = Some(Arc::clone(self.info.config_options()));
193 let mut const_evaluator = ConstEvaluator::try_new(config_options)?;
194 let mut shorten_in_list_simplifier =
195 ShortenInListSimplifier::new(self.info.schema());
196 let guarantees_map: HashMap<&Expr, &NullableInterval> =
197 self.guarantees.iter().map(|(k, v)| (k, v)).collect();
198
199 if self.canonicalize {
200 expr = expr.rewrite(&mut Canonicalizer::new()).data()?
201 }
202
203 let mut num_cycles = 0;
207 let mut has_transformed = false;
208 loop {
209 let Transformed {
210 data, transformed, ..
211 } = expr
212 .rewrite(&mut const_evaluator)?
213 .transform_data(|expr| expr.rewrite(&mut simplifier))?
214 .transform_data(|expr| {
215 rewrite_with_guarantees_map(expr, &guarantees_map)
216 })?;
217 expr = data;
218 num_cycles += 1;
219 has_transformed = has_transformed || transformed;
221 if !transformed || num_cycles >= self.max_simplifier_cycles {
222 break;
223 }
224 }
225 expr = expr.rewrite(&mut shorten_in_list_simplifier).data()?;
227 Ok((
228 Transformed::new_transformed(expr, has_transformed),
229 num_cycles,
230 ))
231 }
232
233 pub fn coerce(&self, expr: Expr, schema: &DFSchema) -> Result<Expr> {
239 let mut expr_rewrite = TypeCoercionRewriter::new(schema).with_session_time_zone(
240 self.info
241 .config_options()
242 .execution
243 .time_zone
244 .as_ref()
245 .map(|tz| tz.as_str()),
246 );
247 expr.rewrite(&mut expr_rewrite).data()
248 }
249
250 pub fn with_guarantees(mut self, guarantees: Vec<(Expr, NullableInterval)>) -> Self {
306 self.guarantees = guarantees;
307 self
308 }
309
310 pub fn with_canonicalize(mut self, canonicalize: bool) -> Self {
358 self.canonicalize = canonicalize;
359 self
360 }
361
362 pub fn with_max_cycles(mut self, max_simplifier_cycles: u32) -> Self {
411 self.max_simplifier_cycles = max_simplifier_cycles;
412 self
413 }
414}
415
416struct Canonicalizer {}
423
424impl Canonicalizer {
425 fn new() -> Self {
426 Self {}
427 }
428}
429
430impl TreeNodeRewriter for Canonicalizer {
431 type Node = Expr;
432
433 fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
434 let Expr::BinaryExpr(BinaryExpr { left, op, right }) = expr else {
435 return Ok(Transformed::no(expr));
436 };
437 match (left.as_ref(), right.as_ref(), op.swap()) {
438 (Expr::Column(left_col), Expr::Column(right_col), Some(swapped_op))
440 if right_col > left_col =>
441 {
442 Ok(Transformed::yes(Expr::BinaryExpr(BinaryExpr {
443 left: right,
444 op: swapped_op,
445 right: left,
446 })))
447 }
448 (Expr::Literal(_a, _), Expr::Column(_b), Some(swapped_op)) => {
450 Ok(Transformed::yes(Expr::BinaryExpr(BinaryExpr {
451 left: right,
452 op: swapped_op,
453 right: left,
454 })))
455 }
456 _ => Ok(Transformed::no(Expr::BinaryExpr(BinaryExpr {
457 left,
458 op,
459 right,
460 }))),
461 }
462 }
463}
464
465struct ConstEvaluator {
470 can_evaluate: Vec<bool>,
483 execution_props: ExecutionProps,
490}
491
492enum ConstSimplifyResult {
494 Simplified(ScalarValue, Option<FieldMetadata>),
496 NotSimplified(ScalarValue, Option<FieldMetadata>),
498 SimplifyRuntimeError(DataFusionError, Expr),
500 Deferred(Expr),
502}
503
504impl TreeNodeRewriter for ConstEvaluator {
505 type Node = Expr;
506
507 fn f_down(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
508 self.can_evaluate.push(true);
510
511 if !Self::can_evaluate(&expr) {
516 let parent_iter = self.can_evaluate.iter_mut().rev();
518 for p in parent_iter {
519 if !*p {
520 break;
523 }
524 *p = false;
525 }
526 }
527
528 Ok(Transformed::no(expr))
532 }
533
534 fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
535 match self.can_evaluate.pop() {
536 Some(true) => match self.evaluate_to_scalar(expr) {
541 ConstSimplifyResult::Simplified(s, m) => {
542 Ok(Transformed::yes(Expr::Literal(s, m)))
543 }
544 ConstSimplifyResult::NotSimplified(s, m) => {
545 Ok(Transformed::no(Expr::Literal(s, m)))
546 }
547 ConstSimplifyResult::SimplifyRuntimeError(err, expr) => {
548 if let Expr::Cast(Cast { ref expr, .. })
551 | Expr::TryCast(TryCast { ref expr, .. }) = expr
552 && matches!(expr.as_ref(), Expr::Literal(_, _))
553 {
554 return Err(err);
555 }
556 Ok(Transformed::yes(expr))
559 }
560 ConstSimplifyResult::Deferred(expr) => {
561 self.can_evaluate.iter_mut().for_each(|can_evaluate| {
564 *can_evaluate = false;
565 });
566 Ok(Transformed::no(expr))
567 }
568 },
569 Some(false) => Ok(Transformed::no(expr)),
570 _ => internal_err!("Failed to pop can_evaluate"),
571 }
572 }
573}
574
575static DUMMY_SCHEMA: LazyLock<Arc<Schema>> =
576 LazyLock::new(|| Arc::new(Schema::new(vec![Field::new(".", DataType::Null, true)])));
577
578static DUMMY_DF_SCHEMA: LazyLock<DFSchema> =
579 LazyLock::new(|| DFSchema::try_from(Arc::clone(&*DUMMY_SCHEMA)).unwrap());
580
581static DUMMY_BATCH: LazyLock<RecordBatch> = LazyLock::new(|| {
582 let col = new_null_array(&DataType::Null, 1);
584 RecordBatch::try_new(DUMMY_SCHEMA.clone(), vec![col]).unwrap()
585});
586
587impl ConstEvaluator {
588 pub fn try_new(config_options: Option<Arc<ConfigOptions>>) -> Result<Self> {
598 let mut execution_props = ExecutionProps::new();
602 execution_props.config_options = config_options;
603
604 Ok(Self {
605 can_evaluate: vec![],
606 execution_props,
607 })
608 }
609
610 fn volatility_ok(volatility: Volatility) -> bool {
612 match volatility {
613 Volatility::Immutable => true,
614 Volatility::Stable => true,
616 Volatility::Volatile => false,
617 }
618 }
619
620 fn can_evaluate(expr: &Expr) -> bool {
623 match expr {
629 #[expect(deprecated)]
631 Expr::AggregateFunction { .. }
632 | Expr::ScalarVariable(_, _)
633 | Expr::Column(_)
634 | Expr::OuterReferenceColumn(_, _)
635 | Expr::Exists { .. }
636 | Expr::InSubquery(_)
637 | Expr::SetComparison(_)
638 | Expr::ScalarSubquery(_)
639 | Expr::WindowFunction { .. }
640 | Expr::GroupingSet(_)
641 | Expr::Wildcard { .. }
642 | Expr::Placeholder(_) => false,
643 Expr::ScalarFunction(ScalarFunction { func, .. }) => {
644 Self::volatility_ok(func.signature().volatility)
645 }
646 Expr::HigherOrderFunction(HigherOrderFunction { func, .. }) => {
647 Self::volatility_ok(func.signature().volatility)
648 }
649 Expr::Cast(Cast { expr, field }) | Expr::TryCast(TryCast { expr, field }) => {
650 if let (
651 Ok(DataType::Struct(source_fields)),
652 DataType::Struct(target_fields),
653 ) = (expr.get_type(&DFSchema::empty()), field.data_type())
654 {
655 if source_fields.len() != target_fields.len() {
657 return false;
658 }
659
660 if !has_one_of_more_common_fields(&source_fields, target_fields) {
662 return false;
663 }
664
665 if let Expr::Literal(ScalarValue::Struct(struct_array), _) =
669 expr.as_ref()
670 && struct_array.len() == 0
671 {
672 return false;
673 }
674 }
675 true
676 }
677 Expr::Literal(_, _)
678 | Expr::Alias(..)
679 | Expr::Unnest(_)
680 | Expr::BinaryExpr { .. }
681 | Expr::Not(_)
682 | Expr::IsNotNull(_)
683 | Expr::IsNull(_)
684 | Expr::IsTrue(_)
685 | Expr::IsFalse(_)
686 | Expr::IsUnknown(_)
687 | Expr::IsNotTrue(_)
688 | Expr::IsNotFalse(_)
689 | Expr::IsNotUnknown(_)
690 | Expr::Negative(_)
691 | Expr::Between { .. }
692 | Expr::Like { .. }
693 | Expr::SimilarTo { .. }
694 | Expr::Case(_)
695 | Expr::InList { .. }
696 | Expr::Lambda(_)
697 | Expr::LambdaVariable(_) => true,
698 }
699 }
700
701 pub(crate) fn evaluate_to_scalar(&mut self, expr: Expr) -> ConstSimplifyResult {
703 if let Expr::Literal(s, m) = expr {
704 return ConstSimplifyResult::NotSimplified(s, m);
705 }
706
707 if !should_evaluate_const_expr(&expr) {
708 return ConstSimplifyResult::Deferred(expr);
709 }
710
711 let phys_expr = match create_physical_expr(
712 &expr,
713 &DUMMY_DF_SCHEMA,
714 &self.execution_props,
715 &PhysicalPlanningContext::default(),
716 ) {
717 Ok(e) => e,
718 Err(err) => return ConstSimplifyResult::SimplifyRuntimeError(err, expr),
719 };
720 let metadata = phys_expr
721 .return_field(DUMMY_BATCH.schema_ref())
722 .ok()
723 .and_then(|f| {
724 let m = f.metadata();
725 match m.is_empty() {
726 true => None,
727 false => Some(FieldMetadata::from(m)),
728 }
729 });
730 let col_val = match phys_expr.evaluate(&DUMMY_BATCH) {
731 Ok(v) => v,
732 Err(err) => return ConstSimplifyResult::SimplifyRuntimeError(err, expr),
733 };
734 match col_val {
735 ColumnarValue::Array(a) => {
736 if a.len() != 1 {
737 ConstSimplifyResult::SimplifyRuntimeError(
738 exec_datafusion_err!(
739 "Could not evaluate the expression, found a result of length {}",
740 a.len()
741 ),
742 expr,
743 )
744 } else if as_list_array(&a).is_ok() {
745 ConstSimplifyResult::Simplified(
746 ScalarValue::List(a.as_list::<i32>().to_owned().into()),
747 metadata,
748 )
749 } else if as_large_list_array(&a).is_ok() {
750 ConstSimplifyResult::Simplified(
751 ScalarValue::LargeList(a.as_list::<i64>().to_owned().into()),
752 metadata,
753 )
754 } else {
755 match ScalarValue::try_from_array(&a, 0) {
757 Ok(s) => ConstSimplifyResult::Simplified(s, metadata),
758 Err(err) => ConstSimplifyResult::SimplifyRuntimeError(err, expr),
759 }
760 }
761 }
762 ColumnarValue::Scalar(s) => ConstSimplifyResult::Simplified(s, metadata),
763 }
764 }
765}
766
767fn should_evaluate_const_expr(expr: &Expr) -> bool {
768 match expr {
769 Expr::ScalarFunction(ScalarFunction { func, args }) => {
770 let Some(args) = args
771 .iter()
772 .map(|arg| match arg {
773 Expr::Literal(value, _) => Some(value),
774 _ => None,
775 })
776 .collect::<Option<Vec<_>>>()
777 else {
778 return true;
779 };
780 func.should_evaluate_const(&args)
781 }
782 Expr::BinaryExpr(BinaryExpr { op, right, .. })
783 if matches!(
784 op,
785 Operator::RegexMatch
786 | Operator::RegexNotMatch
787 | Operator::RegexIMatch
788 | Operator::RegexNotIMatch
789 ) =>
790 {
791 regex_is_within_planning_budget(op, right)
792 }
793 _ => true,
794 }
795}
796
797fn regex_is_within_planning_budget(op: &Operator, pattern: &Expr) -> bool {
798 let Expr::Literal(pattern, _) = pattern else {
799 return true;
800 };
801 let Some(pattern) = pattern.try_as_str().flatten() else {
802 return true;
803 };
804 let mut builder = RegexBuilder::new(pattern);
805 builder.size_limit(REGEX_PLANNING_SIZE_LIMIT_BYTES);
806 if matches!(op, Operator::RegexIMatch | Operator::RegexNotIMatch) {
807 builder.case_insensitive(true);
808 }
809 !matches!(builder.build(), Err(RegexError::CompiledTooBig(_)))
810}
811
812struct Simplifier<'a> {
822 info: &'a SimplifyContext,
823}
824
825impl<'a> Simplifier<'a> {
826 pub fn new(info: &'a SimplifyContext) -> Self {
827 Self { info }
828 }
829}
830
831fn modulo_one_is_zero_type(data_type: &DataType) -> bool {
833 match data_type {
834 DataType::Int8
835 | DataType::Int16
836 | DataType::Int32
837 | DataType::Int64
838 | DataType::UInt8
839 | DataType::UInt16
840 | DataType::UInt32
841 | DataType::UInt64 => true,
842 DataType::Decimal32(_, scale)
844 | DataType::Decimal64(_, scale)
845 | DataType::Decimal128(_, scale)
846 | DataType::Decimal256(_, scale) => *scale <= 0,
847 _ => false,
848 }
849}
850
851impl TreeNodeRewriter for Simplifier<'_> {
852 type Node = Expr;
853
854 fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
856 use datafusion_expr::Operator::{
857 And, BitwiseAnd, BitwiseOr, BitwiseShiftLeft, BitwiseShiftRight, BitwiseXor,
858 Divide, Eq, Modulo, Multiply, NotEq, Or, RegexIMatch, RegexMatch,
859 RegexNotIMatch, RegexNotMatch,
860 };
861
862 let info = self.info;
863 Ok(match expr {
864 ref expr @ Expr::BinaryExpr(BinaryExpr {
868 ref left,
869 ref op,
870 ref right,
871 }) if op.returns_null_on_null()
872 && (is_null(left.as_ref()) || is_null(right.as_ref())) =>
873 {
874 Transformed::yes(Expr::Literal(
875 ScalarValue::try_new_null(&info.get_data_type(expr)?)?,
876 None,
877 ))
878 }
879
880 Expr::BinaryExpr(BinaryExpr {
882 left,
883 op: And | Or,
884 right,
885 }) if is_null(&left) && is_null(&right) => Transformed::yes(lit_bool_null()),
886
887 Expr::BinaryExpr(BinaryExpr {
895 left,
896 op: Eq,
897 right,
898 }) if is_bool_lit(&left) && info.is_boolean_type(&right)? => {
899 Transformed::yes(match as_bool_lit(&left)? {
900 Some(true) => *right,
901 Some(false) => Expr::Not(right),
902 None => lit_bool_null(),
903 })
904 }
905 Expr::BinaryExpr(BinaryExpr {
909 left,
910 op: Eq,
911 right,
912 }) if is_bool_lit(&right) && info.is_boolean_type(&left)? => {
913 Transformed::yes(match as_bool_lit(&right)? {
914 Some(true) => *left,
915 Some(false) => Expr::Not(left),
916 None => lit_bool_null(),
917 })
918 }
919 Expr::BinaryExpr(BinaryExpr {
924 left,
925 op: Eq,
926 right,
927 }) if (left == right) & !left.is_volatile() => {
928 Transformed::yes(match !info.nullable(&left)? {
929 true => lit(true),
930 false => Expr::BinaryExpr(BinaryExpr {
931 left: Box::new(Expr::IsNotNull(left)),
932 op: Or,
933 right: Box::new(lit_bool_null()),
934 }),
935 })
936 }
937
938 Expr::BinaryExpr(BinaryExpr {
945 left,
946 op: NotEq,
947 right,
948 }) if is_bool_lit(&left) && info.is_boolean_type(&right)? => {
949 Transformed::yes(match as_bool_lit(&left)? {
950 Some(true) => Expr::Not(right),
951 Some(false) => *right,
952 None => lit_bool_null(),
953 })
954 }
955 Expr::BinaryExpr(BinaryExpr {
959 left,
960 op: NotEq,
961 right,
962 }) if is_bool_lit(&right) && info.is_boolean_type(&left)? => {
963 Transformed::yes(match as_bool_lit(&right)? {
964 Some(true) => Expr::Not(left),
965 Some(false) => *left,
966 None => lit_bool_null(),
967 })
968 }
969
970 Expr::BinaryExpr(BinaryExpr {
976 left,
977 op: Or,
978 right: _,
979 }) if is_true(&left) => Transformed::yes(*left),
980 Expr::BinaryExpr(BinaryExpr {
982 left,
983 op: Or,
984 right,
985 }) if is_false(&left) => Transformed::yes(*right),
986 Expr::BinaryExpr(BinaryExpr {
988 left: _,
989 op: Or,
990 right,
991 }) if is_true(&right) => Transformed::yes(*right),
992 Expr::BinaryExpr(BinaryExpr {
994 left,
995 op: Or,
996 right,
997 }) if is_false(&right) => Transformed::yes(*left),
998 Expr::BinaryExpr(BinaryExpr {
1000 left,
1001 op: Or,
1002 right,
1003 }) if is_not_of(&right, &left) && !info.nullable(&left)? => {
1004 Transformed::yes(lit(true))
1005 }
1006 Expr::BinaryExpr(BinaryExpr {
1008 left,
1009 op: Or,
1010 right,
1011 }) if is_not_of(&left, &right) && !info.nullable(&right)? => {
1012 Transformed::yes(lit(true))
1013 }
1014 Expr::BinaryExpr(BinaryExpr {
1016 left,
1017 op: Or,
1018 right,
1019 }) if expr_contains(&left, &right, Or) => Transformed::yes(*left),
1020 Expr::BinaryExpr(BinaryExpr {
1022 left,
1023 op: Or,
1024 right,
1025 }) if expr_contains(&right, &left, Or) => Transformed::yes(*right),
1026 Expr::BinaryExpr(BinaryExpr {
1028 left,
1029 op: Or,
1030 right,
1031 }) if is_op_with(And, &right, &left) => Transformed::yes(*left),
1032 Expr::BinaryExpr(BinaryExpr {
1034 left,
1035 op: Or,
1036 right,
1037 }) if is_op_with(And, &left, &right) => Transformed::yes(*right),
1038 Expr::BinaryExpr(BinaryExpr {
1041 left,
1042 op: Or,
1043 right,
1044 }) if has_common_conjunction(&left, &right) => {
1045 let lhs: IndexSet<Expr> = iter_conjunction_owned(*left).collect();
1046 let (common, rhs): (Vec<_>, Vec<_>) = iter_conjunction_owned(*right)
1047 .partition(|e| lhs.contains(e) && !e.is_volatile());
1048
1049 let new_rhs = rhs.into_iter().reduce(and);
1050 let new_lhs = lhs.into_iter().filter(|e| !common.contains(e)).reduce(and);
1051 let common_conjunction = common.into_iter().reduce(and).unwrap();
1052
1053 let new_expr = match (new_lhs, new_rhs) {
1054 (Some(lhs), Some(rhs)) => and(common_conjunction, or(lhs, rhs)),
1055 (_, _) => common_conjunction,
1056 };
1057 Transformed::yes(new_expr)
1058 }
1059
1060 Expr::BinaryExpr(BinaryExpr {
1066 left,
1067 op: And,
1068 right,
1069 }) if is_true(&left) => Transformed::yes(*right),
1070 Expr::BinaryExpr(BinaryExpr {
1072 left,
1073 op: And,
1074 right: _,
1075 }) if is_false(&left) => Transformed::yes(*left),
1076 Expr::BinaryExpr(BinaryExpr {
1078 left,
1079 op: And,
1080 right,
1081 }) if is_true(&right) => Transformed::yes(*left),
1082 Expr::BinaryExpr(BinaryExpr {
1084 left: _,
1085 op: And,
1086 right,
1087 }) if is_false(&right) => Transformed::yes(*right),
1088 Expr::BinaryExpr(BinaryExpr {
1090 left,
1091 op: And,
1092 right,
1093 }) if is_not_of(&right, &left) && !info.nullable(&left)? => {
1094 Transformed::yes(lit(false))
1095 }
1096 Expr::BinaryExpr(BinaryExpr {
1098 left,
1099 op: And,
1100 right,
1101 }) if is_not_of(&left, &right) && !info.nullable(&right)? => {
1102 Transformed::yes(lit(false))
1103 }
1104 Expr::BinaryExpr(BinaryExpr {
1106 left,
1107 op: And,
1108 right,
1109 }) if expr_contains(&left, &right, And) => Transformed::yes(*left),
1110 Expr::BinaryExpr(BinaryExpr {
1112 left,
1113 op: And,
1114 right,
1115 }) if expr_contains(&right, &left, And) => Transformed::yes(*right),
1116 Expr::BinaryExpr(BinaryExpr {
1118 left,
1119 op: And,
1120 right,
1121 }) if is_op_with(Or, &right, &left) => Transformed::yes(*left),
1122 Expr::BinaryExpr(BinaryExpr {
1124 left,
1125 op: And,
1126 right,
1127 }) if is_op_with(Or, &left, &right) => Transformed::yes(*right),
1128 Expr::BinaryExpr(BinaryExpr {
1130 left,
1131 op: And,
1132 right,
1133 }) if can_reduce_to_equal_statement(&left, &right) => {
1134 if let Expr::BinaryExpr(BinaryExpr {
1135 left: left_left,
1136 right: left_right,
1137 ..
1138 }) = *left
1139 {
1140 Transformed::yes(Expr::BinaryExpr(BinaryExpr {
1141 left: left_left,
1142 op: Eq,
1143 right: left_right,
1144 }))
1145 } else {
1146 return internal_err!(
1147 "can_reduce_to_equal_statement should only be called with a BinaryExpr"
1148 );
1149 }
1150 }
1151 Expr::BinaryExpr(BinaryExpr {
1153 left,
1154 op: And,
1155 right,
1156 }) if is_eq_and_ne_with_different_literal(&left, &right) => {
1157 Transformed::yes(*left)
1158 }
1159 Expr::BinaryExpr(BinaryExpr {
1161 left,
1162 op: And,
1163 right,
1164 }) if is_eq_and_ne_with_different_literal(&right, &left) => {
1165 Transformed::yes(*right)
1166 }
1167
1168 Expr::BinaryExpr(BinaryExpr {
1174 left,
1175 op: Multiply,
1176 right,
1177 }) if is_one(&right) => {
1178 simplify_right_is_one_case(info, left, &Multiply, &right)?
1179 }
1180 Expr::BinaryExpr(BinaryExpr {
1182 left,
1183 op: Multiply,
1184 right,
1185 }) if is_one(&left) => {
1186 simplify_right_is_one_case(info, right, &Multiply, &left)?
1188 }
1189
1190 Expr::BinaryExpr(BinaryExpr {
1192 left,
1193 op: Multiply,
1194 right,
1195 }) if !info.nullable(&left)?
1196 && !info.get_data_type(&left)?.is_floating()
1197 && is_zero(&right) =>
1198 {
1199 Transformed::yes(*right)
1200 }
1201 Expr::BinaryExpr(BinaryExpr {
1203 left,
1204 op: Multiply,
1205 right,
1206 }) if !info.nullable(&right)?
1207 && !info.get_data_type(&right)?.is_floating()
1208 && is_zero(&left) =>
1209 {
1210 Transformed::yes(*left)
1211 }
1212
1213 Expr::BinaryExpr(BinaryExpr {
1219 left,
1220 op: Divide,
1221 right,
1222 }) if is_one(&right) => {
1223 simplify_right_is_one_case(info, left, &Divide, &right)?
1224 }
1225
1226 Expr::BinaryExpr(BinaryExpr {
1232 left,
1233 op: Modulo,
1234 right,
1235 }) if !info.nullable(&left)?
1236 && modulo_one_is_zero_type(&info.get_data_type(&left)?)
1237 && is_one(&right) =>
1238 {
1239 Transformed::yes(Expr::Literal(
1240 ScalarValue::new_zero(&info.get_data_type(&left)?)?,
1241 None,
1242 ))
1243 }
1244
1245 Expr::BinaryExpr(BinaryExpr {
1251 left,
1252 op: BitwiseAnd,
1253 right,
1254 }) if !info.nullable(&left)? && is_zero(&right) => Transformed::yes(*right),
1255
1256 Expr::BinaryExpr(BinaryExpr {
1258 left,
1259 op: BitwiseAnd,
1260 right,
1261 }) if !info.nullable(&right)? && is_zero(&left) => Transformed::yes(*left),
1262
1263 Expr::BinaryExpr(BinaryExpr {
1265 left,
1266 op: BitwiseAnd,
1267 right,
1268 }) if expr_contains(&left, &right, BitwiseAnd) => Transformed::yes(*left),
1269
1270 Expr::BinaryExpr(BinaryExpr {
1272 left,
1273 op: BitwiseAnd,
1274 right,
1275 }) if expr_contains(&right, &left, BitwiseAnd) => Transformed::yes(*right),
1276
1277 Expr::BinaryExpr(BinaryExpr {
1279 left,
1280 op: BitwiseAnd,
1281 right,
1282 }) if !info.nullable(&right)? && is_op_with(BitwiseOr, &right, &left) => {
1283 Transformed::yes(*left)
1284 }
1285
1286 Expr::BinaryExpr(BinaryExpr {
1288 left,
1289 op: BitwiseAnd,
1290 right,
1291 }) if !info.nullable(&left)? && is_op_with(BitwiseOr, &left, &right) => {
1292 Transformed::yes(*right)
1293 }
1294
1295 Expr::BinaryExpr(BinaryExpr {
1301 left,
1302 op: BitwiseOr,
1303 right,
1304 }) if is_zero(&right) => Transformed::yes(*left),
1305
1306 Expr::BinaryExpr(BinaryExpr {
1308 left,
1309 op: BitwiseOr,
1310 right,
1311 }) if is_zero(&left) => Transformed::yes(*right),
1312
1313 Expr::BinaryExpr(BinaryExpr {
1315 left,
1316 op: BitwiseOr,
1317 right,
1318 }) if expr_contains(&left, &right, BitwiseOr) => Transformed::yes(*left),
1319
1320 Expr::BinaryExpr(BinaryExpr {
1322 left,
1323 op: BitwiseOr,
1324 right,
1325 }) if expr_contains(&right, &left, BitwiseOr) => Transformed::yes(*right),
1326
1327 Expr::BinaryExpr(BinaryExpr {
1329 left,
1330 op: BitwiseOr,
1331 right,
1332 }) if !info.nullable(&right)? && is_op_with(BitwiseAnd, &right, &left) => {
1333 Transformed::yes(*left)
1334 }
1335
1336 Expr::BinaryExpr(BinaryExpr {
1338 left,
1339 op: BitwiseOr,
1340 right,
1341 }) if !info.nullable(&left)? && is_op_with(BitwiseAnd, &left, &right) => {
1342 Transformed::yes(*right)
1343 }
1344
1345 Expr::BinaryExpr(BinaryExpr {
1351 left,
1352 op: BitwiseXor,
1353 right,
1354 }) if !info.nullable(&left)? && is_zero(&right) => Transformed::yes(*left),
1355
1356 Expr::BinaryExpr(BinaryExpr {
1358 left,
1359 op: BitwiseXor,
1360 right,
1361 }) if !info.nullable(&right)? && is_zero(&left) => Transformed::yes(*right),
1362
1363 Expr::BinaryExpr(BinaryExpr {
1365 left,
1366 op: BitwiseXor,
1367 right,
1368 }) if !info.nullable(&right)? && expr_contains(&left, &right, BitwiseXor) => {
1369 let expr = delete_xor_in_complex_expr(&left, &right, false);
1370 Transformed::yes(if expr == *right {
1371 Expr::Literal(
1372 ScalarValue::new_zero(&info.get_data_type(&right)?)?,
1373 None,
1374 )
1375 } else {
1376 expr
1377 })
1378 }
1379
1380 Expr::BinaryExpr(BinaryExpr {
1382 left,
1383 op: BitwiseXor,
1384 right,
1385 }) if !info.nullable(&left)? && expr_contains(&right, &left, BitwiseXor) => {
1386 let expr = delete_xor_in_complex_expr(&right, &left, true);
1387 Transformed::yes(if expr == *left {
1388 Expr::Literal(
1389 ScalarValue::new_zero(&info.get_data_type(&left)?)?,
1390 None,
1391 )
1392 } else {
1393 expr
1394 })
1395 }
1396
1397 Expr::BinaryExpr(BinaryExpr {
1403 left,
1404 op: BitwiseShiftRight,
1405 right,
1406 }) if is_zero(&right) => Transformed::yes(*left),
1407
1408 Expr::BinaryExpr(BinaryExpr {
1414 left,
1415 op: BitwiseShiftLeft,
1416 right,
1417 }) if is_zero(&right) => Transformed::yes(*left),
1418
1419 Expr::Not(inner) => Transformed::yes(negate_clause(*inner)),
1423
1424 Expr::Negative(inner) => match *inner {
1430 Expr::Negative(inner) => Transformed::yes(*inner),
1431 inner => Transformed::no(Expr::Negative(Box::new(inner))),
1432 },
1433
1434 Expr::BinaryExpr(BinaryExpr {
1442 left,
1443 op: op @ (Eq | NotEq),
1444 right,
1445 }) if is_case_with_literal_outputs(&left) && is_lit(&right) => {
1446 let case = into_case(*left)?;
1447 Transformed::yes(Expr::Case(Case {
1448 expr: None,
1449 when_then_expr: case
1450 .when_then_expr
1451 .into_iter()
1452 .map(|(when, then)| {
1453 (
1454 when,
1455 Box::new(Expr::BinaryExpr(BinaryExpr {
1456 left: then,
1457 op,
1458 right: right.clone(),
1459 })),
1460 )
1461 })
1462 .collect(),
1463 else_expr: case.else_expr.map(|els| {
1464 Box::new(Expr::BinaryExpr(BinaryExpr {
1465 left: els,
1466 op,
1467 right,
1468 }))
1469 }),
1470 }))
1471 }
1472
1473 Expr::Case(Case {
1479 expr: None,
1480 when_then_expr,
1481 mut else_expr,
1482 }) if when_then_expr
1483 .iter()
1484 .any(|(when, _)| is_true(when.as_ref()) || is_false(when.as_ref())) =>
1485 {
1486 let out_type = info.get_data_type(&when_then_expr[0].1)?;
1487 let mut new_when_then_expr = Vec::with_capacity(when_then_expr.len());
1488
1489 for (when, then) in when_then_expr.into_iter() {
1490 if is_true(when.as_ref()) {
1491 else_expr = Some(then);
1494 break;
1495 } else if !is_false(when.as_ref()) {
1496 new_when_then_expr.push((when, then));
1497 }
1498 }
1500
1501 if new_when_then_expr.is_empty() {
1503 if let Some(else_expr) = else_expr {
1505 return Ok(Transformed::yes(*else_expr));
1506 } else {
1508 let null =
1509 Expr::Literal(ScalarValue::try_new_null(&out_type)?, None);
1510 return Ok(Transformed::yes(null));
1511 }
1512 }
1513
1514 Transformed::yes(Expr::Case(Case {
1515 expr: None,
1516 when_then_expr: new_when_then_expr,
1517 else_expr,
1518 }))
1519 }
1520
1521 Expr::Case(Case {
1535 expr: None,
1536 when_then_expr,
1537 else_expr,
1538 }) if !when_then_expr.is_empty()
1539 && (when_then_expr.len() < 3 || (when_then_expr.iter().all(|(_, then)| is_bool_lit(then))
1543 && when_then_expr.iter().filter(|(_, then)| is_true(then)).count() < 3))
1544 && info.is_boolean_type(&when_then_expr[0].1)?
1545 && can_lower_case_to_boolean(&when_then_expr, else_expr.as_deref()) =>
1546 {
1547 let mut filter_expr = lit(false);
1549 let mut out_expr = lit(false);
1551
1552 for (when, then) in when_then_expr {
1553 let when = is_exactly_true(*when, info)?;
1554 let case_expr =
1555 when.clone().and(filter_expr.clone().not()).and(*then);
1556
1557 out_expr = out_expr.or(case_expr);
1558 filter_expr = filter_expr.or(when);
1559 }
1560
1561 let else_expr = else_expr.map(|b| *b).unwrap_or_else(lit_bool_null);
1562 let case_expr = filter_expr.not().and(else_expr);
1563 out_expr = out_expr.or(case_expr);
1564
1565 out_expr.rewrite(self)?
1567 }
1568 Expr::Case(Case {
1589 expr: None,
1590 when_then_expr,
1591 else_expr,
1592 }) if !when_then_expr.is_empty()
1593 && when_then_expr
1594 .iter()
1595 .all(|(_, then)| is_bool_lit(then)) && when_then_expr
1598 .iter()
1599 .filter(|(_, then)| is_false(then))
1600 .count()
1601 < 3
1602 && else_expr.as_deref().is_none_or(is_bool_lit)
1603 && can_lower_case_to_boolean(&when_then_expr, else_expr.as_deref()) =>
1604 {
1605 Transformed::yes(
1606 Expr::Case(Case {
1607 expr: None,
1608 when_then_expr: when_then_expr
1609 .into_iter()
1610 .map(|(when, then)| (when, Box::new(Expr::Not(then))))
1611 .collect(),
1612 else_expr: else_expr
1613 .map(|else_expr| Box::new(Expr::Not(else_expr))),
1614 })
1615 .not(),
1616 )
1617 }
1618 Expr::ScalarFunction(ScalarFunction { func: udf, args }) => {
1619 match udf.simplify(args, info)? {
1620 ExprSimplifyResult::Original(args) => {
1621 Transformed::no(Expr::ScalarFunction(ScalarFunction {
1622 func: udf,
1623 args,
1624 }))
1625 }
1626 ExprSimplifyResult::Simplified(expr) => Transformed::yes(expr),
1627 }
1628 }
1629
1630 Expr::AggregateFunction(datafusion_expr::expr::AggregateFunction {
1631 ref func,
1632 ..
1633 }) => match (func.simplify(), expr) {
1634 (Some(simplify_function), Expr::AggregateFunction(af)) => {
1635 Transformed::yes(simplify_function(af, info)?)
1636 }
1637 (_, expr) => Transformed::no(expr),
1638 },
1639
1640 Expr::WindowFunction(ref window_fun) => match (window_fun.simplify(), expr) {
1641 (Some(simplify_function), Expr::WindowFunction(wf)) => {
1642 Transformed::yes(simplify_function(*wf, info)?)
1643 }
1644 (_, expr) => Transformed::no(expr),
1645 },
1646
1647 Expr::Between(between) => Transformed::yes(if between.negated {
1654 let l = *between.expr.clone();
1655 let r = *between.expr;
1656 or(l.lt(*between.low), r.gt(*between.high))
1657 } else {
1658 and(
1659 between.expr.clone().gt_eq(*between.low),
1660 between.expr.lt_eq(*between.high),
1661 )
1662 }),
1663
1664 Expr::BinaryExpr(BinaryExpr {
1668 left,
1669 op: op @ (RegexMatch | RegexNotMatch | RegexIMatch | RegexNotIMatch),
1670 right,
1671 }) => {
1672 if !matches!(left.as_ref(), Expr::Literal(_, _))
1675 || regex_is_within_planning_budget(&op, &right)
1676 {
1677 simplify_regex_expr(left, op, right)?
1678 } else {
1679 Transformed::no(Expr::BinaryExpr(BinaryExpr { left, op, right }))
1680 }
1681 }
1682
1683 Expr::Like(like) => {
1685 let escape_char = like.escape_char.unwrap_or('\\');
1687
1688 match StringScalar::try_from_expr(&like.pattern) {
1689 Some(string_scalar) => {
1690 let pattern_str = string_scalar.as_str();
1691 match pattern_str {
1692 None => return Ok(Transformed::yes(lit_bool_null())),
1693 Some("%") => {
1694 let result_for_non_null = lit(!like.negated);
1701 Transformed::yes(if !info.nullable(&like.expr)? {
1702 result_for_non_null
1703 } else {
1704 Expr::Case(Case {
1705 expr: Some(Box::new(Expr::IsNotNull(like.expr))),
1706 when_then_expr: vec![(
1707 Box::new(lit(true)),
1708 Box::new(result_for_non_null),
1709 )],
1710 else_expr: None,
1711 })
1712 })
1713 }
1714 Some(pattern_str)
1715 if pattern_str.contains("%%")
1716 && !pattern_str.contains(escape_char) =>
1717 {
1718 static LIKE_REGEX: LazyLock<Regex> =
1722 LazyLock::new(|| Regex::new("%%+").unwrap());
1723 let simplified_pattern =
1724 LIKE_REGEX.replace_all(pattern_str, "%").to_string();
1725 Transformed::yes(Expr::Like(Like {
1726 pattern: Box::new(
1727 string_scalar.to_expr(&simplified_pattern),
1728 ),
1729 ..like
1730 }))
1731 }
1732 Some(pattern_str)
1733 if !like.case_insensitive
1734 && !pattern_str
1735 .contains(['%', '_', escape_char].as_ref()) =>
1736 {
1737 Transformed::yes(Expr::BinaryExpr(BinaryExpr {
1740 left: like.expr.clone(),
1741 op: if like.negated { NotEq } else { Eq },
1742 right: like.pattern.clone(),
1743 }))
1744 }
1745
1746 Some(_pattern_str) => Transformed::no(Expr::Like(like)),
1747 }
1748 }
1749 None => Transformed::no(Expr::Like(like)),
1750 }
1751 }
1752
1753 Expr::IsNotNull(expr) | Expr::IsNotUnknown(expr)
1755 if !info.nullable(&expr)? =>
1756 {
1757 Transformed::yes(lit(true))
1758 }
1759
1760 Expr::IsNull(expr) | Expr::IsUnknown(expr) if !info.nullable(&expr)? => {
1762 Transformed::yes(lit(false))
1763 }
1764
1765 Expr::InList(InList {
1768 expr: _,
1769 list,
1770 negated,
1771 }) if list.is_empty() => Transformed::yes(lit(negated)),
1772
1773 Expr::InList(InList {
1776 expr,
1777 list,
1778 negated: _,
1779 }) if is_null(expr.as_ref()) && !list.is_empty() => {
1780 Transformed::yes(lit_bool_null())
1781 }
1782
1783 Expr::InList(InList {
1785 expr,
1786 mut list,
1787 negated,
1788 }) if list.len() == 1
1789 && matches!(list.first(), Some(Expr::ScalarSubquery { .. })) =>
1790 {
1791 let Expr::ScalarSubquery(subquery) = list.remove(0) else {
1792 unreachable!()
1793 };
1794
1795 Transformed::yes(Expr::InSubquery(InSubquery::new(
1796 expr, subquery, negated,
1797 )))
1798 }
1799
1800 Expr::BinaryExpr(BinaryExpr {
1804 left,
1805 op: Or,
1806 right,
1807 }) if are_inlist_and_eq(left.as_ref(), right.as_ref()) => {
1808 let lhs = to_inlist(*left).unwrap();
1809 let rhs = to_inlist(*right).unwrap();
1810 #[allow(clippy::allow_attributes, clippy::mutable_key_type)]
1811 let mut seen: HashSet<Expr> =
1813 HashSet::with_capacity(lhs.list.len() + rhs.list.len());
1814 let list = lhs
1815 .list
1816 .into_iter()
1817 .chain(rhs.list)
1818 .filter(|e| seen.insert(e.to_owned()))
1819 .collect::<Vec<_>>();
1820
1821 let merged_inlist = InList {
1822 expr: lhs.expr,
1823 list,
1824 negated: false,
1825 };
1826
1827 Transformed::yes(Expr::InList(merged_inlist))
1828 }
1829
1830 Expr::BinaryExpr(BinaryExpr {
1847 left,
1848 op: And,
1849 right,
1850 }) if are_inlist_and_eq_and_match_neg(
1851 left.as_ref(),
1852 right.as_ref(),
1853 false,
1854 false,
1855 ) && inlists_have_set_comparable_literals(
1856 left.as_ref(),
1857 right.as_ref(),
1858 ) =>
1859 {
1860 match (*left, *right) {
1861 (Expr::InList(l1), Expr::InList(l2)) => {
1862 let simplified = inlist_intersection(l1.clone(), &l2, false)?;
1863 if let Some(simplified) =
1864 simplify_inlist_set_operation(info, &l1, &l2, simplified)?
1865 {
1866 Transformed::yes(simplified)
1867 } else {
1868 Transformed::no(Expr::InList(l1).and(Expr::InList(l2)))
1869 }
1870 }
1871 _ => unreachable!(),
1873 }
1874 }
1875
1876 Expr::BinaryExpr(BinaryExpr {
1877 left,
1878 op: And,
1879 right,
1880 }) if are_inlist_and_eq_and_match_neg(
1881 left.as_ref(),
1882 right.as_ref(),
1883 true,
1884 true,
1885 ) =>
1886 {
1887 match (*left, *right) {
1888 (Expr::InList(l1), Expr::InList(l2)) => {
1889 return inlist_union(l1, l2, true).map(Transformed::yes);
1890 }
1891 _ => unreachable!(),
1893 }
1894 }
1895
1896 Expr::BinaryExpr(BinaryExpr {
1897 left,
1898 op: And,
1899 right,
1900 }) if are_inlist_and_eq_and_match_neg(
1901 left.as_ref(),
1902 right.as_ref(),
1903 false,
1904 true,
1905 ) && inlists_have_set_comparable_literals(
1906 left.as_ref(),
1907 right.as_ref(),
1908 ) =>
1909 {
1910 match (*left, *right) {
1911 (Expr::InList(l1), Expr::InList(l2)) => {
1912 let simplified = inlist_except(l1.clone(), &l2)?;
1913 if let Some(simplified) =
1914 simplify_inlist_set_operation(info, &l1, &l2, simplified)?
1915 {
1916 Transformed::yes(simplified)
1917 } else {
1918 Transformed::no(Expr::InList(l1).and(Expr::InList(l2)))
1919 }
1920 }
1921 _ => unreachable!(),
1923 }
1924 }
1925
1926 Expr::BinaryExpr(BinaryExpr {
1927 left,
1928 op: And,
1929 right,
1930 }) if are_inlist_and_eq_and_match_neg(
1931 left.as_ref(),
1932 right.as_ref(),
1933 true,
1934 false,
1935 ) && inlists_have_set_comparable_literals(
1936 left.as_ref(),
1937 right.as_ref(),
1938 ) =>
1939 {
1940 match (*left, *right) {
1941 (Expr::InList(l1), Expr::InList(l2)) => {
1942 let simplified = inlist_except(l2.clone(), &l1)?;
1943 if let Some(simplified) =
1944 simplify_inlist_set_operation(info, &l1, &l2, simplified)?
1945 {
1946 Transformed::yes(simplified)
1947 } else {
1948 Transformed::no(Expr::InList(l1).and(Expr::InList(l2)))
1949 }
1950 }
1951 _ => unreachable!(),
1953 }
1954 }
1955
1956 Expr::BinaryExpr(BinaryExpr {
1957 left,
1958 op: Or,
1959 right,
1960 }) if are_inlist_and_eq_and_match_neg(
1961 left.as_ref(),
1962 right.as_ref(),
1963 true,
1964 true,
1965 ) && inlists_have_set_comparable_literals(
1966 left.as_ref(),
1967 right.as_ref(),
1968 ) =>
1969 {
1970 match (*left, *right) {
1971 (Expr::InList(l1), Expr::InList(l2)) => {
1972 let simplified = inlist_intersection(l1.clone(), &l2, true)?;
1973 if let Some(simplified) =
1974 simplify_inlist_set_operation(info, &l1, &l2, simplified)?
1975 {
1976 Transformed::yes(simplified)
1977 } else {
1978 Transformed::no(Expr::InList(l1).or(Expr::InList(l2)))
1979 }
1980 }
1981 _ => unreachable!(),
1983 }
1984 }
1985
1986 Expr::BinaryExpr(BinaryExpr { left, op, right })
1993 if supports_cast_predicate_for_binary(info, &left, op, &right)
1994 && op.supports_propagation() =>
1995 {
1996 rewrite_cast_predicate_for_binary(info, *left, *right, op)?
1997 }
1998 Expr::BinaryExpr(BinaryExpr { left, op, right })
2002 if op.supports_propagation()
2003 && op.swap().is_some_and(|swapped| {
2004 supports_cast_predicate_for_binary(info, &right, swapped, &left)
2005 }) =>
2006 {
2007 rewrite_cast_predicate_for_binary(
2008 info,
2009 *right,
2010 *left,
2011 op.swap().unwrap(),
2012 )?
2013 }
2014 Expr::InList(InList {
2017 expr,
2018 list,
2019 negated,
2020 }) if supports_cast_predicate_for_inlist(info, &expr, &list) => {
2021 rewrite_cast_predicate_for_inlist(info, *expr, list, negated)?
2022 }
2023
2024 Expr::BinaryExpr(BinaryExpr { left, op, right }) => {
2033 use datafusion_expr::Operator::*;
2034 let is_preimage_op = matches!(
2035 op,
2036 Eq | NotEq
2037 | Lt
2038 | LtEq
2039 | Gt
2040 | GtEq
2041 | IsDistinctFrom
2042 | IsNotDistinctFrom
2043 );
2044 if !is_preimage_op || is_null(&right) {
2045 return Ok(Transformed::no(Expr::BinaryExpr(BinaryExpr {
2046 left,
2047 op,
2048 right,
2049 })));
2050 }
2051
2052 if let PreimageResult::Range { interval, expr } =
2053 get_preimage(left.as_ref(), right.as_ref(), info)?
2054 {
2055 rewrite_with_preimage(*interval, op, expr)?
2056 } else if let Some(swapped) = op.swap() {
2057 if let PreimageResult::Range { interval, expr } =
2058 get_preimage(right.as_ref(), left.as_ref(), info)?
2059 {
2060 rewrite_with_preimage(*interval, swapped, expr)?
2061 } else {
2062 Transformed::no(Expr::BinaryExpr(BinaryExpr { left, op, right }))
2063 }
2064 } else {
2065 Transformed::no(Expr::BinaryExpr(BinaryExpr { left, op, right }))
2066 }
2067 }
2068 Expr::InList(InList {
2071 expr,
2072 list,
2073 negated,
2074 }) => {
2075 if list.len() > THRESHOLD_INLINE_INLIST || list.iter().any(is_null) {
2076 return Ok(Transformed::no(Expr::InList(InList {
2077 expr,
2078 list,
2079 negated,
2080 })));
2081 }
2082
2083 let (op, combiner): (Operator, fn(Expr, Expr) -> Expr) =
2084 if negated { (NotEq, and) } else { (Eq, or) };
2085
2086 let mut rewritten: Option<Expr> = None;
2087 for item in &list {
2088 let PreimageResult::Range { interval, expr } =
2089 get_preimage(expr.as_ref(), item, info)?
2090 else {
2091 return Ok(Transformed::no(Expr::InList(InList {
2092 expr,
2093 list,
2094 negated,
2095 })));
2096 };
2097
2098 let range_expr = rewrite_with_preimage(*interval, op, expr)?.data;
2099 rewritten = Some(match rewritten {
2100 None => range_expr,
2101 Some(acc) => combiner(acc, range_expr),
2102 });
2103 }
2104
2105 if let Some(rewritten) = rewritten {
2106 Transformed::yes(rewritten)
2107 } else {
2108 Transformed::no(Expr::InList(InList {
2109 expr,
2110 list,
2111 negated,
2112 }))
2113 }
2114 }
2115
2116 expr => Transformed::no(expr),
2118 })
2119 }
2120}
2121
2122fn get_preimage(
2123 left_expr: &Expr,
2124 right_expr: &Expr,
2125 info: &SimplifyContext,
2126) -> Result<PreimageResult> {
2127 let Expr::ScalarFunction(ScalarFunction { func, args }) = left_expr else {
2128 return Ok(PreimageResult::None);
2129 };
2130 if !is_literal_or_literal_cast(right_expr) {
2131 return Ok(PreimageResult::None);
2132 }
2133 if func.signature().volatility != Volatility::Immutable {
2134 return Ok(PreimageResult::None);
2135 }
2136 if args.iter().any(Expr::is_volatile) {
2138 return Ok(PreimageResult::None);
2139 }
2140
2141 func.preimage(args, right_expr, info)
2142}
2143
2144fn is_literal_or_literal_cast(expr: &Expr) -> bool {
2145 match expr {
2146 Expr::Literal(_, _) => true,
2147 Expr::Cast(Cast { expr, .. }) => matches!(expr.as_ref(), Expr::Literal(_, _)),
2148 Expr::TryCast(TryCast { expr, .. }) => {
2149 matches!(expr.as_ref(), Expr::Literal(_, _))
2150 }
2151 _ => false,
2152 }
2153}
2154
2155pub(crate) enum StringScalar<'a> {
2157 Utf8(&'a ScalarValue),
2158 LargeUtf8(&'a ScalarValue),
2159 Utf8View(&'a ScalarValue),
2160}
2161
2162impl<'a> StringScalar<'a> {
2163 pub(crate) fn try_from_expr(expr: &'a Expr) -> Option<Self> {
2166 match expr {
2167 Expr::Literal(scalar, _) => Self::try_from_scalar(scalar),
2168 _ => None,
2169 }
2170 }
2171
2172 fn try_from_scalar(scalar: &'a ScalarValue) -> Option<Self> {
2175 match scalar {
2176 ScalarValue::Utf8(_) => Some(Self::Utf8(scalar)),
2177 ScalarValue::LargeUtf8(_) => Some(Self::LargeUtf8(scalar)),
2178 ScalarValue::Utf8View(_) => Some(Self::Utf8View(scalar)),
2179 _ => None,
2180 }
2181 }
2182
2183 pub(crate) fn as_str(&self) -> Option<&'a str> {
2185 match self {
2186 Self::Utf8(scalar) | Self::LargeUtf8(scalar) | Self::Utf8View(scalar) => {
2187 scalar.try_as_str().flatten()
2188 }
2189 }
2190 }
2191
2192 pub(crate) fn to_expr(&self, val: &str) -> Expr {
2194 match self {
2195 Self::Utf8(_) => Expr::Literal(ScalarValue::Utf8(Some(val.to_owned())), None),
2196 Self::LargeUtf8(_) => {
2197 Expr::Literal(ScalarValue::LargeUtf8(Some(val.to_owned())), None)
2198 }
2199 Self::Utf8View(_) => {
2200 Expr::Literal(ScalarValue::Utf8View(Some(val.to_owned())), None)
2201 }
2202 }
2203 }
2204}
2205
2206#[allow(clippy::allow_attributes, clippy::mutable_key_type)] fn has_common_conjunction(lhs: &Expr, rhs: &Expr) -> bool {
2208 let lhs_set: HashSet<&Expr> = iter_conjunction(lhs).collect();
2209 iter_conjunction(rhs).any(|e| lhs_set.contains(&e) && !e.is_volatile())
2210}
2211
2212fn are_inlist_and_eq_and_match_neg(
2214 left: &Expr,
2215 right: &Expr,
2216 is_left_neg: bool,
2217 is_right_neg: bool,
2218) -> bool {
2219 match (left, right) {
2220 (Expr::InList(l), Expr::InList(r)) => {
2221 l.expr == r.expr
2222 && !l.expr.is_volatile()
2223 && !l.list.iter().chain(&r.list).any(Expr::is_volatile)
2224 && l.negated == is_left_neg
2225 && r.negated == is_right_neg
2226 }
2227 _ => false,
2228 }
2229}
2230
2231fn inlists_have_set_comparable_literals(left: &Expr, right: &Expr) -> bool {
2236 match (left, right) {
2237 (Expr::InList(l), Expr::InList(r)) => l.list.iter().chain(&r.list).all(|item| {
2238 item.as_literal().is_some_and(|value| {
2239 !value.is_null() && !has_float_leaf(&value.data_type())
2240 })
2241 }),
2242 _ => false,
2243 }
2244}
2245
2246fn are_inlist_and_eq(left: &Expr, right: &Expr) -> bool {
2248 let left = as_inlist(left);
2249 let right = as_inlist(right);
2250 if let (Some(lhs), Some(rhs)) = (left, right) {
2251 matches!(lhs.expr.as_ref(), Expr::Column(_))
2252 && matches!(rhs.expr.as_ref(), Expr::Column(_))
2253 && lhs.expr == rhs.expr
2254 && !lhs.list.iter().chain(&rhs.list).any(Expr::is_volatile)
2255 && !lhs.negated
2256 && !rhs.negated
2257 } else {
2258 false
2259 }
2260}
2261
2262fn as_inlist(expr: &'_ Expr) -> Option<Cow<'_, InList>> {
2264 match expr {
2265 Expr::InList(inlist) => Some(Cow::Borrowed(inlist)),
2266 Expr::BinaryExpr(BinaryExpr { left, op, right }) if *op == Operator::Eq => {
2267 match (left.as_ref(), right.as_ref()) {
2268 (Expr::Column(_), Expr::Literal(_, _)) => Some(Cow::Owned(InList {
2269 expr: left.clone(),
2270 list: vec![*right.clone()],
2271 negated: false,
2272 })),
2273 (Expr::Literal(_, _), Expr::Column(_)) => Some(Cow::Owned(InList {
2274 expr: right.clone(),
2275 list: vec![*left.clone()],
2276 negated: false,
2277 })),
2278 _ => None,
2279 }
2280 }
2281 _ => None,
2282 }
2283}
2284
2285fn to_inlist(expr: Expr) -> Option<InList> {
2286 match expr {
2287 Expr::InList(inlist) => Some(inlist),
2288 Expr::BinaryExpr(BinaryExpr {
2289 left,
2290 op: Operator::Eq,
2291 right,
2292 }) => match (left.as_ref(), right.as_ref()) {
2293 (Expr::Column(_), Expr::Literal(_, _)) => Some(InList {
2294 expr: left,
2295 list: vec![*right],
2296 negated: false,
2297 }),
2298 (Expr::Literal(_, _), Expr::Column(_)) => Some(InList {
2299 expr: right,
2300 list: vec![*left],
2301 negated: false,
2302 }),
2303 _ => None,
2304 },
2305 _ => None,
2306 }
2307}
2308
2309#[allow(clippy::allow_attributes, clippy::mutable_key_type)] fn inlist_union(mut l1: InList, l2: InList, negated: bool) -> Result<Expr> {
2313 let l1_items: HashSet<_> = l1.list.iter().collect();
2315
2316 let keep_l2: Vec<_> = l2
2318 .list
2319 .into_iter()
2320 .filter_map(|e| if l1_items.contains(&e) { None } else { Some(e) })
2321 .collect();
2322
2323 l1.list.extend(keep_l2);
2324 l1.negated = negated;
2325 Ok(Expr::InList(l1))
2326}
2327
2328#[allow(clippy::allow_attributes, clippy::mutable_key_type)] fn inlist_intersection(mut l1: InList, l2: &InList, negated: bool) -> Result<Expr> {
2332 let l2_items = l2.list.iter().collect::<HashSet<_>>();
2333
2334 l1.list.retain(|e| l2_items.contains(e));
2336
2337 if l1.list.is_empty() {
2340 return Ok(lit(negated));
2341 }
2342 Ok(Expr::InList(l1))
2343}
2344
2345#[allow(clippy::allow_attributes, clippy::mutable_key_type)] fn inlist_except(mut l1: InList, l2: &InList) -> Result<Expr> {
2349 let l2_items = l2.list.iter().collect::<HashSet<_>>();
2350
2351 l1.list.retain(|e| !l2_items.contains(e));
2353
2354 if l1.list.is_empty() {
2355 return Ok(lit(false));
2356 }
2357 Ok(Expr::InList(l1))
2358}
2359
2360fn simplify_inlist_set_operation(
2364 info: &SimplifyContext,
2365 left: &InList,
2366 right: &InList,
2367 result: Expr,
2368) -> Result<Option<Expr>> {
2369 for item in left.list.iter().chain(&right.list) {
2370 if info.nullable(item)? {
2371 return Ok(None);
2372 }
2373 }
2374
2375 if !is_true(&result) && !is_false(&result) {
2376 return Ok(Some(result));
2377 }
2378
2379 Ok(Some(if !info.nullable(left.expr.as_ref())? {
2380 result
2381 } else if is_true(&result) {
2382 Expr::IsNotNull(left.expr.clone()).or(lit_bool_null())
2383 } else {
2384 Expr::IsNull(left.expr.clone()).and(lit_bool_null())
2385 }))
2386}
2387
2388fn can_lower_case_to_boolean(
2392 when_then_expr: &[(Box<Expr>, Box<Expr>)],
2393 else_expr: Option<&Expr>,
2394) -> bool {
2395 let is_leaf = |expr: &Expr| matches!(expr, Expr::Column(_) | Expr::Literal(..));
2396 when_then_expr
2397 .iter()
2398 .all(|(when, then)| is_leaf(when) && is_leaf(then))
2399 && else_expr.is_none_or(is_leaf)
2400}
2401
2402fn is_exactly_true(expr: Expr, info: &SimplifyContext) -> Result<Expr> {
2404 if !info.nullable(&expr)? {
2405 Ok(expr)
2406 } else {
2407 Ok(Expr::BinaryExpr(BinaryExpr {
2408 left: Box::new(expr),
2409 op: Operator::IsNotDistinctFrom,
2410 right: Box::new(lit(true)),
2411 }))
2412 }
2413}
2414
2415fn simplify_right_is_one_case(
2420 info: &SimplifyContext,
2421 left: Box<Expr>,
2422 op: &Operator,
2423 right: &Expr,
2424) -> Result<Transformed<Expr>> {
2425 let left_type = info.get_data_type(&left)?;
2427 let right_type = info.get_data_type(right)?;
2428 match BinaryTypeCoercer::new(&left_type, op, &right_type).get_result_type() {
2429 Ok(result_type) => {
2430 if left_type != result_type {
2432 Ok(Transformed::yes(Expr::Cast(Cast::new(left, result_type))))
2433 } else {
2434 Ok(Transformed::yes(*left))
2435 }
2436 }
2437 Err(_) => Ok(Transformed::yes(*left)),
2438 }
2439}
2440
2441#[cfg(test)]
2442mod tests {
2443 use super::*;
2444 use crate::test::test_table_scan_with_name;
2445 use arrow::{
2446 array::{BooleanArray, Float64Array, Int32Array, StructArray},
2447 datatypes::{FieldRef, Fields},
2448 };
2449 use datafusion_common::{DFSchemaRef, ToDFSchema, assert_contains};
2450 use datafusion_expr::{
2451 expr::WindowFunction,
2452 function::{
2453 AccumulatorArgs, AggregateFunctionSimplification,
2454 WindowFunctionSimplification,
2455 },
2456 interval_arithmetic::Interval,
2457 *,
2458 };
2459 use datafusion_functions_window_common::field::WindowUDFFieldArgs;
2460 use datafusion_functions_window_common::partition::PartitionEvaluatorArgs;
2461 use datafusion_physical_expr::PhysicalExpr;
2462 use std::hash::Hash;
2463 use std::sync::LazyLock;
2464 use std::{
2465 collections::HashMap,
2466 ops::{BitAnd, BitOr, BitXor},
2467 sync::Arc,
2468 };
2469
2470 #[test]
2474 fn api_basic() {
2475 let simplifier = ExprSimplifier::new(
2476 SimplifyContext::builder()
2477 .with_schema(test_schema())
2478 .build(),
2479 );
2480
2481 let expr = lit(1) + lit(2);
2482 let expected = lit(3);
2483 assert_eq!(expected, simplifier.simplify(expr).unwrap());
2484 }
2485
2486 #[test]
2487 fn basic_coercion() {
2488 let schema = test_schema();
2489 let simplifier = ExprSimplifier::new(
2490 SimplifyContext::builder()
2491 .with_schema(Arc::clone(&schema))
2492 .build(),
2493 );
2494
2495 let expr = (lit(1i64) + lit(2i32)).lt(col("i"));
2498 let expected = lit(3i64).lt(col("i"));
2500
2501 let expr = simplifier.coerce(expr, &schema).unwrap();
2502
2503 assert_eq!(expected, simplifier.simplify(expr).unwrap());
2504 }
2505
2506 fn test_schema() -> DFSchemaRef {
2507 static TEST_SCHEMA: LazyLock<DFSchemaRef> = LazyLock::new(|| {
2508 Schema::new(vec![
2509 Field::new("i", DataType::Int64, false),
2510 Field::new("b", DataType::Boolean, true),
2511 ])
2512 .to_dfschema_ref()
2513 .unwrap()
2514 });
2515 Arc::clone(&TEST_SCHEMA)
2516 }
2517
2518 #[test]
2519 fn simplify_and_constant_prop() {
2520 let simplifier = ExprSimplifier::new(
2521 SimplifyContext::builder()
2522 .with_schema(test_schema())
2523 .build(),
2524 );
2525
2526 let expr = (col("i") * (lit(1) - lit(1))).gt(lit(0));
2529 let expected = lit(false);
2530 assert_eq!(expected, simplifier.simplify(expr).unwrap());
2531 }
2532
2533 #[test]
2534 fn simplify_and_constant_prop_with_case() {
2535 let simplifier = ExprSimplifier::new(
2536 SimplifyContext::builder()
2537 .with_schema(test_schema())
2538 .build(),
2539 );
2540
2541 let expr = when(col("i").gt(lit(5)).and(lit(false)), col("i").gt(lit(5)))
2550 .when(col("i").lt(lit(5)).and(lit(true)), col("i").lt(lit(5)))
2551 .otherwise(lit(false))
2552 .unwrap();
2553 let expected = when(col("i").lt(lit(5)), col("i").lt(lit(5)))
2554 .otherwise(lit(false))
2555 .unwrap();
2556 assert_eq!(expected, simplifier.simplify(expr).unwrap());
2557 }
2558
2559 #[test]
2564 fn test_simplify_canonicalize() {
2565 {
2566 let expr = lit(1).lt(col("c2")).and(col("c2").gt(lit(1)));
2567 let expected = col("c2").gt(lit(1));
2568 assert_eq!(simplify(expr), expected);
2569 }
2570 {
2571 let expr = col("c1").lt(col("c2")).and(col("c2").gt(col("c1")));
2572 let expected = col("c2").gt(col("c1"));
2573 assert_eq!(simplify(expr), expected);
2574 }
2575 {
2576 let expr = col("c1")
2577 .eq(lit(1))
2578 .and(lit(1).eq(col("c1")))
2579 .and(col("c1").eq(lit(3)));
2580 let expected = col("c1").eq(lit(1)).and(col("c1").eq(lit(3)));
2581 assert_eq!(simplify(expr), expected);
2582 }
2583 {
2584 let expr = col("c1")
2585 .eq(col("c2"))
2586 .and(col("c1").gt(lit(5)))
2587 .and(col("c2").eq(col("c1")));
2588 let expected = col("c2").eq(col("c1")).and(col("c1").gt(lit(5)));
2589 assert_eq!(simplify(expr), expected);
2590 }
2591 {
2592 let expr = col("c1")
2593 .eq(lit(1))
2594 .and(col("c2").gt(lit(3)).or(lit(3).lt(col("c2"))));
2595 let expected = col("c1").eq(lit(1)).and(col("c2").gt(lit(3)));
2596 assert_eq!(simplify(expr), expected);
2597 }
2598 {
2599 let expr = col("c1").lt(lit(5)).and(col("c1").gt_eq(lit(5)));
2600 let expected = col("c1").lt(lit(5)).and(col("c1").gt_eq(lit(5)));
2601 assert_eq!(simplify(expr), expected);
2602 }
2603 {
2604 let expr = col("c1").lt(lit(5)).and(col("c1").gt_eq(lit(5)));
2605 let expected = col("c1").lt(lit(5)).and(col("c1").gt_eq(lit(5)));
2606 assert_eq!(simplify(expr), expected);
2607 }
2608 {
2609 let expr = col("c1").gt(col("c2")).and(col("c1").gt(col("c2")));
2610 let expected = col("c2").lt(col("c1"));
2611 assert_eq!(simplify(expr), expected);
2612 }
2613 }
2614
2615 #[test]
2616 fn test_simplify_swapped_operands_in_and_or_no_canonicalize() {
2617 let expr = col("c3_non_null")
2627 .eq(lit(5_i64))
2628 .and(lit(5_i64).eq(col("c3_non_null")));
2629 let expected = col("c3_non_null").eq(lit(5_i64));
2630 assert_eq!(simplify_no_canonicalize(expr), expected);
2631
2632 let expr = lit(5_i64)
2634 .eq(col("c3_non_null"))
2635 .and(col("c3_non_null").eq(lit(5_i64)));
2636 let expected = lit(5_i64).eq(col("c3_non_null"));
2637 assert_eq!(simplify_no_canonicalize(expr), expected);
2638
2639 let expr = col("c3_non_null")
2641 .eq(lit(5_i64))
2642 .or(lit(5_i64).eq(col("c3_non_null")));
2643 let expected = col("c3_non_null").eq(lit(5_i64));
2644 assert_eq!(simplify_no_canonicalize(expr), expected);
2645
2646 let expr = col("c3_non_null")
2648 .eq(lit(5_i64))
2649 .and(col("c4_non_null").gt(lit(0_u32)))
2650 .and(lit(5_i64).eq(col("c3_non_null")));
2651 let expected = col("c3_non_null")
2652 .eq(lit(5_i64))
2653 .and(col("c4_non_null").gt(lit(0_u32)));
2654 assert_eq!(simplify_no_canonicalize(expr), expected);
2655 }
2656
2657 #[test]
2658 fn test_simplify_swapped_operands_in_xor_no_canonicalize() {
2659 let expr = bitwise_xor(
2669 col("c4_non_null") + lit(1_u32),
2670 lit(1_u32) + col("c4_non_null"),
2671 );
2672 let (simplified, cycles) = simplify_no_canonicalize_with_cycle_count(expr);
2673 assert_eq!(simplified, lit(0_u32));
2674 assert_eq!(cycles, 2);
2675
2676 let expr = bitwise_xor(
2678 col("c4_non_null") + lit(1_u32),
2679 bitwise_xor(lit(1_u32) + col("c4_non_null"), col("c4_non_null")),
2680 );
2681 let (simplified, cycles) = simplify_no_canonicalize_with_cycle_count(expr);
2682 assert_eq!(simplified, col("c4_non_null"));
2683 assert_eq!(cycles, 2);
2684 }
2685
2686 #[test]
2687 fn test_simplify_eq_not_self() {
2688 let expr_a = col("c2").eq(col("c2"));
2691 let expected_a = col("c2").is_not_null().or(lit_bool_null());
2692
2693 let expr_b = col("c2_non_null").eq(col("c2_non_null"));
2695 let expected_b = lit(true);
2696
2697 assert_eq!(simplify(expr_a), expected_a);
2698 assert_eq!(simplify(expr_b), expected_b);
2699 }
2700
2701 fn in_subquery_expr(a_nullable: bool) -> Expr {
2703 let schema = Schema::new(vec![Field::new("a", DataType::Int64, a_nullable)]);
2704 let source = Arc::new(LogicalTableSource::new(Arc::new(schema)));
2705 let subquery = LogicalPlanBuilder::scan("t", source, None)
2706 .unwrap()
2707 .project(vec![col("a")])
2708 .unwrap()
2709 .build()
2710 .unwrap();
2711
2712 in_subquery(col("c3_non_null"), Arc::new(subquery))
2713 }
2714
2715 #[test]
2716 fn test_simplify_eq_not_self_in_subquery() {
2717 let expr_a = in_subquery_expr(true);
2721 let expected_a = expr_a.clone().is_not_null().or(lit_bool_null());
2722
2723 let expr_b = in_subquery_expr(false);
2725 let expected_b = lit(true);
2726
2727 assert_eq!(simplify(expr_a.clone().eq(expr_a)), expected_a);
2728 assert_eq!(simplify(expr_b.clone().eq(expr_b)), expected_b);
2729 }
2730
2731 #[test]
2732 fn test_simplify_or_true() {
2733 let expr_a = col("c2").or(lit(true));
2734 let expr_b = lit(true).or(col("c2"));
2735 let expected = lit(true);
2736
2737 assert_eq!(simplify(expr_a), expected);
2738 assert_eq!(simplify(expr_b), expected);
2739 }
2740
2741 #[test]
2742 fn test_simplify_or_false() {
2743 let expr_a = lit(false).or(col("c2"));
2744 let expr_b = col("c2").or(lit(false));
2745 let expected = col("c2");
2746
2747 assert_eq!(simplify(expr_a), expected);
2748 assert_eq!(simplify(expr_b), expected);
2749 }
2750
2751 #[test]
2752 fn test_simplify_or_same() {
2753 let expr = col("c2").or(col("c2"));
2754 let expected = col("c2");
2755
2756 assert_eq!(simplify(expr), expected);
2757 }
2758
2759 #[test]
2760 fn test_simplify_or_not_self() {
2761 let expr_a = col("c2_non_null").or(col("c2_non_null").not());
2764 let expr_b = col("c2_non_null").not().or(col("c2_non_null"));
2765 let expected = lit(true);
2766
2767 assert_eq!(simplify(expr_a), expected);
2768 assert_eq!(simplify(expr_b), expected);
2769 }
2770
2771 #[test]
2772 fn test_simplify_and_false() {
2773 let expr_a = lit(false).and(col("c2"));
2774 let expr_b = col("c2").and(lit(false));
2775 let expected = lit(false);
2776
2777 assert_eq!(simplify(expr_a), expected);
2778 assert_eq!(simplify(expr_b), expected);
2779 }
2780
2781 #[test]
2782 fn test_simplify_and_same() {
2783 let expr = col("c2").and(col("c2"));
2784 let expected = col("c2");
2785
2786 assert_eq!(simplify(expr), expected);
2787 }
2788
2789 #[test]
2790 fn test_simplify_and_true() {
2791 let expr_a = lit(true).and(col("c2"));
2792 let expr_b = col("c2").and(lit(true));
2793 let expected = col("c2");
2794
2795 assert_eq!(simplify(expr_a), expected);
2796 assert_eq!(simplify(expr_b), expected);
2797 }
2798
2799 #[test]
2800 fn test_simplify_and_not_self() {
2801 let expr_a = col("c2_non_null").and(col("c2_non_null").not());
2804 let expr_b = col("c2_non_null").not().and(col("c2_non_null"));
2805 let expected = lit(false);
2806
2807 assert_eq!(simplify(expr_a), expected);
2808 assert_eq!(simplify(expr_b), expected);
2809 }
2810
2811 #[test]
2812 fn test_simplify_eq_and_neq_with_different_literals() {
2813 let expr = col("c2").eq(lit(1)).and(col("c2").not_eq(lit(0)));
2815 let expected = col("c2").eq(lit(1));
2816 assert_eq!(simplify(expr), expected);
2817
2818 let expr = col("c2").not_eq(lit(0)).and(col("c2").eq(lit(1)));
2820 let expected = col("c2").eq(lit(1));
2821 assert_eq!(simplify(expr), expected);
2822
2823 let expr = col("c2").eq(lit(1)).and(col("c2").not_eq(lit(1)));
2826 let result = simplify(expr.clone());
2828 assert_eq!(result, expr);
2830
2831 let expr = col("f")
2834 .eq(lit(0.0_f64))
2835 .and(col("f").not_eq(lit(-0.0_f64)));
2836 assert_eq!(simplify(expr.clone()), expr);
2837 }
2838
2839 #[test]
2840 fn test_simplify_multiply_by_one() {
2841 let expr_a = col("c2") * lit(1);
2842 let expr_b = lit(1) * col("c2");
2843 let expected = col("c2");
2844
2845 assert_eq!(simplify(expr_a), expected);
2846 assert_eq!(simplify(expr_b), expected);
2847
2848 let expr = col("c2") * lit(ScalarValue::Decimal128(Some(10000000000), 38, 10));
2849 assert_eq!(simplify(expr), expected);
2850
2851 let expr = lit(ScalarValue::Decimal128(Some(10000000000), 31, 10)) * col("c2");
2852 assert_eq!(simplify(expr), expected);
2853 }
2854
2855 #[test]
2856 fn test_simplify_multiply_by_null() {
2857 let null = lit(ScalarValue::Int64(None));
2858 {
2860 let expr = col("c3") * null.clone();
2861 assert_eq!(simplify(expr), null);
2862 }
2863 {
2865 let expr = null.clone() * col("c3");
2866 assert_eq!(simplify(expr), null);
2867 }
2868 }
2869
2870 #[test]
2871 fn test_simplify_multiply_by_zero() {
2872 {
2874 let expr_a = col("c2") * lit(0);
2875 let expr_b = lit(0) * col("c2");
2876
2877 assert_eq!(simplify(expr_a.clone()), expr_a);
2878 assert_eq!(simplify(expr_b.clone()), expr_b);
2879 }
2880 {
2882 let expr = lit(0) * col("c2_non_null");
2883 assert_eq!(simplify(expr), lit(0));
2884 }
2885 {
2887 let expr = col("c2_non_null") * lit(0);
2888 assert_eq!(simplify(expr), lit(0));
2889 }
2890 {
2892 let expr = col("c2_non_null") * lit(ScalarValue::Decimal128(Some(0), 31, 10));
2893 assert_eq!(
2894 simplify(expr),
2895 lit(ScalarValue::Decimal128(Some(0), 31, 10))
2896 );
2897 let expr = binary_expr(
2898 lit(ScalarValue::Decimal128(Some(0), 31, 10)),
2899 Operator::Multiply,
2900 col("c2_non_null"),
2901 );
2902 assert_eq!(
2903 simplify(expr),
2904 lit(ScalarValue::Decimal128(Some(0), 31, 10))
2905 );
2906 }
2907 }
2908
2909 #[test]
2910 fn test_simplify_divide_by_one() {
2911 let expr = binary_expr(col("c2"), Operator::Divide, lit(1));
2912 let expected = col("c2");
2913 assert_eq!(simplify(expr), expected);
2914 let expr = col("c2") / lit(ScalarValue::Decimal128(Some(10000000000), 31, 10));
2915 assert_eq!(simplify(expr), expected);
2916 }
2917
2918 #[test]
2919 fn test_simplify_divide_null() {
2920 let null = lit(ScalarValue::Int64(None));
2922 {
2923 let expr = col("c3") / null.clone();
2924 assert_eq!(simplify(expr), null);
2925 }
2926 {
2928 let expr = null.clone() / col("c3");
2929 assert_eq!(simplify(expr), null);
2930 }
2931 }
2932
2933 #[test]
2934 fn test_simplify_divide_by_same() {
2935 let expr = col("c2") / col("c2");
2936 let expected = expr.clone();
2938
2939 assert_eq!(simplify(expr), expected);
2940 }
2941
2942 #[test]
2943 fn test_simplify_modulo_by_null() {
2944 let null = lit(ScalarValue::Int64(None));
2945 {
2947 let expr = col("c3") % null.clone();
2948 assert_eq!(simplify(expr), null);
2949 }
2950 {
2952 let expr = null.clone() % col("c3");
2953 assert_eq!(simplify(expr), null);
2954 }
2955 }
2956
2957 #[test]
2958 fn test_simplify_modulo_by_one() {
2959 let expr = col("c2") % lit(1);
2960 let expected = expr.clone();
2962
2963 assert_eq!(simplify(expr), expected);
2964 }
2965
2966 #[test]
2967 fn test_simplify_divide_zero_by_zero() {
2968 let expr = lit(0) / lit(0);
2971 let expected = expr.clone();
2972
2973 assert_eq!(simplify(expr), expected);
2974 }
2975
2976 #[test]
2977 fn test_simplify_divide_by_zero() {
2978 let expr = col("c2_non_null") / lit(0);
2981 let expected = expr.clone();
2982
2983 assert_eq!(simplify(expr), expected);
2984 }
2985
2986 #[test]
2987 fn test_simplify_modulo_by_one_non_null() {
2988 let expr = col("c3_non_null") % lit(1);
2989 let expected = lit(0_i64);
2990 assert_eq!(simplify(expr), expected);
2991 let expr =
2992 col("c3_non_null") % lit(ScalarValue::Decimal128(Some(10000000000), 31, 10));
2993 assert_eq!(simplify(expr), expected);
2994 }
2995
2996 #[test]
2997 fn test_simplify_modulo_by_one_types() {
2998 for (data_type, folds) in [
2999 (DataType::Int8, true),
3000 (DataType::Int16, true),
3001 (DataType::Int32, true),
3002 (DataType::Int64, true),
3003 (DataType::UInt8, true),
3004 (DataType::UInt16, true),
3005 (DataType::UInt32, true),
3006 (DataType::UInt64, true),
3007 (DataType::Float32, false),
3008 (DataType::Float64, false),
3009 (DataType::Decimal32(9, -1), true),
3010 (DataType::Decimal32(9, 0), true),
3011 (DataType::Decimal32(9, 2), false),
3012 (DataType::Decimal64(18, -1), true),
3013 (DataType::Decimal64(18, 0), true),
3014 (DataType::Decimal64(18, 2), false),
3015 (DataType::Decimal128(38, -1), true),
3016 (DataType::Decimal128(38, 0), true),
3017 (DataType::Decimal128(38, 2), false),
3018 (DataType::Decimal256(76, -1), true),
3019 (DataType::Decimal256(76, 0), true),
3020 (DataType::Decimal256(76, 2), false),
3021 ] {
3022 for nullable in [false, true] {
3023 let schema =
3024 Schema::new(vec![Field::new("a", data_type.clone(), nullable)])
3025 .to_dfschema_ref()
3026 .unwrap();
3027 let simplifier = ExprSimplifier::new(
3028 SimplifyContext::builder().with_schema(schema).build(),
3029 );
3030 let expr = col("a") % lit(1);
3031 let expected = if folds && !nullable {
3032 lit(ScalarValue::new_zero(&data_type).unwrap())
3033 } else {
3034 expr.clone()
3035 };
3036 assert_eq!(
3037 simplifier.simplify(expr).unwrap(),
3038 expected,
3039 "{data_type:?}, nullable={nullable}"
3040 );
3041 }
3042 }
3043 }
3044
3045 #[test]
3046 fn test_simplify_bitwise_xor_by_null() {
3047 let null = lit(ScalarValue::Int64(None));
3048 {
3050 let expr = col("c3") ^ null.clone();
3051 assert_eq!(simplify(expr), null);
3052 }
3053 {
3055 let expr = null.clone() ^ col("c3");
3056 assert_eq!(simplify(expr), null);
3057 }
3058 }
3059
3060 #[test]
3061 fn test_simplify_bitwise_shift_right_by_null() {
3062 let null = lit(ScalarValue::Int64(None));
3063 {
3065 let expr = col("c3") >> null.clone();
3066 assert_eq!(simplify(expr), null);
3067 }
3068 {
3070 let expr = null.clone() >> col("c3");
3071 assert_eq!(simplify(expr), null);
3072 }
3073 }
3074
3075 #[test]
3076 fn test_simplify_bitwise_shift_left_by_null() {
3077 let null = lit(ScalarValue::Int64(None));
3078 {
3080 let expr = col("c3") << null.clone();
3081 assert_eq!(simplify(expr), null);
3082 }
3083 {
3085 let expr = null.clone() << col("c3");
3086 assert_eq!(simplify(expr), null);
3087 }
3088 }
3089
3090 #[test]
3091 fn test_simplify_bitwise_and_by_zero() {
3092 {
3094 let expr = col("c2_non_null") & lit(0);
3095 assert_eq!(simplify(expr), lit(0));
3096 }
3097 {
3099 let expr = lit(0) & col("c2_non_null");
3100 assert_eq!(simplify(expr), lit(0));
3101 }
3102 }
3103
3104 #[test]
3105 fn test_simplify_bitwise_or_by_zero() {
3106 {
3108 let expr = col("c2_non_null") | lit(0);
3109 assert_eq!(simplify(expr), col("c2_non_null"));
3110 }
3111 {
3113 let expr = lit(0) | col("c2_non_null");
3114 assert_eq!(simplify(expr), col("c2_non_null"));
3115 }
3116 }
3117
3118 #[test]
3119 fn test_simplify_bitwise_xor_by_zero() {
3120 {
3122 let expr = col("c2_non_null") ^ lit(0);
3123 assert_eq!(simplify(expr), col("c2_non_null"));
3124 }
3125 {
3127 let expr = lit(0) ^ col("c2_non_null");
3128 assert_eq!(simplify(expr), col("c2_non_null"));
3129 }
3130 }
3131
3132 #[test]
3133 fn test_simplify_bitwise_bitwise_shift_right_by_zero() {
3134 {
3136 let expr = col("c2_non_null") >> lit(0);
3137 assert_eq!(simplify(expr), col("c2_non_null"));
3138 }
3139 }
3140
3141 #[test]
3142 fn test_simplify_bitwise_bitwise_shift_left_by_zero() {
3143 {
3145 let expr = col("c2_non_null") << lit(0);
3146 assert_eq!(simplify(expr), col("c2_non_null"));
3147 }
3148 }
3149
3150 #[test]
3151 fn test_simplify_bitwise_and_by_null() {
3152 let null = Expr::Literal(ScalarValue::Int64(None), None);
3153 {
3155 let expr = col("c3") & null.clone();
3156 assert_eq!(simplify(expr), null);
3157 }
3158 {
3160 let expr = null.clone() & col("c3");
3161 assert_eq!(simplify(expr), null);
3162 }
3163 }
3164
3165 #[test]
3166 fn test_simplify_concat_by_null() {
3167 let null = Expr::Literal(ScalarValue::Utf8(None), None);
3168 {
3170 let expr = binary_expr(col("c1"), Operator::StringConcat, null.clone());
3171 assert_eq!(simplify(expr), null);
3172 }
3173 {
3175 let expr = binary_expr(null.clone(), Operator::StringConcat, col("c1"));
3176 assert_eq!(simplify(expr), null);
3177 }
3178 }
3179
3180 #[test]
3181 fn test_simplify_composed_bitwise_and() {
3182 let expr = bitwise_and(
3185 bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
3186 col("c2").gt(lit(5)),
3187 );
3188 let expected = bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
3189
3190 assert_eq!(simplify(expr), expected);
3191
3192 let expr = bitwise_and(
3195 col("c2").gt(lit(5)),
3196 bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
3197 );
3198 let expected = bitwise_and(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
3199 assert_eq!(simplify(expr), expected);
3200 }
3201
3202 #[test]
3203 fn test_simplify_composed_bitwise_or() {
3204 let expr = bitwise_or(
3207 bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
3208 col("c2").gt(lit(5)),
3209 );
3210 let expected = bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
3211
3212 assert_eq!(simplify(expr), expected);
3213
3214 let expr = bitwise_or(
3217 col("c2").gt(lit(5)),
3218 bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
3219 );
3220 let expected = bitwise_or(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
3221
3222 assert_eq!(simplify(expr), expected);
3223 }
3224
3225 #[test]
3226 fn test_simplify_composed_bitwise_xor() {
3227 let expr = bitwise_xor(
3231 col("c2_non_null"),
3232 bitwise_xor(
3233 bitwise_xor(
3234 col("c2_non_null"),
3235 bitwise_or(col("c2_non_null"), col("c1")),
3236 ),
3237 bitwise_and(col("c1"), col("c2_non_null")),
3238 ),
3239 );
3240
3241 let expected = bitwise_xor(
3242 bitwise_or(col("c2_non_null"), col("c1")),
3243 bitwise_and(col("c1"), col("c2_non_null")),
3244 );
3245
3246 assert_eq!(simplify(expr), expected);
3247
3248 let expr = bitwise_xor(
3252 col("c2_non_null"),
3253 bitwise_xor(
3254 bitwise_xor(
3255 col("c2_non_null"),
3256 bitwise_or(col("c2_non_null"), col("c1")),
3257 ),
3258 bitwise_xor(
3259 bitwise_and(col("c1"), col("c2_non_null")),
3260 col("c2_non_null"),
3261 ),
3262 ),
3263 );
3264
3265 let expected = bitwise_xor(
3266 col("c2_non_null"),
3267 bitwise_xor(
3268 bitwise_or(col("c2_non_null"), col("c1")),
3269 bitwise_and(col("c1"), col("c2_non_null")),
3270 ),
3271 );
3272
3273 assert_eq!(simplify(expr), expected);
3274
3275 let expr = bitwise_xor(
3279 bitwise_xor(
3280 bitwise_xor(
3281 col("c2_non_null"),
3282 bitwise_or(col("c2_non_null"), col("c1")),
3283 ),
3284 bitwise_and(col("c1"), col("c2_non_null")),
3285 ),
3286 col("c2_non_null"),
3287 );
3288
3289 let expected = bitwise_xor(
3290 bitwise_or(col("c2_non_null"), col("c1")),
3291 bitwise_and(col("c1"), col("c2_non_null")),
3292 );
3293
3294 assert_eq!(simplify(expr), expected);
3295
3296 let expr = bitwise_xor(
3300 bitwise_xor(
3301 bitwise_xor(
3302 col("c2_non_null"),
3303 bitwise_or(col("c2_non_null"), col("c1")),
3304 ),
3305 bitwise_xor(
3306 bitwise_and(col("c1"), col("c2_non_null")),
3307 col("c2_non_null"),
3308 ),
3309 ),
3310 col("c2_non_null"),
3311 );
3312
3313 let expected = bitwise_xor(
3314 bitwise_xor(
3315 bitwise_or(col("c2_non_null"), col("c1")),
3316 bitwise_and(col("c1"), col("c2_non_null")),
3317 ),
3318 col("c2_non_null"),
3319 );
3320
3321 assert_eq!(simplify(expr), expected);
3322 }
3323
3324 #[test]
3325 fn test_does_not_cancel_nullable_bitwise_xor() {
3326 let nullable = col("c3");
3327 let other = col("c3_non_null");
3328
3329 let expr = bitwise_xor(nullable.clone(), nullable.clone());
3330 assert_eq!(simplify(expr.clone()), expr);
3331
3332 let expr = bitwise_xor(
3333 bitwise_xor(nullable.clone(), other.clone()),
3334 nullable.clone(),
3335 );
3336 assert_eq!(simplify(expr.clone()), expr);
3337
3338 let expr = bitwise_xor(nullable.clone(), bitwise_xor(other, nullable));
3339 assert_eq!(simplify(expr.clone()), expr);
3340 }
3341
3342 #[test]
3343 fn test_preserve_arithmetic_negation() {
3344 let c3 = col("c3_non_null");
3345 let expressions = [
3346 (-c3.clone()) & c3.clone(),
3347 c3.clone() & (-c3.clone()),
3348 (-c3.clone()) | c3.clone(),
3349 c3.clone() | (-c3.clone()),
3350 (-c3.clone()) ^ c3.clone(),
3351 c3.clone() ^ (-c3.clone()),
3352 -bitwise_and(col("c3"), c3.clone()),
3353 -bitwise_or(col("c3"), c3.clone()),
3354 ];
3355
3356 for expr in expressions {
3357 assert_eq!(simplify(expr.clone()), expr);
3358 }
3359
3360 assert_eq!(simplify(-(-c3.clone())), c3);
3362 }
3363
3364 #[test]
3365 fn test_simplify_bitwise_and_or() {
3366 let expr = bitwise_and(
3368 col("c2_non_null").lt(lit(3)),
3369 bitwise_or(col("c2_non_null").lt(lit(3)), col("c1_non_null")),
3370 );
3371 let expected = col("c2_non_null").lt(lit(3));
3372
3373 assert_eq!(simplify(expr), expected);
3374 }
3375
3376 #[test]
3377 fn test_simplify_bitwise_or_and() {
3378 let expr = bitwise_or(
3380 col("c2_non_null").lt(lit(3)),
3381 bitwise_and(col("c2_non_null").lt(lit(3)), col("c1_non_null")),
3382 );
3383 let expected = col("c2_non_null").lt(lit(3));
3384
3385 assert_eq!(simplify(expr), expected);
3386 }
3387
3388 #[test]
3389 fn test_simplify_simple_bitwise_and() {
3390 let expr = (col("c2").gt(lit(5))).bitand(col("c2").gt(lit(5)));
3392 let expected = col("c2").gt(lit(5));
3393
3394 assert_eq!(simplify(expr), expected);
3395 }
3396
3397 #[test]
3398 fn test_simplify_simple_bitwise_or() {
3399 let expr = (col("c2").gt(lit(5))).bitor(col("c2").gt(lit(5)));
3401 let expected = col("c2").gt(lit(5));
3402
3403 assert_eq!(simplify(expr), expected);
3404 }
3405
3406 #[test]
3407 fn test_simplify_simple_bitwise_xor() {
3408 let expr = (col("c4_non_null")).bitxor(col("c4_non_null"));
3410 let expected = lit(0u32);
3411
3412 assert_eq!(simplify(expr), expected);
3413
3414 let expr = col("c3_non_null").bitxor(col("c3_non_null"));
3416 let expected = lit(0i64);
3417
3418 assert_eq!(simplify(expr), expected);
3419 }
3420
3421 #[test]
3422 fn test_simplify_modulo_by_zero_non_null() {
3423 let expr = col("c2_non_null") % lit(0);
3426 let expected = expr.clone();
3427
3428 assert_eq!(simplify(expr), expected);
3429 }
3430
3431 #[test]
3432 fn test_simplify_simple_and() {
3433 let expr = (col("c2").gt(lit(5))).and(col("c2").gt(lit(5)));
3435 let expected = col("c2").gt(lit(5));
3436
3437 assert_eq!(simplify(expr), expected);
3438 }
3439
3440 #[test]
3441 fn test_simplify_composed_and() {
3442 let expr = and(
3444 and(col("c2").gt(lit(5)), col("c1").lt(lit(6))),
3445 col("c2").gt(lit(5)),
3446 );
3447 let expected = and(col("c2").gt(lit(5)), col("c1").lt(lit(6)));
3448
3449 assert_eq!(simplify(expr), expected);
3450 }
3451
3452 #[test]
3453 fn test_simplify_negated_and() {
3454 let expr = and(col("c2").gt(lit(5)), Expr::not(col("c2").gt(lit(5))));
3456 let expected = col("c2").gt(lit(5)).and(col("c2").lt_eq(lit(5)));
3457
3458 assert_eq!(simplify(expr), expected);
3459 }
3460
3461 #[test]
3462 fn test_simplify_or_and() {
3463 let l = col("c2").gt(lit(5));
3464 let r = and(col("c1").lt(lit(6)), col("c2").gt(lit(5)));
3465
3466 let expr = or(l.clone(), r.clone());
3468
3469 let expected = l.clone();
3470 assert_eq!(simplify(expr), expected);
3471
3472 let expr = or(r, l);
3474 assert_eq!(simplify(expr), expected);
3475 }
3476
3477 #[test]
3478 fn test_simplify_or_and_non_null() {
3479 let l = col("c2_non_null").gt(lit(5));
3480 let r = and(col("c1_non_null").lt(lit(6)), col("c2_non_null").gt(lit(5)));
3481
3482 let expr = or(l.clone(), r.clone());
3484
3485 let expected = col("c2_non_null").gt(lit(5));
3487
3488 assert_eq!(simplify(expr), expected);
3489
3490 let expr = or(l, r);
3492
3493 assert_eq!(simplify(expr), expected);
3494 }
3495
3496 #[test]
3497 fn test_simplify_and_or() {
3498 let l = col("c2").gt(lit(5));
3499 let r = or(col("c1").lt(lit(6)), col("c2").gt(lit(5)));
3500
3501 let expr = and(l.clone(), r.clone());
3503
3504 let expected = l.clone();
3505 assert_eq!(simplify(expr), expected);
3506
3507 let expr = and(r, l);
3509 assert_eq!(simplify(expr), expected);
3510 }
3511
3512 #[test]
3513 fn test_simplify_and_or_non_null() {
3514 let l = col("c2_non_null").gt(lit(5));
3515 let r = or(col("c1_non_null").lt(lit(6)), col("c2_non_null").gt(lit(5)));
3516
3517 let expr = and(l.clone(), r.clone());
3519
3520 let expected = col("c2_non_null").gt(lit(5));
3522
3523 assert_eq!(simplify(expr), expected);
3524
3525 let expr = and(l, r);
3527
3528 assert_eq!(simplify(expr), expected);
3529 }
3530
3531 #[test]
3532 fn test_simplify_by_de_morgan_laws() {
3533 let expr = and(col("c3"), col("c4")).not();
3536 let expected = or(col("c3").not(), col("c4").not());
3537 assert_eq!(simplify(expr), expected);
3538 let expr = or(col("c3"), col("c4")).not();
3540 let expected = and(col("c3").not(), col("c4").not());
3541 assert_eq!(simplify(expr), expected);
3542 let expr = col("c3").not().not();
3544 let expected = col("c3");
3545 assert_eq!(simplify(expr), expected);
3546 }
3547
3548 #[test]
3549 fn test_simplify_null_and_false() {
3550 let expr = and(lit_bool_null(), lit(false));
3551 let expr_eq = lit(false);
3552
3553 assert_eq!(simplify(expr), expr_eq);
3554 }
3555
3556 #[test]
3557 fn test_simplify_divide_null_by_null() {
3558 let null = lit(ScalarValue::Int32(None));
3559 let expr_plus = null.clone() / null.clone();
3560 let expr_eq = null;
3561
3562 assert_eq!(simplify(expr_plus), expr_eq);
3563 }
3564
3565 #[test]
3566 fn test_simplify_simplify_arithmetic_expr() {
3567 let expr_plus = lit(1) + lit(1);
3568
3569 assert_eq!(simplify(expr_plus), lit(2));
3570 }
3571
3572 #[test]
3573 fn test_simplify_simplify_eq_expr() {
3574 let expr_eq = binary_expr(lit(1), Operator::Eq, lit(1));
3575
3576 assert_eq!(simplify(expr_eq), lit(true));
3577 }
3578
3579 #[test]
3580 fn test_constant_regex_respects_planning_budget() {
3581 assert_eq!(simplify(regex_match(lit("aaaaa"), lit("^a+$"))), lit(true));
3583
3584 let pattern = "a{5}{5}{5}{5}{5}{5}";
3587 let binary_expr = regex_match(lit("aaaaa"), lit(pattern));
3588 assert_eq!(simplify(binary_expr.clone()), binary_expr);
3589
3590 let aliased = regex_match(lit("aaaaa"), lit(pattern)).alias("matched");
3593 assert_eq!(simplify(aliased.clone()), aliased);
3594
3595 #[derive(Debug, PartialEq, Eq, Hash)]
3596 struct DeferredConstUdf {
3597 signature: Signature,
3598 }
3599
3600 impl ScalarUDFImpl for DeferredConstUdf {
3601 fn name(&self) -> &str {
3602 "deferred_const"
3603 }
3604
3605 fn signature(&self) -> &Signature {
3606 &self.signature
3607 }
3608
3609 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
3610 Ok(DataType::Boolean)
3611 }
3612
3613 fn invoke_with_args(
3614 &self,
3615 _args: ScalarFunctionArgs,
3616 ) -> Result<ColumnarValue> {
3617 panic!("deferred UDF must not be evaluated during planning")
3618 }
3619
3620 fn should_evaluate_const(&self, _args: &[&ScalarValue]) -> bool {
3621 false
3622 }
3623 }
3624
3625 let udf = ScalarUDF::new_from_impl(DeferredConstUdf {
3627 signature: Signature::exact(vec![DataType::Utf8], Volatility::Immutable),
3628 });
3629 let udf_expr = udf.call(vec![lit("value")]);
3630 assert_eq!(simplify(udf_expr.clone()), udf_expr);
3631 }
3632
3633 #[test]
3634 fn test_simplify_regex() {
3635 assert_contains!(
3637 try_simplify(regex_match(col("c1"), lit("foo{")))
3638 .unwrap_err()
3639 .to_string(),
3640 "regex parse error"
3641 );
3642
3643 assert_no_change(regex_match(col("c1"), lit("foo.*")));
3645 assert_no_change(regex_match(col("c1"), lit("(foo)")));
3646 assert_no_change(regex_match(col("c1"), lit("%")));
3647 assert_no_change(regex_match(col("c1"), lit("_")));
3648 assert_no_change(regex_match(col("c1"), lit("f%o")));
3649 assert_no_change(regex_match(col("c1"), lit("^f%o")));
3650 assert_no_change(regex_match(col("c1"), lit("f_o")));
3651
3652 assert_change(
3654 regex_match(col("c1"), lit("")),
3655 if_not_null(col("c1"), true),
3656 );
3657 assert_change(
3658 regex_not_match(col("c1"), lit("")),
3659 if_not_null(col("c1"), false),
3660 );
3661 assert_change(
3662 regex_imatch(col("c1"), lit("")),
3663 if_not_null(col("c1"), true),
3664 );
3665 assert_change(
3666 regex_not_imatch(col("c1"), lit("")),
3667 if_not_null(col("c1"), false),
3668 );
3669
3670 assert_change(regex_match(col("c1"), lit("x")), col("c1").like(lit("%x%")));
3672
3673 assert_change(
3675 regex_match(col("c1"), lit("foo")),
3676 col("c1").like(lit("%foo%")),
3677 );
3678
3679 assert_change(regex_match(col("c1"), lit("^$")), col("c1").eq(lit("")));
3681 assert_change(
3682 regex_not_match(col("c1"), lit("^$")),
3683 col("c1").not_eq(lit("")),
3684 );
3685 assert_change(
3686 regex_match(col("c1"), lit("^foo$")),
3687 col("c1").eq(lit("foo")),
3688 );
3689 assert_change(
3690 regex_not_match(col("c1"), lit("^foo$")),
3691 col("c1").not_eq(lit("foo")),
3692 );
3693
3694 assert_change(
3696 regex_match(col("c1"), lit("^(foo|bar)$")),
3697 col("c1").eq(lit("foo")).or(col("c1").eq(lit("bar"))),
3698 );
3699 assert_change(
3700 regex_not_match(col("c1"), lit("^(foo|bar)$")),
3701 col("c1")
3702 .not_eq(lit("foo"))
3703 .and(col("c1").not_eq(lit("bar"))),
3704 );
3705 assert_change(
3706 regex_match(col("c1"), lit("^(foo)$")),
3707 col("c1").eq(lit("foo")),
3708 );
3709 assert_change(
3710 regex_match(col("c1"), lit("^(foo|bar|baz)$")),
3711 ((col("c1").eq(lit("foo"))).or(col("c1").eq(lit("bar"))))
3712 .or(col("c1").eq(lit("baz"))),
3713 );
3714 assert_change(
3715 regex_match(col("c1"), lit("^(foo|bar|baz|qux)$")),
3716 col("c1")
3717 .in_list(vec![lit("foo"), lit("bar"), lit("baz"), lit("qux")], false),
3718 );
3719 assert_change(
3720 regex_match(col("c1"), lit("^(fo_o)$")),
3721 col("c1").eq(lit("fo_o")),
3722 );
3723 assert_change(
3724 regex_match(col("c1"), lit("^(fo_o)$")),
3725 col("c1").eq(lit("fo_o")),
3726 );
3727 assert_change(
3728 regex_match(col("c1"), lit("^(fo_o|ba_r)$")),
3729 col("c1").eq(lit("fo_o")).or(col("c1").eq(lit("ba_r"))),
3730 );
3731 assert_change(
3732 regex_not_match(col("c1"), lit("^(fo_o|ba_r)$")),
3733 col("c1")
3734 .not_eq(lit("fo_o"))
3735 .and(col("c1").not_eq(lit("ba_r"))),
3736 );
3737 assert_change(
3738 regex_match(col("c1"), lit("^(fo_o|ba_r|ba_z)$")),
3739 ((col("c1").eq(lit("fo_o"))).or(col("c1").eq(lit("ba_r"))))
3740 .or(col("c1").eq(lit("ba_z"))),
3741 );
3742 assert_change(
3743 regex_match(col("c1"), lit("^(fo_o|ba_r|baz|qu_x)$")),
3744 col("c1").in_list(
3745 vec![lit("fo_o"), lit("ba_r"), lit("baz"), lit("qu_x")],
3746 false,
3747 ),
3748 );
3749
3750 assert_no_change(regex_match(col("c1"), lit("(foo|bar)")));
3752 assert_no_change(regex_match(col("c1"), lit("(foo|bar)*")));
3753 assert_no_change(regex_match(col("c1"), lit("(fo_o|b_ar)")));
3754 assert_no_change(regex_match(col("c1"), lit("(foo|ba_r)*")));
3755 assert_no_change(regex_match(col("c1"), lit("(fo_o|ba_r)*")));
3756 assert_no_change(regex_match(col("c1"), lit("^(foo|bar)*")));
3757 assert_no_change(regex_match(col("c1"), lit("^(foo)(bar)$")));
3758 assert_no_change(regex_match(col("c1"), lit("^")));
3759 assert_no_change(regex_match(col("c1"), lit("$")));
3760 assert_no_change(regex_match(col("c1"), lit("$^")));
3761 assert_no_change(regex_match(col("c1"), lit("$foo^")));
3762
3763 assert_change(
3765 regex_match(col("c1"), lit("^foo")),
3766 col("c1").like(lit("foo%")),
3767 );
3768 assert_change(
3769 regex_match(col("c1"), lit("foo$")),
3770 col("c1").like(lit("%foo")),
3771 );
3772 assert_change(
3773 regex_match(col("c1"), lit("^foo|bar$")),
3774 col("c1").like(lit("foo%")).or(col("c1").like(lit("%bar"))),
3775 );
3776
3777 assert_change(
3779 regex_match(col("c1"), lit("foo|bar|baz")),
3780 col("c1")
3781 .like(lit("%foo%"))
3782 .or(col("c1").like(lit("%bar%")))
3783 .or(col("c1").like(lit("%baz%"))),
3784 );
3785 assert_change(
3786 regex_match(col("c1"), lit("foo|x|baz")),
3787 col("c1")
3788 .like(lit("%foo%"))
3789 .or(col("c1").like(lit("%x%")))
3790 .or(col("c1").like(lit("%baz%"))),
3791 );
3792 assert_change(
3793 regex_not_match(col("c1"), lit("foo|bar|baz")),
3794 col("c1")
3795 .not_like(lit("%foo%"))
3796 .and(col("c1").not_like(lit("%bar%")))
3797 .and(col("c1").not_like(lit("%baz%"))),
3798 );
3799 assert_change(
3801 regex_match(col("c1"), lit("foo|^x$|baz")),
3802 col("c1")
3803 .like(lit("%foo%"))
3804 .or(col("c1").eq(lit("x")))
3805 .or(col("c1").like(lit("%baz%"))),
3806 );
3807 assert_change(
3808 regex_not_match(col("c1"), lit("foo|^bar$|baz")),
3809 col("c1")
3810 .not_like(lit("%foo%"))
3811 .and(col("c1").not_eq(lit("bar")))
3812 .and(col("c1").not_like(lit("%baz%"))),
3813 );
3814 assert_no_change(regex_match(col("c1"), lit("foo|bar|baz|blarg|bozo|etc")));
3816 }
3817
3818 #[test]
3819 fn test_simplify_not_regex_match() {
3820 let pattern = || lit("foo.*");
3821
3822 assert_eq!(
3824 simplify(regex_match(col("c1"), pattern()).not()),
3825 regex_not_match(col("c1"), pattern()),
3826 );
3827 assert_eq!(
3829 simplify(regex_not_match(col("c1"), pattern()).not()),
3830 regex_match(col("c1"), pattern()),
3831 );
3832 assert_eq!(
3834 simplify(regex_imatch(col("c1"), pattern()).not()),
3835 regex_not_imatch(col("c1"), pattern()),
3836 );
3837 assert_eq!(
3839 simplify(regex_not_imatch(col("c1"), pattern()).not()),
3840 regex_imatch(col("c1"), pattern()),
3841 );
3842 }
3843
3844 #[track_caller]
3845 fn assert_no_change(expr: Expr) {
3846 let optimized = simplify(expr.clone());
3847 assert_eq!(expr, optimized);
3848 }
3849
3850 #[track_caller]
3851 fn assert_change(expr: Expr, expected: Expr) {
3852 let optimized = simplify(expr);
3853 assert_eq!(optimized, expected);
3854 }
3855
3856 fn regex_match(left: Expr, right: Expr) -> Expr {
3857 Expr::BinaryExpr(BinaryExpr {
3858 left: Box::new(left),
3859 op: Operator::RegexMatch,
3860 right: Box::new(right),
3861 })
3862 }
3863
3864 fn regex_not_match(left: Expr, right: Expr) -> Expr {
3865 Expr::BinaryExpr(BinaryExpr {
3866 left: Box::new(left),
3867 op: Operator::RegexNotMatch,
3868 right: Box::new(right),
3869 })
3870 }
3871
3872 fn regex_imatch(left: Expr, right: Expr) -> Expr {
3873 Expr::BinaryExpr(BinaryExpr {
3874 left: Box::new(left),
3875 op: Operator::RegexIMatch,
3876 right: Box::new(right),
3877 })
3878 }
3879
3880 fn regex_not_imatch(left: Expr, right: Expr) -> Expr {
3881 Expr::BinaryExpr(BinaryExpr {
3882 left: Box::new(left),
3883 op: Operator::RegexNotIMatch,
3884 right: Box::new(right),
3885 })
3886 }
3887
3888 fn try_simplify(expr: Expr) -> Result<Expr> {
3893 let schema = expr_test_schema();
3894 let simplifier =
3895 ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build());
3896 simplifier.simplify(expr)
3897 }
3898
3899 fn coerce(expr: Expr) -> Expr {
3900 let schema = expr_test_schema();
3901 let simplifier = ExprSimplifier::new(
3902 SimplifyContext::builder()
3903 .with_schema(Arc::clone(&schema))
3904 .build(),
3905 );
3906 simplifier.coerce(expr, schema.as_ref()).unwrap()
3907 }
3908
3909 fn simplify(expr: Expr) -> Expr {
3910 try_simplify(expr).unwrap()
3911 }
3912
3913 fn simplify_no_canonicalize(expr: Expr) -> Expr {
3914 simplify_no_canonicalize_with_cycle_count(expr).0
3915 }
3916
3917 fn simplify_no_canonicalize_with_cycle_count(expr: Expr) -> (Expr, u32) {
3918 let schema = expr_test_schema();
3919 let (transformed, count) =
3920 ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build())
3921 .with_canonicalize(false)
3922 .simplify_with_cycle_count_transformed(expr)
3923 .unwrap();
3924 (transformed.data, count)
3925 }
3926
3927 fn try_simplify_with_cycle_count(expr: Expr) -> Result<(Expr, u32)> {
3928 let schema = expr_test_schema();
3929 let simplifier =
3930 ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build());
3931 let (expr, count) = simplifier.simplify_with_cycle_count_transformed(expr)?;
3932 Ok((expr.data, count))
3933 }
3934
3935 fn simplify_with_cycle_count(expr: Expr) -> (Expr, u32) {
3936 try_simplify_with_cycle_count(expr).unwrap()
3937 }
3938
3939 fn simplify_with_guarantee(
3940 expr: Expr,
3941 guarantees: Vec<(Expr, NullableInterval)>,
3942 ) -> Expr {
3943 let schema = expr_test_schema();
3944 let simplifier =
3945 ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build())
3946 .with_guarantees(guarantees);
3947 simplifier.simplify(expr).unwrap()
3948 }
3949
3950 fn expr_test_schema() -> DFSchemaRef {
3951 static EXPR_TEST_SCHEMA: LazyLock<DFSchemaRef> = LazyLock::new(|| {
3952 Arc::new(
3953 DFSchema::from_unqualified_fields(
3954 vec![
3955 Field::new("c1", DataType::Utf8, true),
3956 Field::new("c2", DataType::Boolean, true),
3957 Field::new("c3", DataType::Int64, true),
3958 Field::new("c4", DataType::UInt32, true),
3959 Field::new("c1_non_null", DataType::Utf8, false),
3960 Field::new("c2_non_null", DataType::Boolean, false),
3961 Field::new("c3_non_null", DataType::Int64, false),
3962 Field::new("c4_non_null", DataType::UInt32, false),
3963 Field::new("c5", DataType::FixedSizeBinary(3), true),
3964 ]
3965 .into(),
3966 HashMap::new(),
3967 )
3968 .unwrap(),
3969 )
3970 });
3971 Arc::clone(&EXPR_TEST_SCHEMA)
3972 }
3973
3974 #[test]
3975 fn simplify_expr_null_comparison() {
3976 assert_eq!(
3978 simplify(lit(true).eq(lit(ScalarValue::Boolean(None)))),
3979 lit(ScalarValue::Boolean(None)),
3980 );
3981
3982 assert_eq!(
3984 simplify(
3985 lit(ScalarValue::Boolean(None)).not_eq(lit(ScalarValue::Boolean(None)))
3986 ),
3987 lit(ScalarValue::Boolean(None)),
3988 );
3989
3990 assert_eq!(
3992 simplify(col("c2").not_eq(lit(ScalarValue::Boolean(None)))),
3993 lit(ScalarValue::Boolean(None)),
3994 );
3995
3996 assert_eq!(
3998 simplify(lit(ScalarValue::Boolean(None)).eq(col("c2"))),
3999 lit(ScalarValue::Boolean(None)),
4000 );
4001 }
4002
4003 #[test]
4004 fn simplify_expr_is_not_null() {
4005 assert_eq!(
4006 simplify(Expr::IsNotNull(Box::new(col("c1")))),
4007 Expr::IsNotNull(Box::new(col("c1")))
4008 );
4009
4010 assert_eq!(
4012 simplify(Expr::IsNotNull(Box::new(col("c1_non_null")))),
4013 lit(true)
4014 );
4015 }
4016
4017 #[test]
4018 fn simplify_expr_is_null() {
4019 assert_eq!(
4020 simplify(Expr::IsNull(Box::new(col("c1")))),
4021 Expr::IsNull(Box::new(col("c1")))
4022 );
4023
4024 assert_eq!(
4026 simplify(Expr::IsNull(Box::new(col("c1_non_null")))),
4027 lit(false)
4028 );
4029 }
4030
4031 #[test]
4032 fn simplify_scalar_subquery_is_null() {
4033 let possibly_empty = LogicalPlanBuilder::empty(false)
4034 .project(vec![lit(1)])
4035 .unwrap()
4036 .build()
4037 .unwrap();
4038 let possibly_empty = scalar_subquery(Arc::new(possibly_empty));
4039
4040 assert_eq!(
4041 simplify(possibly_empty.clone().is_null()),
4042 possibly_empty.is_null()
4043 );
4044
4045 let always_one = LogicalPlanBuilder::empty(true)
4046 .project(vec![lit(1)])
4047 .unwrap()
4048 .build()
4049 .unwrap();
4050 let always_one = scalar_subquery(Arc::new(always_one));
4051 assert_eq!(simplify(always_one.is_null()), lit(false));
4052 }
4053
4054 #[test]
4055 fn simplify_expr_is_unknown() {
4056 assert_eq!(simplify(col("c2").is_unknown()), col("c2").is_unknown(),);
4057
4058 assert_eq!(simplify(col("c2_non_null").is_unknown()), lit(false));
4060 }
4061
4062 #[test]
4063 fn simplify_expr_is_not_known() {
4064 assert_eq!(
4065 simplify(col("c2").is_not_unknown()),
4066 col("c2").is_not_unknown()
4067 );
4068
4069 assert_eq!(simplify(col("c2_non_null").is_not_unknown()), lit(true));
4071 }
4072
4073 #[test]
4074 fn simplify_expr_eq() {
4075 let schema = expr_test_schema();
4076 assert_eq!(col("c2").get_type(&schema).unwrap(), DataType::Boolean);
4077
4078 assert_eq!(simplify(lit(true).eq(lit(true))), lit(true));
4080
4081 assert_eq!(simplify(lit(true).eq(lit(false))), lit(false),);
4083
4084 assert_eq!(simplify(col("c2").eq(lit(true))), col("c2"));
4086
4087 assert_eq!(simplify(col("c2").eq(lit(false))), col("c2").not(),);
4089 }
4090
4091 #[test]
4092 fn simplify_expr_eq_skip_nonboolean_type() {
4093 let schema = expr_test_schema();
4094
4095 assert_eq!(col("c1").get_type(&schema).unwrap(), DataType::Utf8);
4101
4102 assert_eq!(simplify(col("c1").eq(lit("foo"))), col("c1").eq(lit("foo")),);
4104 }
4105
4106 #[test]
4107 fn simplify_expr_not_eq() {
4108 let schema = expr_test_schema();
4109
4110 assert_eq!(col("c2").get_type(&schema).unwrap(), DataType::Boolean);
4111
4112 assert_eq!(simplify(col("c2").not_eq(lit(true))), col("c2").not(),);
4114
4115 assert_eq!(simplify(col("c2").not_eq(lit(false))), col("c2"),);
4117
4118 assert_eq!(simplify(lit(true).not_eq(lit(true))), lit(false),);
4120
4121 assert_eq!(simplify(lit(true).not_eq(lit(false))), lit(true),);
4122 }
4123
4124 #[test]
4125 fn simplify_expr_not_eq_skip_nonboolean_type() {
4126 let schema = expr_test_schema();
4127
4128 assert_eq!(col("c1").get_type(&schema).unwrap(), DataType::Utf8);
4132
4133 assert_eq!(
4134 simplify(col("c1").not_eq(lit("foo"))),
4135 col("c1").not_eq(lit("foo")),
4136 );
4137 }
4138
4139 #[test]
4140 fn simplify_literal_case_equality() {
4141 let simple_case = Expr::Case(Case::new(
4143 None,
4144 vec![(
4145 Box::new(col("c2_non_null").not_eq(lit(false))),
4146 Box::new(lit("ok")),
4147 )],
4148 Some(Box::new(lit("not_ok"))),
4149 ));
4150
4151 assert_eq!(
4159 simplify(binary_expr(simple_case.clone(), Operator::Eq, lit("ok"),)),
4160 col("c2_non_null"),
4161 );
4162
4163 assert_eq!(
4171 simplify(binary_expr(simple_case, Operator::NotEq, lit("ok"),)),
4172 not(col("c2_non_null")),
4173 );
4174
4175 let complex_case = Expr::Case(Case::new(
4176 None,
4177 vec![
4178 (
4179 Box::new(col("c1").eq(lit("inboxed"))),
4180 Box::new(lit("pending")),
4181 ),
4182 (
4183 Box::new(col("c1").eq(lit("scheduled"))),
4184 Box::new(lit("pending")),
4185 ),
4186 (
4187 Box::new(col("c1").eq(lit("completed"))),
4188 Box::new(lit("completed")),
4189 ),
4190 (
4191 Box::new(col("c1").eq(lit("paused"))),
4192 Box::new(lit("paused")),
4193 ),
4194 (Box::new(col("c2")), Box::new(lit("running"))),
4195 (
4196 Box::new(col("c1").eq(lit("invoked")).and(col("c3").gt(lit(0)))),
4197 Box::new(lit("backing-off")),
4198 ),
4199 ],
4200 Some(Box::new(lit("ready"))),
4201 ));
4202
4203 for (op, value, outputs) in [
4206 (
4207 Operator::Eq,
4208 "completed",
4209 [false, false, true, false, false, false, false],
4210 ),
4211 (
4212 Operator::NotEq,
4213 "completed",
4214 [true, true, false, true, true, true, true],
4215 ),
4216 (
4217 Operator::Eq,
4218 "running",
4219 [false, false, false, false, true, false, false],
4220 ),
4221 (
4222 Operator::Eq,
4223 "ready",
4224 [false, false, false, false, false, false, true],
4225 ),
4226 (
4227 Operator::NotEq,
4228 "ready",
4229 [true, true, true, true, true, true, false],
4230 ),
4231 ] {
4232 let Expr::Case(mut expected) = complex_case.clone() else {
4233 unreachable!()
4234 };
4235 for ((_, then), value) in expected.when_then_expr.iter_mut().zip(outputs) {
4236 **then = lit(value);
4237 }
4238 expected.else_expr = Some(Box::new(lit(outputs[6])));
4239 assert_eq!(
4240 simplify(binary_expr(complex_case.clone(), op, lit(value))),
4241 Expr::Case(expected)
4242 );
4243 }
4244 }
4245
4246 #[test]
4247 fn simplify_case_preserves_conditional_expressions() {
4248 let fallible =
4249 Expr::Cast(Cast::new(Box::new(col("c1")), DataType::Int32)).gt(lit(0_i32));
4250 let volatile = Expr::ScalarFunction(ScalarFunction::new_udf(
4251 Arc::new(ScalarUDF::new_from_impl(VolatileUdf::new())),
4252 vec![],
4253 ));
4254 for expr in [
4255 Expr::Case(Case::new(
4256 None,
4257 vec![(Box::new(fallible.clone()), Box::new(lit(false)))],
4258 Some(Box::new(lit(false))),
4259 )),
4260 Expr::Case(Case::new(
4261 None,
4262 vec![(Box::new(col("c2")), Box::new(fallible.clone()))],
4263 Some(Box::new(lit(false))),
4264 )),
4265 Expr::Case(Case::new(
4266 None,
4267 vec![(Box::new(col("c2")), Box::new(lit(true)))],
4268 Some(Box::new(fallible.clone())),
4269 )),
4270 Expr::Case(Case::new(
4271 None,
4272 vec![
4273 (Box::new(col("c2")), Box::new(lit(false))),
4274 (Box::new(fallible), Box::new(lit(true))),
4275 ],
4276 Some(Box::new(lit(false))),
4277 )),
4278 Expr::Case(Case::new(
4279 None,
4280 vec![(Box::new(volatile.gt(lit(0_i16))), Box::new(lit(true)))],
4281 Some(Box::new(col("c2"))),
4282 )),
4283 ] {
4284 assert_eq!(simplify(expr.clone()), expr);
4285 }
4286 }
4287
4288 #[test]
4289 fn simplify_expr_case_when_then_else() {
4290 assert_eq!(
4296 simplify(Expr::Case(Case::new(
4297 None,
4298 vec![(
4299 Box::new(col("c2_non_null").not_eq(lit(false))),
4300 Box::new(lit("ok").eq(lit("not_ok"))),
4301 )],
4302 Some(Box::new(col("c2_non_null").eq(lit(true)))),
4303 ))),
4304 lit(false) );
4306
4307 assert_eq!(
4316 simplify(simplify(Expr::Case(Case::new(
4317 None,
4318 vec![(
4319 Box::new(col("c2_non_null").not_eq(lit(false))),
4320 Box::new(lit("ok").eq(lit("ok"))),
4321 )],
4322 Some(Box::new(col("c2_non_null").eq(lit(true)))),
4323 )))),
4324 col("c2_non_null")
4325 );
4326
4327 let expected = Expr::Case(Case::new(
4332 None,
4333 vec![(Box::new(col("c2").is_null()), Box::new(lit(true)))],
4334 Some(Box::new(col("c2"))),
4335 ));
4336 assert_eq!(
4337 simplify(simplify(Expr::Case(Case::new(
4338 None,
4339 vec![(Box::new(col("c2").is_null()), Box::new(lit(true)),)],
4340 Some(Box::new(col("c2"))),
4341 )))),
4342 expected
4343 );
4344
4345 assert_eq!(
4353 simplify(simplify(Expr::Case(Case::new(
4354 None,
4355 vec![
4356 (Box::new(col("c1_non_null")), Box::new(lit(true)),),
4357 (Box::new(col("c2_non_null")), Box::new(lit(false)),),
4358 ],
4359 Some(Box::new(lit(true))),
4360 )))),
4361 col("c1_non_null").or(col("c1_non_null").not().and(col("c2_non_null").not()))
4362 );
4363
4364 assert_eq!(
4372 simplify(simplify(Expr::Case(Case::new(
4373 None,
4374 vec![
4375 (Box::new(col("c1_non_null")), Box::new(lit(true)),),
4376 (Box::new(col("c2_non_null")), Box::new(lit(false)),),
4377 ],
4378 Some(Box::new(lit(true))),
4379 )))),
4380 col("c1_non_null").or(col("c1_non_null").not().and(col("c2_non_null").not()))
4381 );
4382
4383 for expr in [
4385 Expr::Case(Case::new(
4386 None,
4387 vec![(Box::new(col("c3").gt(lit(0_i64))), Box::new(lit(true)))],
4388 None,
4389 )),
4390 Expr::Case(Case::new(
4391 None,
4392 vec![(Box::new(col("c3").gt(lit(0_i64))), Box::new(lit(true)))],
4393 Some(Box::new(lit(false))),
4394 )),
4395 ] {
4396 assert_eq!(simplify(simplify(expr.clone())), expr);
4397 }
4398 }
4399
4400 #[test]
4401 fn simplify_expr_case_when_first_true() {
4402 assert_eq!(
4404 simplify(Expr::Case(Case::new(
4405 None,
4406 vec![(Box::new(lit(true)), Box::new(lit(1)),)],
4407 Some(Box::new(col("c1"))),
4408 ))),
4409 lit(1)
4410 );
4411
4412 assert_eq!(
4414 simplify(Expr::Case(Case::new(
4415 None,
4416 vec![(Box::new(lit(true)), Box::new(lit("a")),)],
4417 Some(Box::new(lit("b"))),
4418 ))),
4419 lit("a")
4420 );
4421
4422 assert_eq!(
4424 simplify(Expr::Case(Case::new(
4425 None,
4426 vec![
4427 (Box::new(lit(true)), Box::new(lit("a"))),
4428 (Box::new(lit("x").gt(lit(5))), Box::new(lit("b"))),
4429 ],
4430 Some(Box::new(lit("c"))),
4431 ))),
4432 lit("a")
4433 );
4434
4435 assert_eq!(
4437 simplify(Expr::Case(Case::new(
4438 None,
4439 vec![(Box::new(lit(true)), Box::new(lit("a")),)],
4440 None,
4441 ))),
4442 lit("a")
4443 );
4444
4445 let expr = Expr::Case(Case::new(
4447 None,
4448 vec![(Box::new(col("c2")), Box::new(lit(1)))],
4449 Some(Box::new(lit(2))),
4450 ));
4451 assert_eq!(simplify(expr.clone()), expr);
4452
4453 let expr = Expr::Case(Case::new(
4455 None,
4456 vec![(Box::new(lit(false)), Box::new(lit(1)))],
4457 Some(Box::new(lit(2))),
4458 ));
4459 assert_ne!(simplify(expr), lit(1));
4460
4461 let expr = Expr::Case(Case::new(
4463 None,
4464 vec![(Box::new(col("c1").gt(lit(5))), Box::new(lit(1)))],
4465 Some(Box::new(lit(2))),
4466 ));
4467 assert_eq!(simplify(expr.clone()), expr);
4468 }
4469
4470 #[test]
4471 fn simplify_expr_case_when_any_true() {
4472 assert_eq!(
4474 simplify(Expr::Case(Case::new(
4475 None,
4476 vec![
4477 (Box::new(col("c3").gt(lit(0))), Box::new(lit("a"))),
4478 (Box::new(lit(true)), Box::new(lit("b"))),
4479 ],
4480 Some(Box::new(lit("c"))),
4481 ))),
4482 Expr::Case(Case::new(
4483 None,
4484 vec![(Box::new(col("c3").gt(lit(0))), Box::new(lit("a")))],
4485 Some(Box::new(lit("b"))),
4486 ))
4487 );
4488
4489 assert_eq!(
4492 simplify(Expr::Case(Case::new(
4493 None,
4494 vec![
4495 (Box::new(col("c3").gt(lit(0))), Box::new(lit("a"))),
4496 (Box::new(col("c4").lt(lit(0))), Box::new(lit("b"))),
4497 (Box::new(lit(true)), Box::new(lit("c"))),
4498 (Box::new(col("c3").eq(lit(0))), Box::new(lit("d"))),
4499 ],
4500 Some(Box::new(lit("e"))),
4501 ))),
4502 Expr::Case(Case::new(
4503 None,
4504 vec![
4505 (Box::new(col("c3").gt(lit(0))), Box::new(lit("a"))),
4506 (Box::new(col("c4").lt(lit(0))), Box::new(lit("b"))),
4507 ],
4508 Some(Box::new(lit("c"))),
4509 ))
4510 );
4511
4512 assert_eq!(
4515 simplify(Expr::Case(Case::new(
4516 None,
4517 vec![
4518 (Box::new(col("c3").gt(lit(0))), Box::new(lit(1))),
4519 (Box::new(col("c4").lt(lit(0))), Box::new(lit(2))),
4520 (Box::new(lit(true)), Box::new(lit(3))),
4521 ],
4522 None,
4523 ))),
4524 Expr::Case(Case::new(
4525 None,
4526 vec![
4527 (Box::new(col("c3").gt(lit(0))), Box::new(lit(1))),
4528 (Box::new(col("c4").lt(lit(0))), Box::new(lit(2))),
4529 ],
4530 Some(Box::new(lit(3))),
4531 ))
4532 );
4533
4534 let expr = Expr::Case(Case::new(
4536 None,
4537 vec![
4538 (Box::new(col("c3").gt(lit(0))), Box::new(col("c3"))),
4539 (Box::new(col("c4").lt(lit(0))), Box::new(lit(2))),
4540 ],
4541 Some(Box::new(lit(3))),
4542 ));
4543 assert_eq!(simplify(expr.clone()), expr);
4544 }
4545
4546 #[test]
4547 fn simplify_expr_case_when_any_false() {
4548 assert_eq!(
4550 simplify(Expr::Case(Case::new(
4551 None,
4552 vec![(Box::new(lit(false)), Box::new(lit("a")))],
4553 None,
4554 ))),
4555 Expr::Literal(ScalarValue::Utf8(None), None)
4556 );
4557
4558 assert_eq!(
4560 simplify(Expr::Case(Case::new(
4561 None,
4562 vec![(Box::new(lit(false)), Box::new(lit(2)))],
4563 Some(Box::new(lit(1))),
4564 ))),
4565 lit(1),
4566 );
4567
4568 assert_eq!(
4570 simplify(Expr::Case(Case::new(
4571 None,
4572 vec![
4573 (Box::new(col("c3").lt(lit(10))), Box::new(lit("b"))),
4574 (Box::new(lit(false)), Box::new(col("c3"))),
4575 ],
4576 Some(Box::new(col("c4"))),
4577 ))),
4578 Expr::Case(Case::new(
4579 None,
4580 vec![(Box::new(col("c3").lt(lit(10))), Box::new(lit("b")))],
4581 Some(Box::new(col("c4"))),
4582 ))
4583 );
4584
4585 let expr = Expr::Case(Case::new(
4587 None,
4588 vec![(Box::new(col("c3").eq(lit(4))), Box::new(lit(1)))],
4589 Some(Box::new(lit(2))),
4590 ));
4591 assert_eq!(simplify(expr.clone()), expr);
4592 }
4593
4594 #[test]
4595 fn simplify_expr_bool_or() {
4596 assert_eq!(simplify(col("c2").or(lit(true))), lit(true),);
4598
4599 assert_eq!(simplify(col("c2").or(lit(false))), col("c2"),);
4601
4602 assert_eq!(simplify(lit(true).or(lit_bool_null())), lit(true),);
4604
4605 assert_eq!(simplify(lit_bool_null().or(lit(true))), lit(true),);
4607
4608 assert_eq!(simplify(lit(false).or(lit_bool_null())), lit_bool_null(),);
4610
4611 assert_eq!(simplify(lit_bool_null().or(lit(false))), lit_bool_null(),);
4613
4614 let expr = col("c1").between(lit(0), lit(10));
4618 let expr = expr.or(lit_bool_null());
4619 let result = simplify(expr);
4620
4621 let expected_expr = or(
4622 and(col("c1").gt_eq(lit(0)), col("c1").lt_eq(lit(10))),
4623 lit_bool_null(),
4624 );
4625 assert_eq!(expected_expr, result);
4626 }
4627
4628 #[test]
4629 fn simplify_inlist() {
4630 assert_eq!(simplify(in_list(col("c1"), vec![], false)), lit(false));
4631 assert_eq!(simplify(in_list(col("c1"), vec![], true)), lit(true));
4632
4633 assert_eq!(
4635 simplify(in_list(lit_bool_null(), vec![col("c1"), lit(1)], false)),
4636 lit_bool_null()
4637 );
4638
4639 assert_eq!(
4641 simplify(in_list(lit_bool_null(), vec![col("c1"), lit(1)], true)),
4642 lit_bool_null()
4643 );
4644
4645 assert_eq!(
4646 simplify(in_list(col("c1"), vec![lit(1)], false)),
4647 col("c1").eq(lit(1))
4648 );
4649 assert_eq!(
4650 simplify(in_list(col("c1"), vec![lit(1)], true)),
4651 col("c1").not_eq(lit(1))
4652 );
4653
4654 assert_eq!(
4657 simplify(in_list(col("c1") * lit(10), vec![lit(2)], false)),
4658 (col("c1") * lit(10)).eq(lit(2))
4659 );
4660
4661 assert_eq!(
4662 simplify(in_list(col("c1"), vec![lit(1), lit(2)], false)),
4663 col("c1").eq(lit(1)).or(col("c1").eq(lit(2)))
4664 );
4665 assert_eq!(
4666 simplify(in_list(col("c1"), vec![lit(1), lit(2)], true)),
4667 col("c1").not_eq(lit(1)).and(col("c1").not_eq(lit(2)))
4668 );
4669
4670 let subquery = Arc::new(test_table_scan_with_name("test").unwrap());
4671 assert_eq!(
4672 simplify(in_list(
4673 col("c1"),
4674 vec![scalar_subquery(Arc::clone(&subquery))],
4675 false
4676 )),
4677 in_subquery(col("c1"), Arc::clone(&subquery))
4678 );
4679 assert_eq!(
4680 simplify(in_list(
4681 col("c1"),
4682 vec![scalar_subquery(Arc::clone(&subquery))],
4683 true
4684 )),
4685 not_in_subquery(col("c1"), subquery)
4686 );
4687
4688 let subquery1 =
4689 scalar_subquery(Arc::new(test_table_scan_with_name("test1").unwrap()));
4690 let subquery2 =
4691 scalar_subquery(Arc::new(test_table_scan_with_name("test2").unwrap()));
4692
4693 assert_eq!(
4695 simplify(in_list(
4696 col("c1"),
4697 vec![subquery1.clone(), subquery2.clone()],
4698 true
4699 )),
4700 col("c1")
4701 .not_eq(subquery1.clone())
4702 .and(col("c1").not_eq(subquery2.clone()))
4703 );
4704
4705 assert_eq!(
4707 simplify(in_list(
4708 col("c1"),
4709 vec![subquery1.clone(), subquery2.clone()],
4710 false
4711 )),
4712 col("c1").eq(subquery1).or(col("c1").eq(subquery2))
4713 );
4714
4715 let expr = in_list(
4717 col("c1_non_null"),
4718 vec![lit(1), lit(2), lit(3), lit(4)],
4719 false,
4720 )
4721 .and(in_list(
4722 col("c1_non_null"),
4723 vec![lit(5), lit(6), lit(7), lit(8)],
4724 false,
4725 ));
4726 assert_eq!(simplify(expr), lit(false));
4727
4728 let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], false).and(
4730 in_list(col("c1"), vec![lit(5), lit(6), lit(7), lit(8)], false),
4731 );
4732 assert_eq!(simplify(expr), col("c1").is_null().and(lit_bool_null()));
4733
4734 let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], false).and(
4736 in_list(col("c1"), vec![lit(4), lit(5), lit(6), lit(7)], false),
4737 );
4738 assert_eq!(simplify(expr), col("c1").eq(lit(4)));
4739
4740 let expr = in_list(
4742 col("c1_non_null"),
4743 vec![lit(1), lit(2), lit(3), lit(4)],
4744 true,
4745 )
4746 .or(in_list(
4747 col("c1_non_null"),
4748 vec![lit(5), lit(6), lit(7), lit(8)],
4749 true,
4750 ));
4751 assert_eq!(simplify(expr), lit(true));
4752
4753 let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).or(
4755 in_list(col("c1"), vec![lit(5), lit(6), lit(7), lit(8)], true),
4756 );
4757 assert_eq!(simplify(expr), col("c1").is_not_null().or(lit_bool_null()));
4758
4759 let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).or(
4761 in_list(col("c1"), vec![lit(4), lit(5), lit(6), lit(7)], true),
4762 );
4763 assert_eq!(simplify(expr), col("c1").not_eq(lit(4)));
4764
4765 let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).and(
4767 in_list(col("c1"), vec![lit(4), lit(5), lit(6), lit(7)], true),
4768 );
4769 assert_eq!(
4770 simplify(expr),
4771 in_list(
4772 col("c1"),
4773 vec![lit(1), lit(2), lit(3), lit(4), lit(5), lit(6), lit(7)],
4774 true
4775 )
4776 );
4777
4778 let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], false).or(
4780 in_list(col("c1"), vec![lit(2), lit(3), lit(4), lit(5)], false),
4781 );
4782 assert_eq!(
4783 simplify(expr),
4784 in_list(
4785 col("c1"),
4786 vec![lit(1), lit(2), lit(3), lit(4), lit(5)],
4787 false
4788 )
4789 );
4790
4791 let expr = in_list(col("c1_non_null"), vec![lit(1), lit(2), lit(3)], false).and(
4793 in_list(
4794 col("c1_non_null"),
4795 vec![lit(1), lit(2), lit(3), lit(4), lit(5)],
4796 true,
4797 ),
4798 );
4799 assert_eq!(simplify(expr), lit(false));
4800
4801 let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3)], false).and(in_list(
4803 col("c1"),
4804 vec![lit(1), lit(2), lit(3), lit(4), lit(5)],
4805 true,
4806 ));
4807 assert_eq!(simplify(expr), col("c1").is_null().and(lit_bool_null()));
4808
4809 let expr =
4811 in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).and(in_list(
4812 col("c1"),
4813 vec![lit(1), lit(2), lit(3), lit(4), lit(5)],
4814 false,
4815 ));
4816 assert_eq!(simplify(expr), col("c1").eq(lit(5)));
4817
4818 let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], false).and(
4820 in_list(col("c1"), vec![lit(5), lit(6), lit(7), lit(8)], true),
4821 );
4822 assert_eq!(
4823 simplify(expr),
4824 in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], false)
4825 );
4826
4827 let expr = in_list(
4830 col("c1"),
4831 vec![lit(1), lit(2), lit(3), lit(4), lit(5), lit(6)],
4832 false,
4833 )
4834 .and(in_list(
4835 col("c1"),
4836 vec![lit(1), lit(3), lit(5), lit(6)],
4837 false,
4838 ))
4839 .and(in_list(col("c1"), vec![lit(3), lit(6)], false));
4840 assert_eq!(
4841 simplify(expr),
4842 col("c1").eq(lit(3)).or(col("c1").eq(lit(6)))
4843 );
4844
4845 let expr = in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).and(
4847 in_list(col("c1"), vec![lit(5), lit(6), lit(7), lit(8)], false)
4848 .and(in_list(
4849 col("c1"),
4850 vec![lit(3), lit(4), lit(5), lit(6)],
4851 true,
4852 ))
4853 .and(in_list(col("c1"), vec![lit(8), lit(9), lit(10)], false)),
4854 );
4855 assert_eq!(simplify(expr), col("c1").eq(lit(8)));
4856
4857 let expr =
4860 in_list(col("c1"), vec![lit(1), lit(2), lit(3), lit(4)], true).or(col("c1")
4861 .not_eq(lit(5))
4862 .or(in_list(
4863 col("c1"),
4864 vec![lit(6), lit(7), lit(8), lit(9)],
4865 true,
4866 )));
4867 assert_eq!(simplify(expr.clone()), expr);
4871 }
4872
4873 fn assert_inlist_simplification_result(
4874 expr: Expr,
4875 batch: &RecordBatch,
4876 expected: Vec<bool>,
4877 ) -> Result<()> {
4878 let schema = batch.schema().to_dfschema_ref()?;
4879 let simplifier = ExprSimplifier::new(
4880 SimplifyContext::builder()
4881 .with_schema(Arc::clone(&schema))
4882 .build(),
4883 );
4884 let original = simplifier.coerce(expr, &schema)?;
4885 let simplified = simplifier.simplify(original.clone())?;
4886 let props = ExecutionProps::new();
4887 let evaluate = |expr: &Expr| {
4888 create_physical_expr(
4889 expr,
4890 &schema,
4891 &props,
4892 &PhysicalPlanningContext::default(),
4893 )?
4894 .evaluate(batch)?
4895 .into_array(batch.num_rows())
4896 };
4897 let original_result = evaluate(&original)?;
4898 let actual = evaluate(&simplified)?;
4899 assert_eq!(original_result.as_ref(), actual.as_ref());
4900 assert_eq!(actual.as_boolean(), &BooleanArray::from(expected));
4901 Ok(())
4902 }
4903
4904 #[test]
4905 fn simplify_inlist_runtime_set_operations() -> Result<()> {
4906 let schema = Arc::new(Schema::new(vec![
4907 Field::new("x", DataType::Int32, false),
4908 Field::new("a", DataType::Int32, false),
4909 Field::new("b", DataType::Int32, false),
4910 ]));
4911 let batch = RecordBatch::try_new(
4912 schema,
4913 vec![
4914 Arc::new(Int32Array::from(vec![1, 2, 3])),
4915 Arc::new(Int32Array::from(vec![1, 1, 3])),
4916 Arc::new(Int32Array::from(vec![1, 2, 4])),
4917 ],
4918 )?;
4919 let left = |negated| {
4920 in_list(col("x"), vec![col("a"), lit(2), lit(10), lit(11)], negated)
4921 };
4922 let right = |negated| {
4923 in_list(col("x"), vec![col("b"), lit(5), lit(12), lit(13)], negated)
4924 };
4925
4926 for (expr, expected) in [
4928 (left(false).and(right(false)), vec![true, true, false]),
4929 (left(false).and(right(true)), vec![false, false, true]),
4930 (left(true).and(right(false)), vec![false, false, false]),
4931 (left(true).or(right(true)), vec![false, false, true]),
4932 (left(false).or(right(false)), vec![true, true, true]),
4934 (left(true).and(right(true)), vec![false, false, false]),
4935 ] {
4936 assert_inlist_simplification_result(expr, &batch, expected)?;
4937 }
4938
4939 let expr = in_list(col("x"), vec![lit(1i32), lit(2), lit(10), lit(11)], false)
4941 .and(in_list(
4942 col("x"),
4943 vec![lit(1i64), lit(3i64), lit(12i64), lit(13i64)],
4944 false,
4945 ));
4946 assert_inlist_simplification_result(expr, &batch, vec![true, false, false])
4947 }
4948
4949 #[test]
4950 fn simplify_inlist_signed_zero() -> Result<()> {
4951 for data_type in [DataType::Float16, DataType::Float32, DataType::Float64] {
4952 let values =
4953 arrow::compute::cast(&Float64Array::from(vec![0.0, -0.0]), &data_type)?;
4954 let literals = |values: &[f64]| {
4955 values
4956 .iter()
4957 .map(|&value| {
4958 ScalarValue::Float64(Some(value))
4959 .cast_to(&data_type)
4960 .map(lit)
4961 })
4962 .collect::<Result<Vec<_>>>()
4963 };
4964 let left_list = literals(&[0.0, 1.0, 2.0, 3.0])?;
4965 let right_list = literals(&[-0.0, 4.0, 5.0, 6.0])?;
4966 let retains_short_lists =
4967 matches!(data_type, DataType::Float32 | DataType::Float64);
4968 let schema = Arc::new(Schema::new(vec![Field::new("x", data_type, false)]));
4969 let batch = RecordBatch::try_new(schema, vec![values])?;
4970 let schema = batch.schema().to_dfschema_ref()?;
4971 let simplifier = ExprSimplifier::new(
4972 SimplifyContext::builder()
4973 .with_schema(Arc::clone(&schema))
4974 .build(),
4975 )
4976 .with_canonicalize(false);
4977 assert!(left_list.len() > THRESHOLD_INLINE_INLIST);
4979 assert!(right_list.len() > THRESHOLD_INLINE_INLIST);
4980 for list_len in [2, left_list.len()] {
4981 let left =
4982 |negated| in_list(col("x"), left_list[..list_len].to_vec(), negated);
4983 let right =
4984 |negated| in_list(col("x"), right_list[..list_len].to_vec(), negated);
4985 for (expr, expected) in [
4986 (left(false).and(right(false)), vec![true, true]),
4987 (left(false).and(right(true)), vec![false, false]),
4988 (left(true).and(right(false)), vec![false, false]),
4989 (left(true).or(right(true)), vec![false, false]),
4990 ] {
4991 let simplified = simplifier.simplify(expr.clone())?;
4992 if list_len > THRESHOLD_INLINE_INLIST || retains_short_lists {
4993 assert_eq!(simplified, expr);
4995 } else {
4996 let actual = create_physical_expr(
4997 &simplified,
4998 &schema,
4999 &ExecutionProps::new(),
5000 &PhysicalPlanningContext::default(),
5001 )?
5002 .evaluate(&batch)?
5003 .into_array(batch.num_rows())?;
5004 assert_eq!(actual.as_boolean(), &BooleanArray::from(expected));
5005 }
5006 }
5007 }
5008 }
5009 Ok(())
5010 }
5011
5012 #[test]
5013 fn simplify_inlist_preserves_volatile_evaluations() {
5014 let fun = Arc::new(ScalarUDF::new_from_impl(VolatileUdf::new()));
5015 let volatile = Expr::ScalarFunction(ScalarFunction::new_udf(fun, vec![]));
5016 let left = |negated| {
5017 in_list(
5018 volatile.clone(),
5019 vec![lit(1), lit(2), lit(3), lit(4)],
5020 negated,
5021 )
5022 };
5023 let right = |negated| {
5024 in_list(
5025 volatile.clone(),
5026 vec![lit(3), lit(4), lit(5), lit(6)],
5027 negated,
5028 )
5029 };
5030 for expr in [
5031 left(false).and(right(false)),
5032 left(false).and(right(true)),
5033 left(true).and(right(false)),
5034 left(true).or(right(true)),
5035 left(true).and(right(true)),
5036 ] {
5037 assert_eq!(simplify_no_canonicalize(expr.clone()), expr);
5038 }
5039
5040 for negated in [false, true] {
5042 let left = in_list(
5043 col("c1"),
5044 vec![volatile.clone(), lit(1), lit(2), lit(3)],
5045 negated,
5046 );
5047 let right = in_list(
5048 col("c1"),
5049 vec![volatile.clone(), lit(4), lit(5), lit(6)],
5050 negated,
5051 );
5052 let expr = if negated {
5053 left.and(right)
5054 } else {
5055 left.or(right)
5056 };
5057 assert_eq!(simplify_no_canonicalize(expr.clone()), expr);
5058 }
5059 }
5060
5061 #[test]
5062 fn simplify_short_inlist_types() {
5063 for (data_type, retain_short) in [
5064 (DataType::Int32, true),
5065 (DataType::Int64, true),
5066 (DataType::UInt64, true),
5067 (DataType::Float32, true),
5068 (DataType::Float64, true),
5069 (DataType::FixedSizeBinary(1), true),
5070 (DataType::FixedSizeBinary(2), true),
5071 (DataType::FixedSizeBinary(4), true),
5072 (DataType::FixedSizeBinary(8), true),
5073 (DataType::FixedSizeBinary(16), true),
5074 (DataType::Float16, false),
5075 (DataType::FixedSizeBinary(3), false),
5076 (DataType::Utf8View, false),
5077 (
5078 DataType::Dictionary(
5079 Box::new(DataType::Int8),
5080 Box::new(DataType::Float64),
5081 ),
5082 false,
5083 ),
5084 ] {
5085 let values = (1..=3)
5086 .map(|value| {
5087 lit(match &data_type {
5088 DataType::FixedSizeBinary(width) => ScalarValue::FixedSizeBinary(
5089 *width,
5090 Some(vec![value; *width as usize]),
5091 ),
5092 DataType::Utf8View => {
5093 ScalarValue::Utf8View(Some(value.to_string()))
5094 }
5095 _ => ScalarValue::Int32(Some(i32::from(value)))
5096 .cast_to(&data_type)
5097 .unwrap(),
5098 })
5099 })
5100 .collect::<Vec<_>>();
5101 let schema = Schema::new(vec![Field::new("value", data_type.clone(), true)])
5102 .to_dfschema_ref()
5103 .unwrap();
5104 let simplifier = ExprSimplifier::new(
5105 SimplifyContext::builder().with_schema(schema).build(),
5106 );
5107 for list_len in [2, 3] {
5108 for negated in [false, true] {
5109 let expr =
5110 in_list(col("value"), values[..list_len].to_vec(), negated);
5111 let simplified = simplifier.simplify(expr.clone()).unwrap();
5112 if retain_short {
5113 assert_eq!(simplified, expr, "{data_type:?}");
5114 } else {
5115 let op = if negated { Operator::And } else { Operator::Or };
5116 assert!(
5117 matches!(simplified, Expr::BinaryExpr(binary) if binary.op == op),
5118 "{data_type:?}, list_len={list_len}, negated={negated}"
5119 );
5120 }
5121 }
5122 }
5123 }
5124 }
5125
5126 #[test]
5127 fn simplify_short_inlist_coerced_literals() {
5128 for negated in [false, true] {
5129 let expr = in_list(col("c3"), vec![lit(1_i32), lit(2_i32)], negated);
5130 let expected = in_list(col("c3"), vec![lit(1_i64), lit(2_i64)], negated);
5131 assert_eq!(simplify(coerce(expr)), expected);
5132 }
5133 }
5134
5135 #[test]
5136 fn simplify_inlist_set_operation_propagates_nullability_errors() {
5137 let info = SimplifyContext::builder()
5138 .with_schema(expr_test_schema())
5139 .build();
5140 let valid = InList {
5141 expr: Box::new(col("c1")),
5142 list: vec![lit("a")],
5143 negated: false,
5144 };
5145
5146 let invalid_list_item = InList {
5147 expr: Box::new(col("c1")),
5148 list: vec![col("missing")],
5149 negated: false,
5150 };
5151 let error =
5152 simplify_inlist_set_operation(&info, &invalid_list_item, &valid, lit(false))
5153 .unwrap_err();
5154 assert_contains!(error.to_string(), "No field named missing");
5155
5156 let invalid_tested_expr = InList {
5157 expr: Box::new(col("missing")),
5158 list: vec![lit("a")],
5159 negated: false,
5160 };
5161 let error = simplify_inlist_set_operation(
5162 &info,
5163 &invalid_tested_expr,
5164 &valid,
5165 lit(false),
5166 )
5167 .unwrap_err();
5168 assert_contains!(error.to_string(), "No field named missing");
5169 }
5170
5171 #[test]
5172 fn simplify_inlist_set_operation_preserves_null_result() {
5173 let info = SimplifyContext::builder()
5174 .with_schema(expr_test_schema())
5175 .build();
5176 let left = InList {
5177 expr: Box::new(col("c1")),
5178 list: vec![lit("a")],
5179 negated: false,
5180 };
5181 let right = InList {
5182 expr: Box::new(col("c1")),
5183 list: vec![lit("b")],
5184 negated: false,
5185 };
5186
5187 assert_eq!(
5188 simplify_inlist_set_operation(&info, &left, &right, lit_bool_null()).unwrap(),
5189 Some(lit_bool_null())
5190 );
5191 }
5192
5193 #[test]
5194 fn simplify_null_in_empty_inlist() {
5195 let expr = in_list(lit_bool_null(), vec![], false);
5197 assert_eq!(simplify(expr), lit(false));
5198
5199 let expr = in_list(lit_bool_null(), vec![], true);
5201 assert_eq!(simplify(expr), lit(true));
5202
5203 let null_null = || Expr::Literal(ScalarValue::Null, None);
5205 let expr = in_list(null_null(), vec![], false);
5206 assert_eq!(simplify(expr), lit(false));
5207
5208 let expr = in_list(null_null(), vec![], true);
5210 assert_eq!(simplify(expr), lit(true));
5211 }
5212
5213 #[test]
5214 fn just_simplifier_simplify_null_in_empty_inlist() {
5215 let simplify = |expr: Expr| -> Expr {
5216 let schema = expr_test_schema();
5217 let info = SimplifyContext::builder().with_schema(schema).build();
5218 let simplifier = &mut Simplifier::new(&info);
5219 expr.rewrite(simplifier)
5220 .expect("Failed to simplify expression")
5221 .data
5222 };
5223
5224 let expr = in_list(lit_bool_null(), vec![], false);
5226 assert_eq!(simplify(expr), lit(false));
5227
5228 let expr = in_list(lit_bool_null(), vec![], true);
5230 assert_eq!(simplify(expr), lit(true));
5231
5232 let null_null = || Expr::Literal(ScalarValue::Null, None);
5234 let expr = in_list(null_null(), vec![], false);
5235 assert_eq!(simplify(expr), lit(false));
5236
5237 let expr = in_list(null_null(), vec![], true);
5239 assert_eq!(simplify(expr), lit(true));
5240 }
5241
5242 #[test]
5243 fn simplify_large_or() {
5244 let expr = (0..5)
5245 .map(|i| col("c1").eq(lit(i)))
5246 .fold(lit(false), |acc, e| acc.or(e));
5247 assert_eq!(
5248 simplify(expr),
5249 in_list(col("c1"), (0..5).map(lit).collect(), false),
5250 );
5251 }
5252
5253 #[test]
5254 fn simplify_expr_bool_and() {
5255 assert_eq!(simplify(col("c2").and(lit(true))), col("c2"),);
5257 assert_eq!(simplify(col("c2").and(lit(false))), lit(false),);
5259
5260 assert_eq!(simplify(lit(true).and(lit_bool_null())), lit_bool_null(),);
5262
5263 assert_eq!(simplify(lit_bool_null().and(lit(true))), lit_bool_null(),);
5265
5266 assert_eq!(simplify(lit(false).and(lit_bool_null())), lit(false),);
5268
5269 assert_eq!(simplify(lit_bool_null().and(lit(false))), lit(false),);
5271
5272 let expr = col("c1").between(lit(0), lit(10));
5276 let expr = expr.and(lit_bool_null());
5277 let result = simplify(expr);
5278
5279 let expected_expr = and(
5280 and(col("c1").gt_eq(lit(0)), col("c1").lt_eq(lit(10))),
5281 lit_bool_null(),
5282 );
5283 assert_eq!(expected_expr, result);
5284 }
5285
5286 #[test]
5287 fn simplify_expr_between() {
5288 let expr = col("c2").between(lit(3), lit(4));
5290 assert_eq!(
5291 simplify(expr),
5292 and(col("c2").gt_eq(lit(3)), col("c2").lt_eq(lit(4)))
5293 );
5294
5295 let expr = col("c2").not_between(lit(3), lit(4));
5297 assert_eq!(
5298 simplify(expr),
5299 or(col("c2").lt(lit(3)), col("c2").gt(lit(4)))
5300 );
5301 }
5302
5303 #[test]
5304 fn test_like_and_ilike() {
5305 let null = lit(ScalarValue::Utf8(None));
5306
5307 let expr = col("c1").like(null.clone());
5309 assert_eq!(simplify(expr), lit_bool_null());
5310
5311 let expr = col("c1").not_like(null.clone());
5312 assert_eq!(simplify(expr), lit_bool_null());
5313
5314 let expr = col("c1").ilike(null.clone());
5315 assert_eq!(simplify(expr), lit_bool_null());
5316
5317 let expr = col("c1").not_ilike(null.clone());
5318 assert_eq!(simplify(expr), lit_bool_null());
5319
5320 let expr = col("c1").like(lit("%"));
5322 assert_eq!(simplify(expr), if_not_null(col("c1"), true));
5323
5324 let expr = col("c1").not_like(lit("%"));
5325 assert_eq!(simplify(expr), if_not_null(col("c1"), false));
5326
5327 let expr = col("c1").ilike(lit("%"));
5328 assert_eq!(simplify(expr), if_not_null(col("c1"), true));
5329
5330 let expr = col("c1").not_ilike(lit("%"));
5331 assert_eq!(simplify(expr), if_not_null(col("c1"), false));
5332
5333 let expr = col("c1").like(lit("%%"));
5335 assert_eq!(simplify(expr), if_not_null(col("c1"), true));
5336
5337 let expr = col("c1").not_like(lit("%%"));
5338 assert_eq!(simplify(expr), if_not_null(col("c1"), false));
5339
5340 let expr = col("c1").ilike(lit("%%"));
5341 assert_eq!(simplify(expr), if_not_null(col("c1"), true));
5342
5343 let expr = col("c1").not_ilike(lit("%%"));
5344 assert_eq!(simplify(expr), if_not_null(col("c1"), false));
5345
5346 let expr = col("c1_non_null").like(lit("%"));
5348 assert_eq!(simplify(expr), lit(true));
5349
5350 let expr = col("c1_non_null").not_like(lit("%"));
5351 assert_eq!(simplify(expr), lit(false));
5352
5353 let expr = col("c1_non_null").ilike(lit("%"));
5354 assert_eq!(simplify(expr), lit(true));
5355
5356 let expr = col("c1_non_null").not_ilike(lit("%"));
5357 assert_eq!(simplify(expr), lit(false));
5358
5359 let expr = col("c1_non_null").like(lit("%%"));
5361 assert_eq!(simplify(expr), lit(true));
5362
5363 let expr = col("c1_non_null").not_like(lit("%%"));
5364 assert_eq!(simplify(expr), lit(false));
5365
5366 let expr = col("c1_non_null").ilike(lit("%%"));
5367 assert_eq!(simplify(expr), lit(true));
5368
5369 let expr = col("c1_non_null").not_ilike(lit("%%"));
5370 assert_eq!(simplify(expr), lit(false));
5371
5372 let expr = null.clone().like(lit("%"));
5374 assert_eq!(simplify(expr), lit_bool_null());
5375
5376 let expr = null.clone().not_like(lit("%"));
5377 assert_eq!(simplify(expr), lit_bool_null());
5378
5379 let expr = null.clone().ilike(lit("%"));
5380 assert_eq!(simplify(expr), lit_bool_null());
5381
5382 let expr = null.clone().not_ilike(lit("%"));
5383 assert_eq!(simplify(expr), lit_bool_null());
5384
5385 let expr = null.clone().like(lit("%%"));
5387 assert_eq!(simplify(expr), lit_bool_null());
5388
5389 let expr = null.clone().not_like(lit("%%"));
5390 assert_eq!(simplify(expr), lit_bool_null());
5391
5392 let expr = null.clone().ilike(lit("%%"));
5393 assert_eq!(simplify(expr), lit_bool_null());
5394
5395 let expr = null.clone().not_ilike(lit("%%"));
5396 assert_eq!(simplify(expr), lit_bool_null());
5397
5398 let expr = null.clone().like(lit("a%"));
5400 assert_eq!(simplify(expr), lit_bool_null());
5401
5402 let expr = null.clone().not_like(lit("a%"));
5403 assert_eq!(simplify(expr), lit_bool_null());
5404
5405 let expr = null.clone().ilike(lit("a%"));
5406 assert_eq!(simplify(expr), lit_bool_null());
5407
5408 let expr = null.clone().not_ilike(lit("a%"));
5409 assert_eq!(simplify(expr), lit_bool_null());
5410
5411 let expr = col("c1").like(lit("a"));
5413 assert_eq!(simplify(expr), col("c1").eq(lit("a")));
5414 let expr = col("c1").not_like(lit("a"));
5415 assert_eq!(simplify(expr), col("c1").not_eq(lit("a")));
5416 let expr = col("c1").like(lit("a_"));
5417 assert_eq!(simplify(expr), col("c1").like(lit("a_")));
5418 let expr = col("c1").not_like(lit("a_"));
5419 assert_eq!(simplify(expr), col("c1").not_like(lit("a_")));
5420
5421 let expr = col("c1").ilike(lit("a"));
5422 assert_eq!(simplify(expr), col("c1").ilike(lit("a")));
5423 let expr = col("c1").not_ilike(lit("a"));
5424 assert_eq!(simplify(expr), col("c1").not_ilike(lit("a")));
5425 }
5426
5427 #[test]
5428 fn test_simplify_with_guarantee() {
5429 let expr_x = col("c3").gt(lit(3_i64));
5431 let expr_y = (col("c4") + lit(2_u32)).lt(lit(10_u32));
5432 let expr_z = col("c1").in_list(vec![lit("a"), lit("b")], true);
5433 let expr = expr_x.clone().and(expr_y.or(expr_z));
5434
5435 let guarantees = vec![
5437 (col("c3"), NullableInterval::from(ScalarValue::Int64(None))),
5438 (col("c4"), NullableInterval::from(ScalarValue::UInt32(None))),
5439 (col("c1"), NullableInterval::from(ScalarValue::Utf8(None))),
5440 ];
5441
5442 let output = simplify_with_guarantee(expr.clone(), guarantees);
5443 assert_eq!(output, lit_bool_null());
5444
5445 let guarantees = vec![
5447 (
5448 col("c3"),
5449 NullableInterval::NotNull {
5450 values: Interval::make(Some(0_i64), Some(2_i64)).unwrap(),
5451 },
5452 ),
5453 (
5454 col("c4"),
5455 NullableInterval::from(ScalarValue::UInt32(Some(9))),
5456 ),
5457 (col("c1"), NullableInterval::from(ScalarValue::from("a"))),
5458 ];
5459 let output = simplify_with_guarantee(expr.clone(), guarantees);
5460 assert_eq!(output, lit(false));
5461
5462 let guarantees = vec![
5464 (
5465 col("c3"),
5466 NullableInterval::MaybeNull {
5467 values: Interval::make(Some(0_i64), Some(2_i64)).unwrap(),
5468 },
5469 ),
5470 (
5471 col("c4"),
5472 NullableInterval::MaybeNull {
5473 values: Interval::make(Some(9_u32), Some(9_u32)).unwrap(),
5474 },
5475 ),
5476 (
5477 col("c1"),
5478 NullableInterval::NotNull {
5479 values: Interval::try_new(
5480 ScalarValue::from("d"),
5481 ScalarValue::from("f"),
5482 )
5483 .unwrap(),
5484 },
5485 ),
5486 ];
5487 let output = simplify_with_guarantee(expr.clone(), guarantees);
5488 assert_eq!(&output, &expr_x);
5489
5490 let guarantees = vec![
5492 (
5493 col("c3"),
5494 NullableInterval::from(ScalarValue::Int64(Some(9))),
5495 ),
5496 (
5497 col("c4"),
5498 NullableInterval::from(ScalarValue::UInt32(Some(3))),
5499 ),
5500 ];
5501 let output = simplify_with_guarantee(expr.clone(), guarantees);
5502 assert_eq!(output, lit(true));
5503
5504 let guarantees = vec![(
5506 col("c4"),
5507 NullableInterval::from(ScalarValue::UInt32(Some(3))),
5508 )];
5509 let output = simplify_with_guarantee(expr, guarantees);
5510 assert_eq!(&output, &expr_x);
5511 }
5512
5513 #[test]
5514 fn test_expression_partial_simplify_1() {
5515 let expr = (lit(1) + lit(2)) + (lit(4) / lit(0));
5517 let expected = (lit(3)) + (lit(4) / lit(0));
5518
5519 assert_eq!(simplify(expr), expected);
5520 }
5521
5522 #[test]
5523 fn test_expression_partial_simplify_2() {
5524 let expr = (lit(1).gt(lit(2))).and(lit(4) / lit(0));
5526 let expected = lit(false);
5527
5528 assert_eq!(simplify(expr), expected);
5529 }
5530
5531 #[test]
5532 fn test_simplify_cycles() {
5533 let expr = lit(true);
5535 let expected = lit(true);
5536 let (expr, num_iter) = simplify_with_cycle_count(expr);
5537 assert_eq!(expr, expected);
5538 assert_eq!(num_iter, 1);
5539
5540 let expr = lit(true).not_eq(lit_bool_null()).or(lit(5).gt(lit(10)));
5542 let expected = lit_bool_null();
5543 let (expr, num_iter) = simplify_with_cycle_count(expr);
5544 assert_eq!(expr, expected);
5545 assert_eq!(num_iter, 2);
5546
5547 let expr = (((col("c4") - lit(10)) + lit(10)) * lit(100)) / lit(100);
5550 let expected = expr.clone();
5551 let (expr, num_iter) = simplify_with_cycle_count(expr);
5552 assert_eq!(expr, expected);
5553 assert_eq!(num_iter, 1);
5554
5555 let expr = col("c4")
5557 .lt(lit(1))
5558 .or(col("c3").lt(lit(2)))
5559 .and(col("c3_non_null").lt(lit(3)))
5560 .and(lit(false));
5561 let expected = lit(false);
5562 let (expr, num_iter) = simplify_with_cycle_count(expr);
5563 assert_eq!(expr, expected);
5564 assert_eq!(num_iter, 2);
5565 }
5566
5567 fn boolean_test_schema() -> DFSchemaRef {
5568 static BOOLEAN_TEST_SCHEMA: LazyLock<DFSchemaRef> = LazyLock::new(|| {
5569 Schema::new(vec![
5570 Field::new("A", DataType::Boolean, false),
5571 Field::new("B", DataType::Boolean, false),
5572 Field::new("C", DataType::Boolean, false),
5573 Field::new("D", DataType::Boolean, false),
5574 ])
5575 .to_dfschema_ref()
5576 .unwrap()
5577 });
5578 Arc::clone(&BOOLEAN_TEST_SCHEMA)
5579 }
5580
5581 #[test]
5582 fn simplify_common_factor_conjunction_in_disjunction() {
5583 let schema = boolean_test_schema();
5584 let simplifier =
5585 ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build());
5586
5587 let a = || col("A");
5588 let b = || col("B");
5589 let c = || col("C");
5590 let d = || col("D");
5591
5592 let expr = a().and(b()).or(a().and(c()));
5594 let expected = a().and(b().or(c()));
5595
5596 assert_eq!(expected, simplifier.simplify(expr).unwrap());
5597
5598 let expr = a().and(b()).or(a().and(c())).or(a().and(d()));
5600 let expected = a().and(b().or(c()).or(d()));
5601 assert_eq!(expected, simplifier.simplify(expr).unwrap());
5602
5603 let expr = a().or(b().and(c().and(a())));
5605 let expected = a();
5606 assert_eq!(expected, simplifier.simplify(expr).unwrap());
5607 }
5608
5609 #[test]
5610 fn test_simplify_udaf() {
5611 let udaf = AggregateUDF::new_from_impl(SimplifyMockUdaf::new_with_simplify());
5612 let aggregate_function_expr =
5613 Expr::AggregateFunction(expr::AggregateFunction::new_udf(
5614 udaf.into(),
5615 vec![],
5616 false,
5617 None,
5618 vec![],
5619 None,
5620 ));
5621
5622 let expected = col("result_column");
5623 assert_eq!(simplify(aggregate_function_expr), expected);
5624
5625 let udaf = AggregateUDF::new_from_impl(SimplifyMockUdaf::new_without_simplify());
5626 let aggregate_function_expr =
5627 Expr::AggregateFunction(expr::AggregateFunction::new_udf(
5628 udaf.into(),
5629 vec![],
5630 false,
5631 None,
5632 vec![],
5633 None,
5634 ));
5635
5636 let expected = aggregate_function_expr.clone();
5637 assert_eq!(simplify(aggregate_function_expr), expected);
5638 }
5639
5640 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
5643 struct SimplifyMockUdaf {
5644 simplify: bool,
5645 }
5646
5647 impl SimplifyMockUdaf {
5648 fn new_with_simplify() -> Self {
5650 Self { simplify: true }
5651 }
5652 fn new_without_simplify() -> Self {
5654 Self { simplify: false }
5655 }
5656 }
5657
5658 impl AggregateUDFImpl for SimplifyMockUdaf {
5659 fn name(&self) -> &str {
5660 "mock_simplify"
5661 }
5662
5663 fn signature(&self) -> &Signature {
5664 unimplemented!()
5665 }
5666
5667 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
5668 unimplemented!("not needed for tests")
5669 }
5670
5671 fn accumulator(
5672 &self,
5673 _acc_args: AccumulatorArgs,
5674 ) -> Result<Box<dyn Accumulator>> {
5675 unimplemented!("not needed for tests")
5676 }
5677
5678 fn groups_accumulator_supported(&self, _args: AccumulatorArgs) -> bool {
5679 unimplemented!("not needed for testing")
5680 }
5681
5682 fn create_groups_accumulator(
5683 &self,
5684 _args: AccumulatorArgs,
5685 ) -> Result<Box<dyn GroupsAccumulator>> {
5686 unimplemented!("not needed for testing")
5687 }
5688
5689 fn simplify(&self) -> Option<AggregateFunctionSimplification> {
5690 if self.simplify {
5691 Some(Box::new(|_, _| Ok(col("result_column"))))
5692 } else {
5693 None
5694 }
5695 }
5696 }
5697
5698 #[test]
5699 fn test_simplify_udwf() {
5700 let udwf = WindowFunctionDefinition::WindowUDF(
5701 WindowUDF::new_from_impl(SimplifyMockUdwf::new_with_simplify()).into(),
5702 );
5703 let window_function_expr = Expr::from(WindowFunction::new(udwf, vec![]));
5704
5705 let expected = col("result_column");
5706 assert_eq!(simplify(window_function_expr), expected);
5707
5708 let udwf = WindowFunctionDefinition::WindowUDF(
5709 WindowUDF::new_from_impl(SimplifyMockUdwf::new_without_simplify()).into(),
5710 );
5711 let window_function_expr = Expr::from(WindowFunction::new(udwf, vec![]));
5712
5713 let expected = window_function_expr.clone();
5714 assert_eq!(simplify(window_function_expr), expected);
5715 }
5716
5717 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
5720 struct SimplifyMockUdwf {
5721 simplify: bool,
5722 }
5723
5724 impl SimplifyMockUdwf {
5725 fn new_with_simplify() -> Self {
5727 Self { simplify: true }
5728 }
5729 fn new_without_simplify() -> Self {
5731 Self { simplify: false }
5732 }
5733 }
5734
5735 impl WindowUDFImpl for SimplifyMockUdwf {
5736 fn name(&self) -> &str {
5737 "mock_simplify"
5738 }
5739
5740 fn signature(&self) -> &Signature {
5741 unimplemented!()
5742 }
5743
5744 fn simplify(&self) -> Option<WindowFunctionSimplification> {
5745 if self.simplify {
5746 Some(Box::new(|_, _| Ok(col("result_column"))))
5747 } else {
5748 None
5749 }
5750 }
5751
5752 fn partition_evaluator(
5753 &self,
5754 _partition_evaluator_args: PartitionEvaluatorArgs,
5755 ) -> Result<Box<dyn PartitionEvaluator>> {
5756 unimplemented!("not needed for tests")
5757 }
5758
5759 fn field(&self, _field_args: WindowUDFFieldArgs) -> Result<FieldRef> {
5760 unimplemented!("not needed for tests")
5761 }
5762
5763 fn limit_effect(&self, _args: &[Arc<dyn PhysicalExpr>]) -> LimitEffect {
5764 LimitEffect::Unknown
5765 }
5766 }
5767 #[derive(Debug, PartialEq, Eq, Hash)]
5768 struct VolatileUdf {
5769 signature: Signature,
5770 }
5771
5772 impl VolatileUdf {
5773 pub fn new() -> Self {
5774 Self {
5775 signature: Signature::exact(vec![], Volatility::Volatile),
5776 }
5777 }
5778 }
5779 impl ScalarUDFImpl for VolatileUdf {
5780 fn name(&self) -> &str {
5781 "VolatileUdf"
5782 }
5783
5784 fn signature(&self) -> &Signature {
5785 &self.signature
5786 }
5787
5788 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
5789 Ok(DataType::Int16)
5790 }
5791
5792 fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
5793 panic!("dummy - not implemented")
5794 }
5795 }
5796
5797 #[test]
5798 fn test_optimize_volatile_conditions() {
5799 let fun = Arc::new(ScalarUDF::new_from_impl(VolatileUdf::new()));
5800 let rand = Expr::ScalarFunction(ScalarFunction::new_udf(fun, vec![]));
5801 {
5802 let expr = rand
5803 .clone()
5804 .eq(lit(0))
5805 .or(col("column1").eq(lit(2)).and(rand.clone().eq(lit(0))));
5806
5807 assert_eq!(simplify(expr.clone()), expr);
5808 }
5809
5810 {
5811 let expr = col("column1")
5812 .eq(lit(2))
5813 .or(col("column1").eq(lit(2)).and(rand.clone().eq(lit(0))));
5814
5815 assert_eq!(simplify(expr), col("column1").eq(lit(2)));
5816 }
5817
5818 {
5819 let expr = (col("column1").eq(lit(2)).and(rand.clone().eq(lit(0)))).or(col(
5820 "column1",
5821 )
5822 .eq(lit(2))
5823 .and(rand.clone().eq(lit(0))));
5824
5825 assert_eq!(
5826 simplify(expr),
5827 col("column1")
5828 .eq(lit(2))
5829 .and((rand.clone().eq(lit(0))).or(rand.clone().eq(lit(0))))
5830 );
5831 }
5832 }
5833
5834 #[test]
5835 fn simplify_fixed_size_binary_eq_lit() {
5836 let bytes = [1u8, 2, 3].as_slice();
5837
5838 let expr = col("c5").eq(lit(bytes));
5840
5841 let coerced = coerce(expr.clone());
5843 let schema = expr_test_schema();
5844 assert_eq!(
5845 coerced,
5846 col("c5")
5847 .cast_to(&DataType::Binary, schema.as_ref())
5848 .unwrap()
5849 .eq(lit(bytes))
5850 );
5851
5852 assert_eq!(
5854 simplify(coerced),
5855 col("c5").eq(Expr::Literal(
5856 ScalarValue::FixedSizeBinary(3, Some(bytes.to_vec()),),
5857 None
5858 ))
5859 );
5860 }
5861
5862 #[test]
5863 fn simplify_cast_literal() {
5864 let expr = Expr::Cast(Cast::new(Box::new(lit(123i32)), DataType::Int64));
5868 let expected = lit(123i64);
5869 assert_eq!(simplify(expr), expected);
5870
5871 let expr = Expr::Cast(Cast::new(
5874 Box::new(lit(1761630189642i64)),
5875 DataType::Timestamp(
5876 arrow::datatypes::TimeUnit::Nanosecond,
5877 Some("+00:00".into()),
5878 ),
5879 ));
5880 let result = simplify(expr);
5882 match result {
5883 Expr::Literal(ScalarValue::TimestampNanosecond(Some(val), tz), _) => {
5884 assert_eq!(val, 1761630189642i64);
5885 assert_eq!(tz.as_deref(), Some("+00:00"));
5886 }
5887 other => panic!("Expected TimestampNanosecond literal, got: {other:?}"),
5888 }
5889
5890 let expr = Expr::Cast(Cast::new(
5894 Box::new(lit("1761630189642")),
5895 DataType::Timestamp(
5896 arrow::datatypes::TimeUnit::Nanosecond,
5897 Some("+00:00".into()),
5898 ),
5899 ));
5900
5901 let schema = test_schema();
5903 let simplifier =
5904 ExprSimplifier::new(SimplifyContext::builder().with_schema(schema).build());
5905 let result = simplifier.simplify(expr);
5906 assert!(result.is_err(), "Expected error for invalid cast");
5907 let err_msg = result.unwrap_err().to_string();
5908 assert_contains!(err_msg, "Error parsing timestamp");
5909 }
5910
5911 fn if_not_null(expr: Expr, then: bool) -> Expr {
5912 Expr::Case(Case {
5913 expr: Some(expr.is_not_null().into()),
5914 when_then_expr: vec![(lit(true).into(), lit(then).into())],
5915 else_expr: None,
5916 })
5917 }
5918
5919 fn make_struct_cast_expr(source_fields: Fields, target_fields: Fields) -> Expr {
5925 let arrays: Vec<Arc<dyn Array>> = vec![
5927 Arc::new(Int32Array::from(vec![Some(1)])),
5928 Arc::new(Int32Array::from(vec![Some(2)])),
5929 ];
5930 let struct_array = StructArray::try_new(source_fields, arrays, None).unwrap();
5931
5932 Expr::Cast(Cast::new(
5933 Box::new(Expr::Literal(
5934 ScalarValue::Struct(Arc::new(struct_array)),
5935 None,
5936 )),
5937 DataType::Struct(target_fields),
5938 ))
5939 }
5940
5941 #[test]
5942 fn test_struct_cast_different_field_counts_not_foldable() {
5943 let source_fields = Fields::from(vec![
5947 Arc::new(Field::new("a", DataType::Int32, true)),
5948 Arc::new(Field::new("b", DataType::Int32, true)),
5949 ]);
5950
5951 let target_fields = Fields::from(vec![
5952 Arc::new(Field::new("x", DataType::Int32, true)),
5953 Arc::new(Field::new("y", DataType::Int32, true)),
5954 Arc::new(Field::new("z", DataType::Int32, true)),
5955 ]);
5956
5957 let expr = make_struct_cast_expr(source_fields, target_fields);
5958
5959 let simplifier = ExprSimplifier::new(
5960 SimplifyContext::builder()
5961 .with_schema(test_schema())
5962 .build(),
5963 );
5964
5965 let result = simplifier.simplify(expr.clone()).unwrap();
5967 assert_eq!(
5969 result, expr,
5970 "Struct cast with different field counts should remain unchanged (no const-folding)"
5971 );
5972 }
5973
5974 #[test]
5975 fn test_struct_cast_same_field_count_foldable() {
5976 let source_fields = Fields::from(vec![
5979 Arc::new(Field::new("a", DataType::Int32, true)),
5980 Arc::new(Field::new("b", DataType::Int32, true)),
5981 ]);
5982
5983 let target_fields = Fields::from(vec![
5984 Arc::new(Field::new("a", DataType::Int32, true)),
5985 Arc::new(Field::new("b", DataType::Int32, true)),
5986 ]);
5987
5988 let expr = make_struct_cast_expr(source_fields, target_fields);
5989
5990 let simplifier = ExprSimplifier::new(
5991 SimplifyContext::builder()
5992 .with_schema(test_schema())
5993 .build(),
5994 );
5995
5996 let result = simplifier.simplify(expr.clone()).unwrap();
5998 assert!(matches!(result, Expr::Literal(_, _)));
6000 assert_ne!(
6002 result, expr,
6003 "Struct cast with same field count should be simplified (not identical to input)"
6004 );
6005 }
6006
6007 #[test]
6008 fn test_struct_cast_different_names_same_count() {
6009 let source_fields = Fields::from(vec![
6013 Arc::new(Field::new("a", DataType::Int32, true)),
6014 Arc::new(Field::new("b", DataType::Int32, true)),
6015 ]);
6016
6017 let target_fields = Fields::from(vec![
6018 Arc::new(Field::new("x", DataType::Int32, true)),
6019 Arc::new(Field::new("y", DataType::Int32, true)),
6020 ]);
6021
6022 let expr = make_struct_cast_expr(source_fields, target_fields);
6023
6024 let simplifier = ExprSimplifier::new(
6025 SimplifyContext::builder()
6026 .with_schema(test_schema())
6027 .build(),
6028 );
6029
6030 let result = simplifier.simplify(expr.clone()).unwrap();
6032 assert_eq!(
6033 result, expr,
6034 "Struct cast with different names but same field count should not be simplified"
6035 );
6036 }
6037
6038 #[test]
6039 fn test_struct_cast_empty_array_not_foldable() {
6040 let source_fields = Fields::from(vec![
6045 Arc::new(Field::new("a", DataType::Int32, true)),
6046 Arc::new(Field::new("b", DataType::Int32, true)),
6047 ]);
6048
6049 let target_fields = Fields::from(vec![
6050 Arc::new(Field::new("a", DataType::Int32, true)),
6051 Arc::new(Field::new("b", DataType::Int32, true)),
6052 ]);
6053
6054 let arrays: Vec<Arc<dyn Array>> = vec![
6056 Arc::new(Int32Array::new(vec![].into(), None)),
6057 Arc::new(Int32Array::new(vec![].into(), None)),
6058 ];
6059 let struct_array = StructArray::try_new(source_fields, arrays, None).unwrap();
6060
6061 let expr = Expr::Cast(Cast::new(
6062 Box::new(Expr::Literal(
6063 ScalarValue::Struct(Arc::new(struct_array)),
6064 None,
6065 )),
6066 DataType::Struct(target_fields),
6067 ));
6068
6069 let simplifier = ExprSimplifier::new(
6070 SimplifyContext::builder()
6071 .with_schema(test_schema())
6072 .build(),
6073 );
6074
6075 let result = simplifier.simplify(expr.clone()).unwrap();
6077 assert_eq!(
6078 result, expr,
6079 "Struct cast with empty (0-row) array should remain unchanged"
6080 );
6081 }
6082}