1use std::collections::{BTreeMap, HashSet};
16use std::fmt::{self, Debug};
17use std::ops::Bound;
18use std::sync::LazyLock;
19
20use fixedbitset::FixedBitSet;
21use itertools::Itertools;
22use risingwave_common::catalog::Schema;
23use risingwave_common::types::{DataType, DefaultOrd, ScalarImpl};
24use risingwave_common::util::iter_util::ZipEqFast;
25use risingwave_common::util::scan_range::{ScanRange, is_full_range};
26
27use crate::TableCatalog;
28use crate::error::Result;
29use crate::expr::{
30 ExprDisplay, ExprImpl, ExprMutator, ExprRewriter, ExprType, ExprVisitor, FunctionCall,
31 InequalityInputPair, InputRef, collect_input_refs, column_self_eq_eliminate,
32 factorization_expr, fold_boolean_constant, push_down_not, to_conjunctions,
33 try_get_bool_constant,
34};
35use crate::utils::condition::cast_compare::{ResultForCmp, ResultForEq};
36
37#[derive(Debug, Clone, PartialEq, Eq, Hash)]
38pub struct Condition {
39 pub conjunctions: Vec<ExprImpl>,
41}
42
43impl IntoIterator for Condition {
44 type IntoIter = std::vec::IntoIter<ExprImpl>;
45 type Item = ExprImpl;
46
47 fn into_iter(self) -> Self::IntoIter {
48 self.conjunctions.into_iter()
49 }
50}
51
52impl fmt::Display for Condition {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 let mut conjunctions = self.conjunctions.iter();
55 if let Some(expr) = conjunctions.next() {
56 write!(f, "{:?}", expr)?;
57 }
58 if self.always_true() {
59 write!(f, "true")?;
60 } else {
61 for expr in conjunctions {
62 write!(f, " AND {:?}", expr)?;
63 }
64 }
65 Ok(())
66 }
67}
68
69impl Condition {
70 pub fn with_expr(expr: ExprImpl) -> Self {
71 let conjunctions = to_conjunctions(expr);
72
73 Self { conjunctions }.simplify()
74 }
75
76 pub fn true_cond() -> Self {
77 Self {
78 conjunctions: vec![],
79 }
80 }
81
82 pub fn false_cond() -> Self {
83 Self {
84 conjunctions: vec![ExprImpl::literal_bool(false)],
85 }
86 }
87
88 pub fn always_true(&self) -> bool {
89 self.conjunctions.is_empty()
90 }
91
92 pub fn always_false(&self) -> bool {
93 static FALSE: LazyLock<ExprImpl> = LazyLock::new(|| ExprImpl::literal_bool(false));
94 !self.conjunctions.is_empty() && self.conjunctions.contains(&*FALSE)
96 }
97
98 pub fn as_expr_unless_true(&self) -> Option<ExprImpl> {
100 if self.always_true() {
101 None
102 } else {
103 Some(self.clone().into())
104 }
105 }
106
107 #[must_use]
108 pub fn and(self, other: Self) -> Self {
109 let mut ret = self;
110 ret.conjunctions.extend(other.conjunctions);
111 ret.simplify()
112 }
113
114 #[must_use]
115 pub fn or(self, other: Self) -> Self {
116 let or_expr = ExprImpl::FunctionCall(
117 FunctionCall::new_unchecked(
118 ExprType::Or,
119 vec![self.into(), other.into()],
120 DataType::Boolean,
121 )
122 .into(),
123 );
124 let ret = Self::with_expr(or_expr);
125 ret.simplify()
126 }
127
128 #[must_use]
130 pub fn split(self, left_col_num: usize, right_col_num: usize) -> (Self, Self, Self) {
131 let left_bit_map = FixedBitSet::from_iter(0..left_col_num);
132 let right_bit_map = FixedBitSet::from_iter(left_col_num..left_col_num + right_col_num);
133
134 self.group_by::<_, 3>(|expr| {
135 let input_bits = expr.collect_input_refs(left_col_num + right_col_num);
136 if input_bits.is_subset(&left_bit_map) {
137 0
138 } else if input_bits.is_subset(&right_bit_map) {
139 1
140 } else {
141 2
142 }
143 })
144 .into_iter()
145 .next_tuple()
146 .unwrap()
147 }
148
149 pub fn collect_input_refs(&self, input_col_num: usize) -> FixedBitSet {
154 collect_input_refs(input_col_num, &self.conjunctions)
155 }
156
157 #[must_use]
171 pub fn split_by_input_col_nums(
172 self,
173 input_col_nums: &[usize],
174 only_eq: bool,
175 ) -> (BTreeMap<(usize, usize), Self>, Self) {
176 let mut bitmaps = Vec::with_capacity(input_col_nums.len());
177 let mut cols_seen = 0;
178 for cols in input_col_nums {
179 bitmaps.push(FixedBitSet::from_iter(cols_seen..cols_seen + cols));
180 cols_seen += cols;
181 }
182
183 let mut pairwise_conditions = BTreeMap::new();
184 let mut non_eq_join = vec![];
185
186 for expr in self.conjunctions {
187 let input_bits = expr.collect_input_refs(cols_seen);
188 let mut subset_indices = Vec::with_capacity(input_col_nums.len());
189 for (idx, bitmap) in bitmaps.iter().enumerate() {
190 if !input_bits.is_disjoint(bitmap) {
191 subset_indices.push(idx);
192 }
193 }
194 if subset_indices.len() != 2 || (only_eq && expr.as_eq_cond().is_none()) {
195 non_eq_join.push(expr);
196 } else {
197 let key = if subset_indices[0] < subset_indices[1] {
199 (subset_indices[0], subset_indices[1])
200 } else {
201 (subset_indices[1], subset_indices[0])
202 };
203 let e = pairwise_conditions
204 .entry(key)
205 .or_insert_with(Condition::true_cond);
206 e.conjunctions.push(expr);
207 }
208 }
209 (
210 pairwise_conditions,
211 Condition {
212 conjunctions: non_eq_join,
213 },
214 )
215 }
216
217 #[must_use]
218 pub fn split_eq_keys(
225 self,
226 left_col_num: usize,
227 right_col_num: usize,
228 ) -> (Vec<(InputRef, InputRef, bool)>, Self) {
229 let left_bit_map = FixedBitSet::from_iter(0..left_col_num);
230 let right_bit_map = FixedBitSet::from_iter(left_col_num..left_col_num + right_col_num);
231
232 let (mut eq_keys, mut others) = (vec![], vec![]);
233 self.conjunctions.into_iter().for_each(|expr| {
234 let input_bits = expr.collect_input_refs(left_col_num + right_col_num);
235 if input_bits.is_disjoint(&left_bit_map) || input_bits.is_disjoint(&right_bit_map) {
236 others.push(expr)
237 } else if let Some(columns) = expr.as_eq_cond() {
238 eq_keys.push((columns.0, columns.1, false));
239 } else if let Some(columns) = expr.as_is_not_distinct_from_cond() {
240 eq_keys.push((columns.0, columns.1, true));
241 } else {
242 others.push(expr)
243 }
244 });
245
246 (
247 eq_keys,
248 Condition {
249 conjunctions: others,
250 },
251 )
252 }
253
254 pub(crate) fn extract_inequality_keys(
265 &self,
266 left_col_num: usize,
267 right_col_num: usize,
268 ) -> Vec<(usize, InequalityInputPair)> {
269 let left_bit_map = FixedBitSet::from_iter(0..left_col_num);
270 let right_bit_map = FixedBitSet::from_iter(left_col_num..left_col_num + right_col_num);
271
272 self.conjunctions
273 .iter()
274 .enumerate()
275 .filter_map(|(conjunction_idx, expr)| {
276 let input_bits = expr.collect_input_refs(left_col_num + right_col_num);
277 if input_bits.is_disjoint(&left_bit_map) || input_bits.is_disjoint(&right_bit_map) {
278 return None;
279 }
280
281 let (left_input, op, right_input) = expr.as_comparison_cond()?;
283
284 if left_input.index() < left_col_num
287 && right_input.index() >= left_col_num
288 && right_input.index() < left_col_num + right_col_num
289 {
290 Some((
291 conjunction_idx,
292 InequalityInputPair::new(
293 left_input.index(),
294 right_input.index() - left_col_num, op,
296 ),
297 ))
298 } else {
299 None
300 }
301 })
302 .collect_vec()
303 }
304
305 #[must_use]
308 pub fn split_disjoint(self, columns: &FixedBitSet) -> (Self, Self) {
309 self.group_by::<_, 2>(|expr| {
310 let input_bits = expr.collect_input_refs(columns.len());
311 input_bits.is_disjoint(columns) as usize
312 })
313 .into_iter()
314 .next_tuple()
315 .unwrap()
316 }
317
318 #[must_use]
331 pub fn split_pushable(self, columns: &FixedBitSet) -> (Self, Self) {
332 let [kept, pushed] = self.group_by::<_, 2>(|expr| {
333 let input_bits = expr.collect_input_refs(columns.len());
334 let index = expr.is_pure() && input_bits.is_disjoint(columns);
335
336 index as usize
337 });
338
339 (kept, pushed)
340 }
341
342 fn disjunctions_to_scan_ranges(
345 table: &TableCatalog,
346 max_split_range_gap: u64,
347 disjunctions: Vec<ExprImpl>,
348 ) -> Result<Option<(Vec<ScanRange>, bool)>> {
349 let disjunctions_result: Result<Vec<(Vec<ScanRange>, Self)>> = disjunctions
350 .into_iter()
351 .map(|x| {
352 Condition {
353 conjunctions: to_conjunctions(x),
354 }
355 .split_to_scan_ranges(table, max_split_range_gap)
356 })
357 .collect();
358
359 let disjunctions_result = disjunctions_result?;
361
362 let all_equal = disjunctions_result
365 .iter()
366 .all(|(scan_ranges, other_condition)| {
367 other_condition.always_true()
368 && scan_ranges
369 .iter()
370 .all(|x| !x.eq_conds.is_empty() && is_full_range(&x.range))
371 });
372
373 if all_equal {
374 let scan_ranges = disjunctions_result
378 .into_iter()
379 .flat_map(|(scan_ranges, _)| scan_ranges)
380 .sorted_by(|a, b| a.eq_conds.len().cmp(&b.eq_conds.len()))
382 .collect_vec();
383 let mut non_overlap_scan_ranges: Vec<ScanRange> = vec![];
385 for s1 in &scan_ranges {
386 let overlap = non_overlap_scan_ranges.iter().any(|s2| {
387 #[expect(clippy::disallowed_methods)]
388 s1.eq_conds
389 .iter()
390 .zip(s2.eq_conds.iter())
391 .all(|(a, b)| a == b)
392 });
393 if !overlap {
397 non_overlap_scan_ranges.push(s1.clone());
398 }
399 }
400
401 Ok(Some((non_overlap_scan_ranges, false)))
402 } else {
403 let mut scan_ranges = vec![];
404 for (scan_ranges_chunk, _) in disjunctions_result {
405 if scan_ranges_chunk.is_empty() {
406 return Ok(None);
408 }
409
410 scan_ranges.extend(scan_ranges_chunk);
411 }
412
413 let order_types = table
414 .pk
415 .iter()
416 .cloned()
417 .map(|x| {
418 if x.order_type.is_descending() {
419 x.order_type.reverse()
420 } else {
421 x.order_type
422 }
423 })
424 .collect_vec();
425 scan_ranges.sort_by(|left, right| ScanRange::cmp_start(left, right, &order_types));
426
427 let mut output_scan_ranges: Vec<ScanRange> = vec![];
430 for mut scan_range in scan_ranges {
431 while let Some(last) = output_scan_ranges.last()
432 && ScanRange::is_overlap(last, &scan_range, &order_types)
433 {
434 let last = output_scan_ranges.pop().unwrap();
435 scan_range = last.union(scan_range, &order_types);
436 }
437 if scan_range.is_full_table_scan() {
438 return Ok(None);
439 }
440 output_scan_ranges.push(scan_range);
441 }
442
443 Ok(Some((output_scan_ranges, true)))
444 }
445 }
446
447 fn split_row_cmp_to_scan_ranges(
448 &self,
449 table: &TableCatalog,
450 ) -> Result<Option<(Vec<ScanRange>, Self)>> {
451 let (mut row_conjunctions, row_conjunctions_without_struct): (Vec<_>, Vec<_>) =
452 self.conjunctions.clone().into_iter().partition(|expr| {
453 if let Some(f) = expr.as_function_call() {
454 if let Some(left_input) = f.inputs().get(0)
455 && let Some(left_input) = left_input.as_function_call()
456 && matches!(left_input.func_type(), ExprType::Row)
457 && left_input.inputs().iter().all(|x| x.is_input_ref())
458 && let Some(right_input) = f.inputs().get(1)
459 && right_input.is_literal()
460 {
461 true
462 } else {
463 false
464 }
465 } else {
466 false
467 }
468 });
469 if row_conjunctions.len() == 1 {
474 let row_conjunction = row_conjunctions.pop().unwrap();
475 let row_left_inputs = row_conjunction
476 .as_function_call()
477 .unwrap()
478 .inputs()
479 .get(0)
480 .unwrap()
481 .as_function_call()
482 .unwrap()
483 .inputs();
484 let row_right_literal = row_conjunction
485 .as_function_call()
486 .unwrap()
487 .inputs()
488 .get(1)
489 .unwrap()
490 .as_literal()
491 .unwrap();
492 if !matches!(row_right_literal.get_data(), Some(ScalarImpl::Struct(_))) {
493 return Ok(None);
494 }
495 let row_right_literal_data = row_right_literal.get_data().clone().unwrap();
496 let right_iter = row_right_literal_data.as_struct().fields();
497 let func_type = row_conjunction.as_function_call().unwrap().func_type();
498 if row_left_inputs.len() > 1
499 && (matches!(func_type, ExprType::LessThan)
500 || matches!(func_type, ExprType::GreaterThan))
501 {
502 let mut pk_struct = vec![];
503 let mut order_type = None;
504 let mut all_added = true;
505 let mut iter = row_left_inputs.iter().zip_eq_fast(right_iter);
506 for column_order in &table.pk {
507 if let Some((left_expr, right_expr)) = iter.next() {
508 if left_expr.as_input_ref().unwrap().index != column_order.column_index {
509 all_added = false;
510 break;
511 }
512 if right_expr.is_none() {
514 all_added = false;
515 break;
516 }
517 match order_type {
518 Some(o) => {
519 if o != column_order.order_type {
520 all_added = false;
521 break;
522 }
523 }
524 None => order_type = Some(column_order.order_type),
525 }
526 pk_struct.push(right_expr.clone());
527 }
528 }
529 if pk_struct.len() < row_left_inputs.len() {
531 all_added = false;
532 }
533
534 if !pk_struct.is_empty() {
536 if !all_added {
537 let scan_range = ScanRange {
538 eq_conds: vec![],
539 range: match func_type {
540 ExprType::GreaterThan => {
541 (Bound::Included(pk_struct), Bound::Unbounded)
542 }
543 ExprType::LessThan => {
544 (Bound::Unbounded, Bound::Included(pk_struct))
545 }
546 _ => unreachable!(),
547 },
548 };
549 return Ok(Some((
550 vec![scan_range],
551 Condition {
552 conjunctions: self.conjunctions.clone(),
553 },
554 )));
555 } else {
556 let scan_range = ScanRange {
557 eq_conds: vec![],
558 range: match func_type {
559 ExprType::GreaterThan => {
560 (Bound::Excluded(pk_struct), Bound::Unbounded)
561 }
562 ExprType::LessThan => {
563 (Bound::Unbounded, Bound::Excluded(pk_struct))
564 }
565 _ => unreachable!(),
566 },
567 };
568 return Ok(Some((
569 vec![scan_range],
570 Condition {
571 conjunctions: row_conjunctions_without_struct,
572 },
573 )));
574 }
575 }
576 }
577 }
578 Ok(None)
579 }
580
581 pub fn get_eq_const_input_refs(&self) -> Vec<InputRef> {
583 self.conjunctions
584 .iter()
585 .filter_map(|expr| expr.as_eq_const().map(|(input_ref, _)| input_ref))
586 .collect()
587 }
588
589 pub fn split_to_scan_ranges(
591 self,
592 table: &TableCatalog,
593 max_split_range_gap: u64,
594 ) -> Result<(Vec<ScanRange>, Self)> {
595 fn false_cond() -> (Vec<ScanRange>, Condition) {
596 (vec![], Condition::false_cond())
597 }
598
599 if self.conjunctions.len() == 1
601 && let Some(disjunctions) = self.conjunctions[0].as_or_disjunctions()
602 {
603 if let Some((scan_ranges, maintaining_condition)) =
604 Self::disjunctions_to_scan_ranges(table, max_split_range_gap, disjunctions)?
605 {
606 if maintaining_condition {
607 return Ok((scan_ranges, self));
608 } else {
609 return Ok((scan_ranges, Condition::true_cond()));
610 }
611 } else {
612 return Ok((vec![], self));
613 }
614 }
615 if let Some((scan_ranges, other_condition)) = self.split_row_cmp_to_scan_ranges(table)? {
616 return Ok((scan_ranges, other_condition));
617 }
618
619 let mut groups = Self::classify_conjunctions_by_pk(self.conjunctions, table);
620 let mut other_conds = groups.pop().unwrap();
621
622 let mut scan_range = ScanRange::full_table_scan();
624 for i in 0..table.pk.len() {
625 let group = std::mem::take(&mut groups[i]);
626 if group.is_empty() {
627 groups.push(other_conds);
628 return Ok((
629 if scan_range.is_full_table_scan() {
630 vec![]
631 } else {
632 vec![scan_range]
633 },
634 Self {
635 conjunctions: groups[i + 1..].concat(),
636 },
637 ));
638 }
639
640 let Some((
641 lower_bound_conjunctions,
642 upper_bound_conjunctions,
643 eq_conds,
644 part_of_other_conds,
645 )) = Self::analyze_group(group)?
646 else {
647 return Ok(false_cond());
648 };
649 other_conds.extend(part_of_other_conds);
650
651 let lower_bound = Self::merge_lower_bound_conjunctions(lower_bound_conjunctions);
652 let upper_bound = Self::merge_upper_bound_conjunctions(upper_bound_conjunctions);
653
654 if Self::is_invalid_range(&lower_bound, &upper_bound) {
655 return Ok(false_cond());
656 }
657
658 match eq_conds.len() {
660 1 => {
661 let eq_conds =
662 Self::extract_eq_conds_within_range(eq_conds, &upper_bound, &lower_bound);
663 if eq_conds.is_empty() {
664 return Ok(false_cond());
665 }
666 scan_range.eq_conds.extend(eq_conds);
667 }
668 0 => {
669 let convert = |bound| match bound {
670 Bound::Included(l) => Bound::Included(vec![Some(l)]),
671 Bound::Excluded(l) => Bound::Excluded(vec![Some(l)]),
672 Bound::Unbounded => Bound::Unbounded,
673 };
674 scan_range.range = (convert(lower_bound), convert(upper_bound));
675 other_conds.extend(groups[i + 1..].iter().flatten().cloned());
676 break;
677 }
678 _ => {
679 let eq_conds =
686 Self::extract_eq_conds_within_range(eq_conds, &upper_bound, &lower_bound);
687 if eq_conds.is_empty() {
688 return Ok(false_cond());
689 }
690 other_conds.extend(groups[i + 1..].iter().flatten().cloned());
691 let scan_ranges = eq_conds
692 .into_iter()
693 .map(|lit| {
694 let mut scan_range = scan_range.clone();
695 scan_range.eq_conds.push(lit);
696 scan_range
697 })
698 .collect();
699 return Ok((
700 scan_ranges,
701 Self {
702 conjunctions: other_conds,
703 },
704 ));
705 }
706 }
707 }
708
709 Ok((
710 if scan_range.is_full_table_scan() {
711 vec![]
712 } else if table.columns[table.pk[0].column_index].data_type.is_int() {
713 match scan_range.split_small_range(max_split_range_gap) {
714 Some(scan_ranges) => scan_ranges,
715 None => vec![scan_range],
716 }
717 } else {
718 vec![scan_range]
719 },
720 Self {
721 conjunctions: other_conds,
722 },
723 ))
724 }
725
726 fn classify_conjunctions_by_pk(
730 conjunctions: Vec<ExprImpl>,
731 table: &TableCatalog,
732 ) -> Vec<Vec<ExprImpl>> {
733 let pk_cols_num = table.pk.len();
734 let cols_num = table.columns.len();
735
736 let mut col_idx_to_pk_idx = vec![None; cols_num];
737 table
738 .order_column_indices()
739 .enumerate()
740 .for_each(|(idx, pk_idx)| {
741 col_idx_to_pk_idx[pk_idx] = Some(idx);
742 });
743
744 let mut groups = vec![vec![]; pk_cols_num + 1];
745 for (key, group) in &conjunctions.into_iter().chunk_by(|expr| {
746 let input_bits = expr.collect_input_refs(cols_num);
747 if input_bits.count_ones(..) == 1 {
748 let col_idx = input_bits.ones().next().unwrap();
749 col_idx_to_pk_idx[col_idx].unwrap_or(pk_cols_num)
750 } else {
751 pk_cols_num
752 }
753 }) {
754 groups[key].extend(group);
755 }
756
757 groups
758 }
759
760 #[expect(clippy::type_complexity)]
768 fn analyze_group(
769 group: Vec<ExprImpl>,
770 ) -> Result<
771 Option<(
772 Vec<Bound<ScalarImpl>>,
773 Vec<Bound<ScalarImpl>>,
774 Vec<Option<ScalarImpl>>,
775 Vec<ExprImpl>,
776 )>,
777 > {
778 let mut lower_bound_conjunctions = vec![];
779 let mut upper_bound_conjunctions = vec![];
780 let mut eq_conds = vec![];
782 let mut other_conds = vec![];
783
784 'group_loop: for expr in group {
786 if let Some((input_ref, const_expr)) = expr.as_eq_const() {
787 let new_expr = if let Ok(expr) =
788 const_expr.clone().cast_implicit(&input_ref.data_type)
789 {
790 expr
791 } else {
792 match self::cast_compare::cast_compare_for_eq(const_expr, input_ref.data_type) {
793 Ok(ResultForEq::Success(expr)) => expr,
794 Ok(ResultForEq::NeverEqual) => {
795 return Ok(None);
796 }
797 Err(_) => {
798 other_conds.push(expr);
799 continue;
800 }
801 }
802 };
803
804 let Some(new_cond) = new_expr.fold_const()? else {
805 return Ok(None);
807 };
808 if Self::mutual_exclusive_with_eq_conds(&new_cond, &eq_conds) {
809 return Ok(None);
810 }
811 eq_conds = vec![Some(new_cond)];
812 } else if expr.as_is_null().is_some() {
813 if !eq_conds.is_empty() && eq_conds.into_iter().all(|l| l.is_some()) {
814 return Ok(None);
815 }
816 eq_conds = vec![None];
817 } else if let Some((input_ref, in_const_list)) = expr
818 .as_in_const_list()
819 .or_else(|| expr.as_some_eq_const_list())
820 {
821 let mut scalars = HashSet::new();
822 for const_expr in in_const_list {
823 let new_expr =
824 if let Ok(expr) = const_expr.clone().cast_implicit(&input_ref.data_type) {
825 expr
826 } else {
827 match self::cast_compare::cast_compare_for_eq(
828 const_expr,
829 input_ref.data_type.clone(),
830 ) {
831 Ok(ResultForEq::Success(expr)) => expr,
832 Ok(ResultForEq::NeverEqual) => {
833 continue;
834 }
835 Err(_) => {
836 other_conds.push(expr);
837 continue 'group_loop;
838 }
839 }
840 };
841
842 let value = new_expr.fold_const()?;
843 let Some(value) = value else {
844 continue;
845 };
846 scalars.insert(Some(value));
847 }
848 if scalars.is_empty() {
849 return Ok(None);
851 }
852 if !eq_conds.is_empty() {
853 scalars = scalars
854 .intersection(&HashSet::from_iter(eq_conds))
855 .cloned()
856 .collect();
857 if scalars.is_empty() {
858 return Ok(None);
859 }
860 }
861 eq_conds = scalars
863 .into_iter()
864 .sorted_by(DefaultOrd::default_cmp)
865 .collect();
866 } else if let Some((input_ref, op, const_expr)) = expr.as_comparison_const() {
867 let new_expr =
868 if let Ok(expr) = const_expr.clone().cast_implicit(&input_ref.data_type) {
869 expr
870 } else {
871 match self::cast_compare::cast_compare_for_cmp(
872 const_expr,
873 input_ref.data_type,
874 op,
875 ) {
876 Ok(ResultForCmp::Success(expr)) => expr,
877 _ => {
878 other_conds.push(expr);
879 continue;
880 }
881 }
882 };
883 let Some(value) = new_expr.fold_const()? else {
884 return Ok(None);
886 };
887 match op {
888 ExprType::LessThan => {
889 upper_bound_conjunctions.push(Bound::Excluded(value));
890 }
891 ExprType::LessThanOrEqual => {
892 upper_bound_conjunctions.push(Bound::Included(value));
893 }
894 ExprType::GreaterThan => {
895 lower_bound_conjunctions.push(Bound::Excluded(value));
896 }
897 ExprType::GreaterThanOrEqual => {
898 lower_bound_conjunctions.push(Bound::Included(value));
899 }
900 _ => unreachable!(),
901 }
902 } else {
903 other_conds.push(expr);
904 }
905 }
906 Ok(Some((
907 lower_bound_conjunctions,
908 upper_bound_conjunctions,
909 eq_conds,
910 other_conds,
911 )))
912 }
913
914 fn mutual_exclusive_with_eq_conds(
915 new_conds: &ScalarImpl,
916 eq_conds: &[Option<ScalarImpl>],
917 ) -> bool {
918 !eq_conds.is_empty()
919 && eq_conds.iter().all(|l| {
920 if let Some(l) = l {
921 l != new_conds
922 } else {
923 true
924 }
925 })
926 }
927
928 fn merge_lower_bound_conjunctions(lb: Vec<Bound<ScalarImpl>>) -> Bound<ScalarImpl> {
929 lb.into_iter()
930 .max_by(|a, b| {
931 match (a, b) {
933 (Bound::Included(_), Bound::Unbounded) => std::cmp::Ordering::Greater,
934 (Bound::Excluded(_), Bound::Unbounded) => std::cmp::Ordering::Greater,
935 (Bound::Unbounded, Bound::Included(_)) => std::cmp::Ordering::Less,
936 (Bound::Unbounded, Bound::Excluded(_)) => std::cmp::Ordering::Less,
937 (Bound::Unbounded, Bound::Unbounded) => std::cmp::Ordering::Equal,
938 (Bound::Included(a), Bound::Included(b)) => a.default_cmp(b),
939 (Bound::Excluded(a), Bound::Excluded(b)) => a.default_cmp(b),
940 (Bound::Included(a), Bound::Excluded(b)) => match a.default_cmp(b) {
942 std::cmp::Ordering::Equal => std::cmp::Ordering::Less,
943 other => other,
944 },
945 (Bound::Excluded(a), Bound::Included(b)) => match a.default_cmp(b) {
946 std::cmp::Ordering::Equal => std::cmp::Ordering::Greater,
947 other => other,
948 },
949 }
950 })
951 .unwrap_or(Bound::Unbounded)
952 }
953
954 fn merge_upper_bound_conjunctions(ub: Vec<Bound<ScalarImpl>>) -> Bound<ScalarImpl> {
955 ub.into_iter()
956 .min_by(|a, b| {
957 match (a, b) {
959 (Bound::Included(_), Bound::Unbounded) => std::cmp::Ordering::Less,
960 (Bound::Excluded(_), Bound::Unbounded) => std::cmp::Ordering::Less,
961 (Bound::Unbounded, Bound::Included(_)) => std::cmp::Ordering::Greater,
962 (Bound::Unbounded, Bound::Excluded(_)) => std::cmp::Ordering::Greater,
963 (Bound::Unbounded, Bound::Unbounded) => std::cmp::Ordering::Equal,
964 (Bound::Included(a), Bound::Included(b)) => a.default_cmp(b),
965 (Bound::Excluded(a), Bound::Excluded(b)) => a.default_cmp(b),
966 (Bound::Included(a), Bound::Excluded(b)) => match a.default_cmp(b) {
968 std::cmp::Ordering::Equal => std::cmp::Ordering::Greater,
969 other => other,
970 },
971 (Bound::Excluded(a), Bound::Included(b)) => match a.default_cmp(b) {
972 std::cmp::Ordering::Equal => std::cmp::Ordering::Less,
973 other => other,
974 },
975 }
976 })
977 .unwrap_or(Bound::Unbounded)
978 }
979
980 fn is_invalid_range(lower_bound: &Bound<ScalarImpl>, upper_bound: &Bound<ScalarImpl>) -> bool {
981 match (lower_bound, upper_bound) {
982 (Bound::Included(l), Bound::Included(u)) => l.default_cmp(u).is_gt(), (Bound::Included(l), Bound::Excluded(u)) => l.default_cmp(u).is_ge(), (Bound::Excluded(l), Bound::Included(u)) => l.default_cmp(u).is_ge(), (Bound::Excluded(l), Bound::Excluded(u)) => l.default_cmp(u).is_ge(), _ => false,
987 }
988 }
989
990 fn extract_eq_conds_within_range(
991 eq_conds: Vec<Option<ScalarImpl>>,
992 upper_bound: &Bound<ScalarImpl>,
993 lower_bound: &Bound<ScalarImpl>,
994 ) -> Vec<Option<ScalarImpl>> {
995 if Self::is_invalid_range(lower_bound, upper_bound) {
998 return vec![];
999 }
1000
1001 let is_extract_null = upper_bound == &Bound::Unbounded && lower_bound == &Bound::Unbounded;
1002
1003 eq_conds
1004 .into_iter()
1005 .filter(|cond| {
1006 if let Some(cond) = cond {
1007 match lower_bound {
1008 Bound::Included(val) => {
1009 if cond.default_cmp(val).is_lt() {
1010 return false;
1012 }
1013 }
1014 Bound::Excluded(val) => {
1015 if cond.default_cmp(val).is_le() {
1016 return false;
1018 }
1019 }
1020 Bound::Unbounded => {}
1021 }
1022 match upper_bound {
1023 Bound::Included(val) => {
1024 if cond.default_cmp(val).is_gt() {
1025 return false;
1027 }
1028 }
1029 Bound::Excluded(val) => {
1030 if cond.default_cmp(val).is_ge() {
1031 return false;
1033 }
1034 }
1035 Bound::Unbounded => {}
1036 }
1037 true
1038 } else {
1039 is_extract_null
1040 }
1041 })
1042 .collect()
1043 }
1044
1045 #[must_use]
1051 pub fn group_by<F, const N: usize>(self, f: F) -> [Self; N]
1052 where
1053 F: Fn(&ExprImpl) -> usize,
1054 {
1055 const EMPTY: Vec<ExprImpl> = vec![];
1056 let mut groups = [EMPTY; N];
1057 for (key, group) in &self.conjunctions.into_iter().chunk_by(|expr| {
1058 let i = f(expr);
1060 assert!(i < N);
1061 i
1062 }) {
1063 groups[key].extend(group);
1064 }
1065
1066 groups.map(|group| Condition {
1067 conjunctions: group,
1068 })
1069 }
1070
1071 #[must_use]
1072 pub fn rewrite_expr(self, rewriter: &mut (impl ExprRewriter + ?Sized)) -> Self {
1073 Self {
1074 conjunctions: self
1075 .conjunctions
1076 .into_iter()
1077 .map(|expr| rewriter.rewrite_expr(expr))
1078 .collect(),
1079 }
1080 .simplify()
1081 }
1082
1083 pub fn visit_expr<V: ExprVisitor + ?Sized>(&self, visitor: &mut V) {
1084 self.conjunctions
1085 .iter()
1086 .for_each(|expr| visitor.visit_expr(expr));
1087 }
1088
1089 pub fn visit_expr_mut(&mut self, mutator: &mut (impl ExprMutator + ?Sized)) {
1090 self.conjunctions
1091 .iter_mut()
1092 .for_each(|expr| mutator.visit_expr(expr))
1093 }
1094
1095 fn simplify(self) -> Self {
1098 let conjunctions: Vec<_> = self
1100 .conjunctions
1101 .into_iter()
1102 .map(push_down_not)
1103 .map(fold_boolean_constant)
1104 .map(column_self_eq_eliminate)
1105 .flat_map(to_conjunctions)
1106 .collect();
1107 let mut res: Vec<ExprImpl> = Vec::new();
1108 let mut visited: HashSet<ExprImpl> = HashSet::new();
1109 for expr in conjunctions {
1110 if !expr.has_subquery() {
1112 let results_of_factorization = factorization_expr(expr);
1113 res.extend(
1114 results_of_factorization
1115 .clone()
1116 .into_iter()
1117 .filter(|expr| !visited.contains(expr)),
1118 );
1119 visited.extend(results_of_factorization);
1120 } else {
1121 res.push(expr);
1123 }
1124 }
1125 res.retain(|expr| {
1127 if let Some(v) = try_get_bool_constant(expr)
1128 && v
1129 {
1130 false
1131 } else {
1132 true
1133 }
1134 });
1135 for expr in &mut res {
1137 if let Some(v) = try_get_bool_constant(expr)
1138 && !v
1139 {
1140 res.clear();
1141 res.push(ExprImpl::literal_bool(false));
1142 break;
1143 }
1144 }
1145 Self { conjunctions: res }
1146 }
1147}
1148
1149pub struct ConditionDisplay<'a> {
1150 pub condition: &'a Condition,
1151 pub input_schema: &'a Schema,
1152}
1153
1154impl ConditionDisplay<'_> {
1155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1156 if self.condition.always_true() {
1157 write!(f, "true")
1158 } else {
1159 write!(
1160 f,
1161 "{}",
1162 self.condition
1163 .conjunctions
1164 .iter()
1165 .format_with(" AND ", |expr, f| {
1166 f(&ExprDisplay {
1167 expr,
1168 input_schema: self.input_schema,
1169 })
1170 })
1171 )
1172 }
1173 }
1174}
1175
1176impl fmt::Display for ConditionDisplay<'_> {
1177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1178 self.fmt(f)
1179 }
1180}
1181
1182impl fmt::Debug for ConditionDisplay<'_> {
1183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1184 self.fmt(f)
1185 }
1186}
1187
1188mod cast_compare {
1193 use risingwave_common::types::DataType;
1194
1195 use crate::expr::{Expr, ExprImpl, ExprType};
1196
1197 enum ShrinkResult {
1198 OutUpperBound,
1199 OutLowerBound,
1200 InRange(ExprImpl),
1201 }
1202
1203 pub enum ResultForEq {
1204 Success(ExprImpl),
1205 NeverEqual,
1206 }
1207
1208 pub enum ResultForCmp {
1209 Success(ExprImpl),
1210 OutUpperBound,
1211 OutLowerBound,
1212 }
1213
1214 pub fn cast_compare_for_eq(const_expr: ExprImpl, target: DataType) -> Result<ResultForEq, ()> {
1215 match (const_expr.return_type(), &target) {
1216 (DataType::Int64, DataType::Int32)
1217 | (DataType::Int64, DataType::Int16)
1218 | (DataType::Int32, DataType::Int16) => match shrink_integral(const_expr, target)? {
1219 ShrinkResult::InRange(expr) => Ok(ResultForEq::Success(expr)),
1220 ShrinkResult::OutUpperBound | ShrinkResult::OutLowerBound => {
1221 Ok(ResultForEq::NeverEqual)
1222 }
1223 },
1224 _ => Err(()),
1225 }
1226 }
1227
1228 pub fn cast_compare_for_cmp(
1229 const_expr: ExprImpl,
1230 target: DataType,
1231 _op: ExprType,
1232 ) -> Result<ResultForCmp, ()> {
1233 match (const_expr.return_type(), &target) {
1234 (DataType::Int64, DataType::Int32)
1235 | (DataType::Int64, DataType::Int16)
1236 | (DataType::Int32, DataType::Int16) => match shrink_integral(const_expr, target)? {
1237 ShrinkResult::InRange(expr) => Ok(ResultForCmp::Success(expr)),
1238 ShrinkResult::OutUpperBound => Ok(ResultForCmp::OutUpperBound),
1239 ShrinkResult::OutLowerBound => Ok(ResultForCmp::OutLowerBound),
1240 },
1241 _ => Err(()),
1242 }
1243 }
1244
1245 fn shrink_integral(const_expr: ExprImpl, target: DataType) -> Result<ShrinkResult, ()> {
1246 let (upper_bound, lower_bound) = match (const_expr.return_type(), &target) {
1247 (DataType::Int64, DataType::Int32) => (i32::MAX as i64, i32::MIN as i64),
1248 (DataType::Int64, DataType::Int16) | (DataType::Int32, DataType::Int16) => {
1249 (i16::MAX as i64, i16::MIN as i64)
1250 }
1251 _ => unreachable!(),
1252 };
1253 match const_expr.fold_const().map_err(|_| ())? {
1254 Some(scalar) => {
1255 let value = scalar.as_integral();
1256 if value > upper_bound {
1257 Ok(ShrinkResult::OutUpperBound)
1258 } else if value < lower_bound {
1259 Ok(ShrinkResult::OutLowerBound)
1260 } else {
1261 Ok(ShrinkResult::InRange(
1262 const_expr.cast_explicit(&target).unwrap(),
1263 ))
1264 }
1265 }
1266 None => Ok(ShrinkResult::InRange(
1267 const_expr.cast_explicit(&target).unwrap(),
1268 )),
1269 }
1270 }
1271}
1272
1273#[cfg(test)]
1274mod tests {
1275 use rand::Rng;
1276
1277 use super::*;
1278
1279 #[test]
1280 fn test_split() {
1281 let left_col_num = 3;
1282 let right_col_num = 2;
1283
1284 let ty = DataType::Int32;
1285
1286 let mut rng = rand::rng();
1287
1288 let left: ExprImpl = FunctionCall::new(
1289 ExprType::LessThanOrEqual,
1290 vec![
1291 InputRef::new(rng.random_range(0..left_col_num), ty.clone()).into(),
1292 InputRef::new(rng.random_range(0..left_col_num), ty.clone()).into(),
1293 ],
1294 )
1295 .unwrap()
1296 .into();
1297
1298 let right: ExprImpl = FunctionCall::new(
1299 ExprType::LessThan,
1300 vec![
1301 InputRef::new(
1302 rng.random_range(left_col_num..left_col_num + right_col_num),
1303 ty.clone(),
1304 )
1305 .into(),
1306 InputRef::new(
1307 rng.random_range(left_col_num..left_col_num + right_col_num),
1308 ty.clone(),
1309 )
1310 .into(),
1311 ],
1312 )
1313 .unwrap()
1314 .into();
1315
1316 let other: ExprImpl = FunctionCall::new(
1317 ExprType::GreaterThan,
1318 vec![
1319 InputRef::new(rng.random_range(0..left_col_num), ty.clone()).into(),
1320 InputRef::new(
1321 rng.random_range(left_col_num..left_col_num + right_col_num),
1322 ty,
1323 )
1324 .into(),
1325 ],
1326 )
1327 .unwrap()
1328 .into();
1329
1330 let cond = Condition::with_expr(other.clone())
1331 .and(Condition::with_expr(right.clone()))
1332 .and(Condition::with_expr(left.clone()));
1333
1334 let res = cond.split(left_col_num, right_col_num);
1335
1336 assert_eq!(res.0.conjunctions, vec![left]);
1337 assert_eq!(res.1.conjunctions, vec![right]);
1338 assert_eq!(res.2.conjunctions, vec![other]);
1339 }
1340
1341 #[test]
1342 fn test_self_eq_eliminate() {
1343 let left_col_num = 3;
1344 let right_col_num = 2;
1345
1346 let ty = DataType::Int32;
1347
1348 let mut rng = rand::rng();
1349
1350 let x: ExprImpl = InputRef::new(rng.random_range(0..left_col_num), ty.clone()).into();
1351
1352 let left: ExprImpl = FunctionCall::new(ExprType::Equal, vec![x.clone(), x.clone()])
1353 .unwrap()
1354 .into();
1355
1356 let right: ExprImpl = FunctionCall::new(
1357 ExprType::LessThan,
1358 vec![
1359 InputRef::new(
1360 rng.random_range(left_col_num..left_col_num + right_col_num),
1361 ty.clone(),
1362 )
1363 .into(),
1364 InputRef::new(
1365 rng.random_range(left_col_num..left_col_num + right_col_num),
1366 ty.clone(),
1367 )
1368 .into(),
1369 ],
1370 )
1371 .unwrap()
1372 .into();
1373
1374 let other: ExprImpl = FunctionCall::new(
1375 ExprType::GreaterThan,
1376 vec![
1377 InputRef::new(rng.random_range(0..left_col_num), ty.clone()).into(),
1378 InputRef::new(
1379 rng.random_range(left_col_num..left_col_num + right_col_num),
1380 ty,
1381 )
1382 .into(),
1383 ],
1384 )
1385 .unwrap()
1386 .into();
1387
1388 let cond = Condition::with_expr(other.clone())
1389 .and(Condition::with_expr(right.clone()))
1390 .and(Condition::with_expr(left));
1391
1392 let res = cond.split(left_col_num, right_col_num);
1393
1394 let left_res = FunctionCall::new(ExprType::IsNotNull, vec![x])
1395 .unwrap()
1396 .into();
1397
1398 assert_eq!(res.0.conjunctions, vec![left_res]);
1399 assert_eq!(res.1.conjunctions, vec![right]);
1400 assert_eq!(res.2.conjunctions, vec![other]);
1401 }
1402}