1use datafusion_expr::logical_plan::MaterializedCtePlan;
30use std::collections::{HashMap, HashSet};
31use std::sync::Arc;
32
33use arrow::datatypes::DataType;
34use indexmap::IndexSet;
35use itertools::Itertools;
36use log::{Level, debug, log_enabled};
37
38use datafusion_common::instant::Instant;
39use datafusion_common::tree_node::{
40 Transformed, TransformedResult, TreeNode, TreeNodeRecursion,
41};
42use datafusion_common::{
43 Column, DFSchema, Result, ScalarValue, assert_eq_or_internal_err, internal_err,
44 plan_err, qualified_name,
45};
46use datafusion_expr::expr::WindowFunction;
47use datafusion_expr::expr_rewriter::replace_col;
48use datafusion_expr::logical_plan::{Join, JoinType, LogicalPlan};
49use datafusion_expr::utils::{
50 conjunction, expr_to_columns, split_conjunction, split_conjunction_owned,
51};
52use datafusion_expr::{
53 BinaryExpr, Distinct, EmptyRelation, Expr, Filter, Operator, Projection,
54 TableProviderFilterPushDown, and, or,
55};
56
57use crate::extract_leaf_expressions::is_pure_extraction_projection;
58use crate::optimizer::ApplyOrder;
59use crate::simplify_expressions::{reorder_predicates, simplify_predicates};
60use crate::utils::{
61 ColumnReference, has_all_column_refs, is_restrict_null_predicate, schema_columns,
62};
63use crate::{OptimizerConfig, OptimizerRule};
64use datafusion_expr::ExpressionPlacement;
65
66#[derive(Default, Debug)]
154pub struct PushDownFilter {}
155
156pub(crate) fn lr_is_preserved(join_type: JoinType) -> (bool, bool) {
181 match join_type {
182 JoinType::Inner => (true, true),
183 JoinType::Left => (true, false),
184 JoinType::Right => (false, true),
185 JoinType::Full => (false, false),
186 JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => (true, false),
191 JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => (false, true),
196 }
197}
198
199pub(crate) fn on_lr_is_preserved(join_type: JoinType) -> (bool, bool) {
201 join_type.on_lr_is_preserved()
202}
203
204#[derive(Debug)]
207struct ColumnChecker<'a> {
208 left_schema: &'a DFSchema,
210 left_columns: Option<HashSet<ColumnReference<'a>>>,
212 right_schema: &'a DFSchema,
214 right_columns: Option<HashSet<ColumnReference<'a>>>,
216}
217
218impl<'a> ColumnChecker<'a> {
219 fn new(left_schema: &'a DFSchema, right_schema: &'a DFSchema) -> Self {
220 Self {
221 left_schema,
222 left_columns: None,
223 right_schema,
224 right_columns: None,
225 }
226 }
227
228 fn is_left_only(&mut self, predicate: &Expr) -> bool {
230 if self.left_columns.is_none() {
231 self.left_columns = Some(schema_columns(self.left_schema));
232 }
233 has_all_column_refs(predicate, self.left_columns.as_ref().unwrap())
234 }
235
236 fn is_right_only(&mut self, predicate: &Expr) -> bool {
238 if self.right_columns.is_none() {
239 self.right_columns = Some(schema_columns(self.right_schema));
240 }
241 has_all_column_refs(predicate, self.right_columns.as_ref().unwrap())
242 }
243}
244
245fn can_evaluate_as_join_condition(predicate: &Expr) -> Result<bool> {
247 Ok(!predicate.exists(|expr| match expr {
248 Expr::Exists { .. }
249 | Expr::InSubquery(_)
250 | Expr::SetComparison(_)
251 | Expr::ScalarSubquery(_)
252 | Expr::OuterReferenceColumn(_, _)
253 | Expr::Unnest(_) => Ok(true),
254 Expr::Column(_)
255 | Expr::Literal(_, _)
256 | Expr::Placeholder(_)
257 | Expr::ScalarVariable(_, _)
258 | Expr::Alias(_)
259 | Expr::BinaryExpr(_)
260 | Expr::Like(_)
261 | Expr::SimilarTo(_)
262 | Expr::Not(_)
263 | Expr::IsNotNull(_)
264 | Expr::IsNull(_)
265 | Expr::IsTrue(_)
266 | Expr::IsFalse(_)
267 | Expr::IsUnknown(_)
268 | Expr::IsNotTrue(_)
269 | Expr::IsNotFalse(_)
270 | Expr::IsNotUnknown(_)
271 | Expr::Negative(_)
272 | Expr::Between(_)
273 | Expr::Case(_)
274 | Expr::Cast(_)
275 | Expr::TryCast(_)
276 | Expr::InList { .. }
277 | Expr::ScalarFunction(_)
278 | Expr::HigherOrderFunction(_)
279 | Expr::Lambda(_)
280 | Expr::LambdaVariable(_) => Ok(false),
281 #[expect(deprecated)]
283 Expr::AggregateFunction(_)
284 | Expr::WindowFunction(_)
285 | Expr::Wildcard { .. }
286 | Expr::GroupingSet(_) => internal_err!("Unsupported predicate type"),
287 })?)
288}
289
290fn extract_or_clauses_for_join<'a>(
324 filters: &'a [Expr],
325 schema_cols: &'a HashSet<ColumnReference>,
326) -> impl Iterator<Item = Expr> + 'a {
327 filters.iter().filter_map(move |expr| {
329 if let Expr::BinaryExpr(BinaryExpr {
330 left,
331 op: Operator::Or,
332 right,
333 }) = expr
334 {
335 let left_expr = extract_or_clause(left.as_ref(), schema_cols);
336 let right_expr = extract_or_clause(right.as_ref(), schema_cols);
337
338 if let (Some(left_expr), Some(right_expr)) = (left_expr, right_expr) {
340 return Some(or(left_expr, right_expr));
341 }
342 }
343 None
344 })
345}
346
347fn extract_or_clause(
359 expr: &Expr,
360 schema_columns: &HashSet<ColumnReference>,
361) -> Option<Expr> {
362 let mut predicate = None;
363
364 match expr {
365 Expr::BinaryExpr(BinaryExpr {
366 left: l_expr,
367 op: Operator::Or,
368 right: r_expr,
369 }) => {
370 let l_expr = extract_or_clause(l_expr, schema_columns);
371 let r_expr = extract_or_clause(r_expr, schema_columns);
372
373 if let (Some(l_expr), Some(r_expr)) = (l_expr, r_expr) {
374 predicate = Some(or(l_expr, r_expr));
375 }
376 }
377 Expr::BinaryExpr(BinaryExpr {
378 left: l_expr,
379 op: Operator::And,
380 right: r_expr,
381 }) => {
382 let l_expr = extract_or_clause(l_expr, schema_columns);
383 let r_expr = extract_or_clause(r_expr, schema_columns);
384
385 match (l_expr, r_expr) {
386 (Some(l_expr), Some(r_expr)) => {
387 predicate = Some(and(l_expr, r_expr));
388 }
389 (Some(l_expr), None) => {
390 predicate = Some(l_expr);
391 }
392 (None, Some(r_expr)) => {
393 predicate = Some(r_expr);
394 }
395 (None, None) => {
396 predicate = None;
397 }
398 }
399 }
400 _ => {
401 if has_all_column_refs(expr, schema_columns) {
402 predicate = Some(expr.clone());
403 }
404 }
405 }
406
407 predicate
408}
409
410fn push_down_all_join(
412 predicates: Vec<Expr>,
413 inferred_join_predicates: Vec<Expr>,
414 mut join: Join,
415 on_filter: Vec<Expr>,
416) -> Result<Transformed<LogicalPlan>> {
417 let is_inner_join = join.join_type == JoinType::Inner;
418 let (left_preserved, mut right_preserved) = lr_is_preserved(join.join_type);
420 let (on_left_preserved, mut on_right_preserved) = on_lr_is_preserved(join.join_type);
421
422 if join.null_aware {
435 right_preserved = false;
436 on_right_preserved = false;
437 }
438
439 let left_schema = join.left.schema();
444 let right_schema = join.right.schema();
445
446 let left_schema_columns = schema_columns(left_schema.as_ref());
447 let right_schema_columns = schema_columns(right_schema.as_ref());
448
449 let mut left_push = vec![];
450 let mut right_push = vec![];
451 let mut keep_predicates = vec![];
452 let mut join_conditions = vec![];
453 let mut checker = ColumnChecker::new(left_schema, right_schema);
454 for predicate in predicates {
455 if left_preserved && checker.is_left_only(&predicate) {
456 left_push.push(predicate);
457 } else if right_preserved && checker.is_right_only(&predicate) {
458 right_push.push(predicate);
459 } else if is_inner_join && can_evaluate_as_join_condition(&predicate)? {
460 join_conditions.push(predicate);
463 } else {
464 keep_predicates.push(predicate);
465 }
466 }
467
468 for predicate in inferred_join_predicates {
470 if checker.is_left_only(&predicate) {
471 left_push.push(predicate);
472 } else if checker.is_right_only(&predicate) {
473 right_push.push(predicate);
474 }
475 }
476
477 let mut on_filter_join_conditions = vec![];
478 for on in on_filter {
479 if on_left_preserved && checker.is_left_only(&on) {
480 left_push.push(on)
481 } else if on_right_preserved && checker.is_right_only(&on) {
482 right_push.push(on)
483 } else {
484 on_filter_join_conditions.push(on)
485 }
486 }
487
488 if left_preserved {
491 left_push.extend(extract_or_clauses_for_join(
492 &keep_predicates,
493 &left_schema_columns,
494 ));
495 left_push.extend(extract_or_clauses_for_join(
496 &join_conditions,
497 &left_schema_columns,
498 ));
499 }
500 if right_preserved {
501 right_push.extend(extract_or_clauses_for_join(
502 &keep_predicates,
503 &right_schema_columns,
504 ));
505 right_push.extend(extract_or_clauses_for_join(
506 &join_conditions,
507 &right_schema_columns,
508 ));
509 }
510
511 if on_left_preserved {
514 left_push.extend(extract_or_clauses_for_join(
515 &on_filter_join_conditions,
516 &left_schema_columns,
517 ));
518 }
519 if on_right_preserved {
520 right_push.extend(extract_or_clauses_for_join(
521 &on_filter_join_conditions,
522 &right_schema_columns,
523 ));
524 }
525
526 let join_conditions_empty = join_conditions.is_empty();
528 join_conditions.extend(on_filter_join_conditions);
529 join.filter = conjunction(join_conditions);
530
531 if join_conditions_empty && left_push.is_empty() && right_push.is_empty() {
532 return Ok(Transformed::no(with_filters(
534 keep_predicates,
535 LogicalPlan::Join(join),
536 )));
537 }
538
539 if let Some(predicate) = conjunction(left_push) {
540 join.left = Arc::new(LogicalPlan::Filter(Filter::new(predicate, join.left)));
541 }
542
543 if let Some(predicate) = conjunction(right_push) {
544 join.right = Arc::new(LogicalPlan::Filter(Filter::new(predicate, join.right)));
545 }
546
547 Ok(Transformed::yes(with_filters(
549 keep_predicates,
550 LogicalPlan::Join(join),
551 )))
552}
553
554fn push_down_join(
555 mut join: Join,
556 parent_predicate: Option<Expr>,
557) -> Result<Transformed<LogicalPlan>> {
558 let predicates = parent_predicate.map_or_else(Vec::new, split_conjunction_owned);
560
561 let on_filters = join
563 .filter
564 .take()
565 .map_or_else(Vec::new, split_conjunction_owned);
566
567 let inferred_join_predicates = with_debug_timing("infer_join_predicates", || {
569 infer_join_predicates(&join, &predicates, &on_filters)
570 })?;
571
572 if log_enabled!(Level::Debug) {
573 debug!(
574 "push_down_filter: join_type={:?}, parent_predicates={}, on_filters={}, inferred_join_predicates={}",
575 join.join_type,
576 predicates.len(),
577 on_filters.len(),
578 inferred_join_predicates.len()
579 );
580 }
581
582 if on_filters.is_empty()
583 && predicates.is_empty()
584 && inferred_join_predicates.is_empty()
585 {
586 return Ok(Transformed::no(LogicalPlan::Join(join)));
587 }
588
589 push_down_all_join(predicates, inferred_join_predicates, join, on_filters)
590}
591
592fn infer_join_predicates(
602 join: &Join,
603 predicates: &[Expr],
604 on_filters: &[Expr],
605) -> Result<Vec<Expr>> {
606 if join.null_aware {
614 return Ok(vec![]);
615 }
616
617 let join_col_keys = join
619 .on
620 .iter()
621 .filter_map(|(l, r)| {
622 let left_col = l.try_as_col()?;
623 let right_col = r.try_as_col()?;
624 Some((left_col, right_col))
625 })
626 .collect::<Vec<_>>();
627
628 let join_type = join.join_type;
629
630 let mut inferred_predicates = InferredPredicates::new(join_type);
631
632 infer_join_predicates_from_predicates(
633 &join_col_keys,
634 predicates,
635 &mut inferred_predicates,
636 )?;
637
638 infer_join_predicates_from_on_filters(
639 &join_col_keys,
640 join_type,
641 on_filters,
642 &mut inferred_predicates,
643 )?;
644
645 Ok(inferred_predicates.predicates)
646}
647
648struct InferredPredicates {
657 predicates: Vec<Expr>,
658 is_inner_join: bool,
659}
660
661impl InferredPredicates {
662 fn new(join_type: JoinType) -> Self {
663 Self {
664 predicates: vec![],
665 is_inner_join: join_type == JoinType::Inner,
666 }
667 }
668
669 fn try_build_predicate(
670 &mut self,
671 predicate: Expr,
672 replace_map: &HashMap<&Column, &Column>,
673 ) -> Result<()> {
674 if self.is_inner_join
675 || matches!(
676 is_restrict_null_predicate(
677 predicate.clone(),
678 replace_map.keys().copied()
679 ),
680 Ok(true)
681 )
682 {
683 self.predicates.push(replace_col(predicate, replace_map)?);
684 }
685
686 Ok(())
687 }
688}
689
690fn infer_join_predicates_from_predicates(
699 join_col_keys: &[(&Column, &Column)],
700 predicates: &[Expr],
701 inferred_predicates: &mut InferredPredicates,
702) -> Result<()> {
703 infer_join_predicates_impl::<true, true>(
704 join_col_keys,
705 predicates,
706 inferred_predicates,
707 )
708}
709
710fn infer_join_predicates_from_on_filters(
722 join_col_keys: &[(&Column, &Column)],
723 join_type: JoinType,
724 on_filters: &[Expr],
725 inferred_predicates: &mut InferredPredicates,
726) -> Result<()> {
727 match join_type {
728 JoinType::Full | JoinType::LeftAnti | JoinType::RightAnti => Ok(()),
729 JoinType::Inner => infer_join_predicates_impl::<true, true>(
730 join_col_keys,
731 on_filters,
732 inferred_predicates,
733 ),
734 JoinType::Left | JoinType::LeftSemi | JoinType::LeftMark => {
735 infer_join_predicates_impl::<true, false>(
736 join_col_keys,
737 on_filters,
738 inferred_predicates,
739 )
740 }
741 JoinType::Right | JoinType::RightSemi | JoinType::RightMark => {
742 infer_join_predicates_impl::<false, true>(
743 join_col_keys,
744 on_filters,
745 inferred_predicates,
746 )
747 }
748 }
749}
750
751fn infer_join_predicates_impl<
767 const ENABLE_LEFT_TO_RIGHT: bool,
768 const ENABLE_RIGHT_TO_LEFT: bool,
769>(
770 join_col_keys: &[(&Column, &Column)],
771 input_predicates: &[Expr],
772 inferred_predicates: &mut InferredPredicates,
773) -> Result<()> {
774 let mut join_cols_to_replace = HashMap::new();
775 for predicate in input_predicates {
776 join_cols_to_replace.clear();
777
778 for &col in &predicate.column_refs() {
779 for (l, r) in join_col_keys.iter() {
780 if ENABLE_LEFT_TO_RIGHT && col == *l {
781 join_cols_to_replace.insert(col, *r);
782 break;
783 }
784 if ENABLE_RIGHT_TO_LEFT && col == *r {
785 join_cols_to_replace.insert(col, *l);
786 break;
787 }
788 }
789 }
790 if join_cols_to_replace.is_empty() {
791 continue;
792 }
793
794 inferred_predicates
795 .try_build_predicate(predicate.clone(), &join_cols_to_replace)?;
796 }
797 Ok(())
798}
799
800fn references_any_column(expr: &Expr, names: &HashSet<String>) -> bool {
809 let mut found = false;
810 expr.apply(|e| {
811 let outer_refs = match e {
812 Expr::Column(col) => {
813 if names.contains(&col.name) {
814 found = true;
815 return Ok(TreeNodeRecursion::Stop);
816 }
817 return Ok(TreeNodeRecursion::Continue);
818 }
819 Expr::Exists(exists) => &exists.subquery.outer_ref_columns,
820 Expr::InSubquery(in_subquery) => &in_subquery.subquery.outer_ref_columns,
821 Expr::ScalarSubquery(subquery) => &subquery.outer_ref_columns,
822 Expr::SetComparison(set_comparison) => {
823 &set_comparison.subquery.outer_ref_columns
824 }
825 _ => return Ok(TreeNodeRecursion::Continue),
826 };
827 if outer_refs.iter().any(|outer_ref| {
828 matches!(outer_ref, Expr::OuterReferenceColumn(_, c) if names.contains(&c.name))
829 }) {
830 found = true;
831 return Ok(TreeNodeRecursion::Stop);
832 }
833 Ok(TreeNodeRecursion::Continue)
834 })
835 .expect("traversal is infallible");
836 found
837}
838
839impl OptimizerRule for PushDownFilter {
840 fn name(&self) -> &str {
841 "push_down_filter"
842 }
843
844 fn apply_order(&self) -> Option<ApplyOrder> {
845 Some(ApplyOrder::TopDown)
846 }
847
848 fn rewrite(
849 &self,
850 plan: LogicalPlan,
851 config: &dyn OptimizerConfig,
852 ) -> Result<Transformed<LogicalPlan>> {
853 let _ = config;
854 if let LogicalPlan::Join(join) = plan {
855 return push_down_join(join, None);
856 }
857
858 let LogicalPlan::Filter(mut filter) = plan else {
859 return Ok(Transformed::no(plan));
860 };
861
862 let predicate = split_conjunction_owned(filter.predicate.clone());
863 let old_predicate_len = predicate.len();
864 let new_predicates =
865 with_debug_timing("simplify_predicates", || simplify_predicates(predicate))?;
866
867 if log_enabled!(Level::Debug) {
868 debug!(
869 "push_down_filter: simplify_predicates old_count={}, new_count={}",
870 old_predicate_len,
871 new_predicates.len()
872 );
873 }
874
875 let (new_predicates, reorder_changed) = reorder_predicates(new_predicates);
879
880 let predicates_changed = if old_predicate_len != new_predicates.len() {
884 true
885 } else {
886 let old_predicates = split_conjunction(&filter.predicate);
887 new_predicates
888 .iter()
889 .zip(&old_predicates)
890 .any(|(new, old)| new != *old)
891 && {
892 let new_predicates: IndexSet<_> = new_predicates.iter().collect();
893 old_predicates
894 .iter()
895 .any(|old| !new_predicates.contains(old))
896 }
897 };
898 if predicates_changed || reorder_changed {
899 let Some(new_predicate) = conjunction(new_predicates) else {
900 return Ok(Transformed::yes(Arc::unwrap_or_clone(filter.input)));
903 };
904 filter.predicate = new_predicate;
905 }
906
907 if matches!(
910 filter.predicate,
911 Expr::Literal(ScalarValue::Boolean(Some(false)), _)
912 ) {
913 return Ok(Transformed::yes(LogicalPlan::EmptyRelation(
914 EmptyRelation {
915 produce_one_row: false,
916 schema: Arc::clone(filter.input.schema()),
917 },
918 )));
919 }
920
921 if filter.input.fetch()?.is_some() || filter.input.skip()?.is_some() {
925 return Ok(Transformed::new(
926 LogicalPlan::Filter(filter),
927 predicates_changed || reorder_changed,
928 TreeNodeRecursion::Continue,
929 ));
930 }
931
932 let result = match Arc::unwrap_or_clone(filter.input) {
933 LogicalPlan::Filter(mut child_filter) => {
934 let new_predicates: IndexSet<Expr> =
937 split_conjunction_owned(child_filter.predicate)
938 .into_iter()
939 .chain(split_conjunction_owned(filter.predicate))
940 .collect();
941
942 let Some(new_predicate) = conjunction(new_predicates) else {
943 return plan_err!("at least one expression exists");
944 };
945
946 child_filter.predicate = new_predicate;
947 self.rewrite(LogicalPlan::Filter(child_filter), config)
948 }
949 LogicalPlan::Repartition(mut repartition) => {
950 filter.input = repartition.input;
951 repartition.input = Arc::new(LogicalPlan::Filter(filter));
952 Ok(Transformed::yes(LogicalPlan::Repartition(repartition)))
953 }
954 LogicalPlan::Distinct(distinct) => {
955 let distinct = match distinct {
956 Distinct::All(input) => {
957 filter.input = input;
958 Distinct::All(Arc::new(LogicalPlan::Filter(filter)))
959 }
960 Distinct::On(mut distinct) => {
961 filter.input = distinct.input;
962 distinct.input = Arc::new(LogicalPlan::Filter(filter));
963 Distinct::On(distinct)
964 }
965 };
966
967 Ok(Transformed::yes(LogicalPlan::Distinct(distinct)))
968 }
969 LogicalPlan::Sort(mut sort) => {
970 filter.input = sort.input;
971 sort.input = Arc::new(LogicalPlan::Filter(filter));
972 Ok(Transformed::yes(LogicalPlan::Sort(sort)))
973 }
974 LogicalPlan::SubqueryAlias(mut subquery_alias) => {
975 let mut replace_map =
976 HashMap::with_capacity(subquery_alias.input.schema().fields().len());
977 for (i, (qualifier, field)) in
978 subquery_alias.input.schema().iter().enumerate()
979 {
980 let (sub_qualifier, sub_field) =
981 subquery_alias.schema.qualified_field(i);
982 replace_map.insert(
983 qualified_name(sub_qualifier, sub_field.name()),
984 Expr::Column(Column::new(qualifier.cloned(), field.name())),
985 );
986 }
987
988 filter.predicate = replace_cols_by_name(filter.predicate, &replace_map)?;
989 filter.input = subquery_alias.input;
990 subquery_alias.input = Arc::new(LogicalPlan::Filter(filter));
991 Ok(Transformed::yes(LogicalPlan::SubqueryAlias(subquery_alias)))
992 }
993 LogicalPlan::Projection(projection) => {
994 let predicates = split_conjunction_owned(filter.predicate.clone());
995 let (mut result, keep_predicates) =
996 rewrite_projection(predicates, projection)?;
997 if result.transformed {
998 result.data = with_filters(keep_predicates, result.data)
999 } else {
1000 filter.input = Arc::new(result.data);
1001 result.data = LogicalPlan::Filter(filter)
1002 }
1003
1004 Ok(result)
1005 }
1006 LogicalPlan::Unnest(mut unnest) => {
1007 let predicates = split_conjunction_owned(filter.predicate.clone());
1008 let mut non_unnest_predicates = vec![];
1009 let mut unnest_predicates = vec![];
1010 let mut unnest_struct_columns = vec![];
1011
1012 for idx in &unnest.struct_type_columns {
1013 let (sub_qualifier, field) =
1014 unnest.input.schema().qualified_field(*idx);
1015 if let DataType::Struct(children) = field.data_type() {
1016 let field_name = field.name();
1017 for child in children {
1018 let child_name = child.name();
1019 unnest_struct_columns.push(Column::new(
1020 sub_qualifier.cloned(),
1021 format!("{field_name}.{child_name}"),
1022 ));
1023 }
1024 }
1025 }
1026
1027 let mut accum: HashSet<Column> = HashSet::new();
1028 for predicate in predicates {
1029 accum.clear();
1031 expr_to_columns(&predicate, &mut accum)?;
1032
1033 let contains_list_columns =
1034 unnest.list_type_columns.iter().any(|(_, unnest_list)| {
1035 accum.contains(&unnest_list.output_column)
1036 });
1037 let contains_struct_columns =
1038 unnest_struct_columns.iter().any(|c| accum.contains(c));
1039
1040 if contains_list_columns || contains_struct_columns {
1041 unnest_predicates.push(predicate);
1042 } else {
1043 non_unnest_predicates.push(predicate);
1044 }
1045 }
1046
1047 if non_unnest_predicates.is_empty() {
1050 filter.input = Arc::new(LogicalPlan::Unnest(unnest));
1051 return Ok(Transformed::new(
1052 LogicalPlan::Filter(filter),
1053 predicates_changed || reorder_changed,
1054 TreeNodeRecursion::Continue,
1055 ));
1056 }
1057
1058 filter.predicate = conjunction(non_unnest_predicates).unwrap();
1068 filter.input = unnest.input;
1069 unnest.input = Arc::new(LogicalPlan::Filter(filter));
1073 Ok(Transformed::yes(with_filters(
1074 unnest_predicates,
1075 LogicalPlan::Unnest(unnest),
1076 )))
1077 }
1078 LogicalPlan::Union(mut union) => {
1079 let mut inputs = Vec::with_capacity(union.inputs.len());
1080 let mut replace_map = HashMap::with_capacity(union.schema.fields().len());
1081 for input in union.inputs {
1082 replace_map.clear();
1083 for (i, (qualifier, field)) in input.schema().iter().enumerate() {
1084 let (union_qualifier, union_field) =
1085 union.schema.qualified_field(i);
1086 replace_map.insert(
1087 qualified_name(union_qualifier, union_field.name()),
1088 Expr::Column(Column::new(qualifier.cloned(), field.name())),
1089 );
1090 }
1091
1092 let push_predicate =
1093 replace_cols_by_name(filter.predicate.clone(), &replace_map)?;
1094 inputs.push(Arc::new(LogicalPlan::Filter(Filter::new(
1095 push_predicate,
1096 input,
1097 ))))
1098 }
1099
1100 union.inputs = inputs;
1101 Ok(Transformed::yes(LogicalPlan::Union(union)))
1102 }
1103 LogicalPlan::Aggregate(mut agg) => {
1104 let non_volatile_group_exprs: Vec<Expr> = agg
1109 .group_expr
1110 .iter()
1111 .filter(|expr| !expr.is_volatile())
1112 .cloned()
1113 .collect();
1114 let group_expr_columns = expr_columns(&non_volatile_group_exprs);
1115
1116 let mut replace_map = HashMap::with_capacity(agg.group_expr.len());
1125 for expr in &agg.group_expr {
1126 let (relation, name) = expr.qualified_name();
1127 replace_map.insert(Column::new(relation, name), unalias(expr));
1128 }
1129
1130 let predicates = split_conjunction_owned(filter.predicate);
1131 let mut keep_predicates = vec![];
1132 let mut push_predicates = vec![];
1133 for expr in predicates {
1134 let cols = expr.column_refs();
1135 if cols.iter().all(|c| group_expr_columns.contains(c)) {
1136 push_predicates.push(replace_cols_by_column(expr, &replace_map)?);
1137 } else {
1138 keep_predicates.push(expr);
1139 }
1140 }
1141
1142 let result = if let Some(predicate) = conjunction(push_predicates) {
1144 filter.predicate = predicate;
1145 filter.input = agg.input;
1146 agg.input = Arc::new(LogicalPlan::Filter(filter));
1147 Transformed::yes(LogicalPlan::Aggregate(agg))
1148 } else {
1149 Transformed::no(LogicalPlan::Aggregate(agg))
1150 };
1151
1152 result.map_data(|plan| Ok(with_filters(keep_predicates, plan)))
1154 }
1155 LogicalPlan::Window(mut window) => {
1166 #[allow(clippy::allow_attributes, clippy::mutable_key_type)]
1173 fn extract_partition_keys(func: &WindowFunction) -> HashSet<&Expr> {
1174 func.params.partition_by.iter().collect()
1175 }
1176
1177 #[allow(clippy::allow_attributes, clippy::mutable_key_type)]
1179 let potential_partition_keys = window
1180 .window_expr
1181 .iter()
1182 .map(|e| {
1183 match e {
1184 Expr::WindowFunction(window_func) => {
1185 extract_partition_keys(window_func)
1186 }
1187 Expr::Alias(alias) => {
1188 if let Expr::WindowFunction(window_func) =
1189 alias.expr.as_ref()
1190 {
1191 extract_partition_keys(window_func)
1192 } else {
1193 unreachable!()
1195 }
1196 }
1197 _ => {
1198 unreachable!()
1200 }
1201 }
1202 })
1203 .reduce(|a, b| &a & &b)
1206 .unwrap_or_default();
1207
1208 let predicates = split_conjunction_owned(filter.predicate);
1209 let mut keep_predicates = vec![];
1210 let mut push_predicates = vec![];
1211 for expr in predicates {
1212 if !expr.is_volatile()
1215 && reads_only_partition_keys(&expr, &potential_partition_keys)?
1216 {
1217 push_predicates.push(expr);
1218 } else {
1219 keep_predicates.push(expr);
1220 }
1221 }
1222
1223 let result = if let Some(predicate) = conjunction(push_predicates) {
1232 filter.predicate = predicate;
1233 filter.input = window.input;
1234 window.input = Arc::new(LogicalPlan::Filter(filter));
1235 Transformed::yes(LogicalPlan::Window(window))
1236 } else {
1237 Transformed::no(LogicalPlan::Window(window))
1238 };
1239
1240 result.map_data(|plan| Ok(with_filters(keep_predicates, plan)))
1242 }
1243 LogicalPlan::Join(join) => push_down_join(join, Some(filter.predicate)),
1244 LogicalPlan::AsOfJoin(mut join) => {
1260 let (push_predicates, keep_predicates): (Vec<_>, Vec<_>) =
1265 split_conjunction_owned(filter.predicate)
1266 .into_iter()
1267 .partition(|predicate| {
1268 !predicate.is_volatile()
1269 && predicate.column_refs().iter().all(|column| {
1270 join.left.schema().is_column_from_schema(column)
1271 })
1272 });
1273
1274 let key_replacements = join
1279 .on
1280 .iter()
1281 .filter_map(|(left, right)| {
1282 Some((left.try_as_col()?, right.try_as_col()?))
1283 })
1284 .collect::<HashMap<_, _>>();
1285 let mut right_predicates = Vec::new();
1286 for predicate in &push_predicates {
1287 let columns = predicate.column_refs();
1288 if !columns.is_empty()
1289 && columns
1290 .iter()
1291 .all(|column| key_replacements.contains_key(column))
1292 {
1293 right_predicates
1294 .push(replace_col(predicate.clone(), &key_replacements)?);
1295 }
1296 }
1297 if let Some(predicate) = conjunction(right_predicates) {
1298 join.right =
1299 Arc::new(LogicalPlan::Filter(Filter::new(predicate, join.right)));
1300 }
1301
1302 let result = if let Some(predicate) = conjunction(push_predicates) {
1303 filter.predicate = predicate;
1304 filter.input = join.left;
1305 join.left = Arc::new(LogicalPlan::Filter(filter));
1306 Transformed::yes(LogicalPlan::AsOfJoin(join))
1307 } else {
1308 Transformed::no(LogicalPlan::AsOfJoin(join))
1309 };
1310
1311 result.map_data(|plan| Ok(with_filters(keep_predicates, plan)))
1312 }
1313 LogicalPlan::TableScan(mut scan) => {
1314 let filter_predicates = split_conjunction(&filter.predicate);
1315 let (subquery_filters, pushdown_candidates): (Vec<&Expr>, Vec<&Expr>) =
1319 filter_predicates
1320 .into_iter()
1321 .partition(|pred| pred.contains_scalar_subquery());
1322
1323 let (volatile_filters, non_volatile_filters): (Vec<&Expr>, Vec<&Expr>) =
1324 pushdown_candidates
1325 .into_iter()
1326 .partition(|pred| pred.is_volatile());
1327
1328 let supported_filters = scan
1330 .source
1331 .supports_filters_pushdown(non_volatile_filters.as_slice())?;
1332 assert_eq_or_internal_err!(
1333 non_volatile_filters.len(),
1334 supported_filters.len(),
1335 "Vec returned length: {} from supports_filters_pushdown is not the same size as the filters passed, which length is: {}",
1336 supported_filters.len(),
1337 non_volatile_filters.len()
1338 );
1339
1340 if supported_filters
1341 .iter()
1342 .all(|res| res == &TableProviderFilterPushDown::Unsupported)
1343 {
1344 filter.input = Arc::new(LogicalPlan::TableScan(scan));
1345 return Ok(Transformed::new(
1346 LogicalPlan::Filter(filter),
1347 predicates_changed || reorder_changed,
1348 TreeNodeRecursion::Continue,
1349 ));
1350 }
1351
1352 let zip = non_volatile_filters.iter().zip(supported_filters.iter());
1354
1355 let new_scan_filters = zip
1356 .clone()
1357 .filter(|(_, res)| *res != &TableProviderFilterPushDown::Unsupported)
1358 .map(|(&pred, _)| pred);
1359
1360 let new_scan_filters: Vec<Expr> = scan
1362 .filters
1363 .iter()
1364 .chain(new_scan_filters)
1365 .unique()
1366 .cloned()
1367 .collect();
1368
1369 if supported_filters
1370 .iter()
1371 .all(|res| res == &TableProviderFilterPushDown::Inexact)
1372 && scan.filters == new_scan_filters
1373 {
1374 filter.input = Arc::new(LogicalPlan::TableScan(scan));
1375 return Ok(Transformed::new(
1376 LogicalPlan::Filter(filter),
1377 predicates_changed || reorder_changed,
1378 TreeNodeRecursion::Continue,
1379 ));
1380 } else {
1381 scan.filters = new_scan_filters;
1382 }
1383
1384 let new_predicate: Vec<Expr> = zip
1387 .filter(|(_, res)| *res != &TableProviderFilterPushDown::Exact)
1388 .map(|(&pred, _)| pred)
1389 .chain(volatile_filters)
1390 .chain(subquery_filters)
1391 .cloned()
1392 .collect();
1393
1394 Ok(Transformed::yes(with_filters(
1395 new_predicate,
1396 LogicalPlan::TableScan(scan),
1397 )))
1398 }
1399 LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(mut cte)) => {
1400 cte.continuation = Arc::new(LogicalPlan::Filter(Filter::new(
1404 filter.predicate,
1405 cte.continuation,
1406 )));
1407 Ok(Transformed::yes(LogicalPlan::MaterializedCte(
1408 MaterializedCtePlan::Cte(cte),
1409 )))
1410 }
1411 scan @ LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => {
1413 filter.input = Arc::new(scan);
1414 Ok(Transformed::no(LogicalPlan::Filter(filter)))
1415 }
1416 LogicalPlan::Extension(extension_plan) => {
1417 if extension_plan.node.inputs().is_empty() {
1420 filter.input = Arc::new(LogicalPlan::Extension(extension_plan));
1421 return Ok(Transformed::new(
1422 LogicalPlan::Filter(filter),
1423 predicates_changed || reorder_changed,
1424 TreeNodeRecursion::Continue,
1425 ));
1426 }
1427 let prevent_cols =
1428 extension_plan.node.prevent_predicate_push_down_columns();
1429
1430 let predicate_push_or_keep: Vec<bool> =
1434 split_conjunction(&filter.predicate)
1435 .iter()
1436 .map(|expr| !references_any_column(expr, &prevent_cols))
1437 .collect();
1438
1439 if predicate_push_or_keep.iter().all(|&x| !x) {
1441 filter.input = Arc::new(LogicalPlan::Extension(extension_plan));
1442 return Ok(Transformed::new(
1443 LogicalPlan::Filter(filter),
1444 predicates_changed || reorder_changed,
1445 TreeNodeRecursion::Continue,
1446 ));
1447 }
1448
1449 let mut keep_predicates = vec![];
1451 let mut push_predicates = vec![];
1452 for (push, expr) in predicate_push_or_keep
1453 .into_iter()
1454 .zip(split_conjunction_owned(filter.predicate))
1455 {
1456 if !push {
1457 keep_predicates.push(expr);
1458 } else {
1459 push_predicates.push(expr);
1460 }
1461 }
1462
1463 let predicate = conjunction(push_predicates).unwrap();
1465 let new_children = extension_plan
1466 .node
1467 .inputs()
1468 .into_iter()
1469 .map(|child| {
1470 LogicalPlan::Filter(Filter::new(
1471 predicate.clone(),
1472 Arc::new(child.clone()),
1473 ))
1474 })
1475 .collect();
1476
1477 let extension = LogicalPlan::Extension(extension_plan);
1479 let new_plan =
1480 extension.with_new_exprs(extension.expressions(), new_children)?;
1481 Ok(Transformed::yes(with_filters(keep_predicates, new_plan)))
1482 }
1483 child => {
1484 filter.input = Arc::new(child);
1485 Ok(Transformed::no(LogicalPlan::Filter(filter)))
1486 }
1487 };
1488 result.map(|mut result| {
1489 result.transformed |= predicates_changed || reorder_changed;
1490 result
1491 })
1492 }
1493}
1494
1495fn rewrite_projection(
1523 predicates: Vec<Expr>,
1524 mut projection: Projection,
1525) -> Result<(Transformed<LogicalPlan>, Vec<Expr>)> {
1526 if is_pure_extraction_projection(&projection.expr) {
1541 return Ok((
1542 Transformed::no(LogicalPlan::Projection(projection)),
1543 predicates,
1544 ));
1545 }
1546
1547 let (non_pushable_map, pushable_map): (HashMap<_, _>, HashMap<_, _>) = projection
1559 .schema
1560 .iter()
1561 .zip(projection.expr.iter())
1562 .map(|((qualifier, field), expr)| {
1563 (Column::new(qualifier.cloned(), field.name()), unalias(expr))
1564 })
1565 .partition(|(_, value)| {
1566 value.is_volatile()
1567 || value.placement() == ExpressionPlacement::MoveTowardsLeafNodes
1568 });
1569
1570 let mut push_predicates = vec![];
1571 let mut keep_predicates = vec![];
1572 for expr in predicates {
1573 if contains_column(&expr, &non_pushable_map) {
1574 keep_predicates.push(expr);
1575 } else {
1576 push_predicates.push(expr);
1577 }
1578 }
1579
1580 let projection = if let Some(expr) = conjunction(push_predicates) {
1581 projection.input = Arc::new(LogicalPlan::Filter(Filter::new(
1584 replace_cols_by_column(expr, &pushable_map)?,
1585 projection.input,
1586 )));
1587
1588 Transformed::yes(LogicalPlan::Projection(projection))
1589 } else {
1590 Transformed::no(LogicalPlan::Projection(projection))
1591 };
1592
1593 Ok((projection, keep_predicates))
1594}
1595
1596#[deprecated(since = "55.0.0", note = "Use `Filter::try_new` instead")]
1600pub fn make_filter(predicate: Expr, input: Arc<LogicalPlan>) -> Result<LogicalPlan> {
1601 Filter::try_new(predicate, input).map(LogicalPlan::Filter)
1602}
1603
1604impl PushDownFilter {
1605 #[expect(missing_docs)]
1606 pub fn new() -> Self {
1607 Self {}
1608 }
1609}
1610
1611fn with_debug_timing<T, F>(label: &'static str, f: F) -> Result<T>
1612where
1613 F: FnOnce() -> Result<T>,
1614{
1615 if !log_enabled!(Level::Debug) {
1616 return f();
1617 }
1618 let start = Instant::now();
1619 let result = f();
1620 debug!(
1621 "push_down_filter_timing: section={label}, elapsed_us={}",
1622 start.elapsed().as_micros()
1623 );
1624 result
1625}
1626
1627pub fn replace_cols_by_name(
1629 e: Expr,
1630 replace_map: &HashMap<String, impl AsRef<Expr>>,
1631) -> Result<Expr> {
1632 e.transform_up(|expr| {
1633 if let Expr::Column(c) = &expr
1634 && let Some(new_expr) = replace_map.get(&c.flat_name())
1635 {
1636 Ok(Transformed::yes(new_expr.as_ref().clone()))
1637 } else {
1638 Ok(Transformed::no(expr))
1639 }
1640 })
1641 .data()
1642}
1643
1644fn replace_cols_by_column(
1651 e: Expr,
1652 replace_map: &HashMap<Column, impl AsRef<Expr>>,
1653) -> Result<Expr> {
1654 e.transform_up(|expr| {
1655 if let Expr::Column(c) = &expr
1656 && let Some(new_expr) = replace_map.get(c)
1657 {
1658 Ok(Transformed::yes(new_expr.as_ref().clone()))
1659 } else {
1660 Ok(Transformed::no(expr))
1661 }
1662 })
1663 .data()
1664}
1665
1666fn unalias(expr: &Expr) -> &Expr {
1668 if let Expr::Alias(alias) = expr {
1669 unalias(&alias.expr)
1670 } else {
1671 expr
1672 }
1673}
1674
1675fn contains_column<T>(e: &Expr, check_map: &HashMap<Column, T>) -> bool {
1677 e.exists(|expr| Ok(matches!(expr, Expr::Column(c) if check_map.contains_key(c))))
1678 .unwrap()
1679}
1680
1681fn with_filters(predicates: Vec<Expr>, plan: LogicalPlan) -> LogicalPlan {
1682 if let Some(predicate) = conjunction(predicates) {
1683 LogicalPlan::Filter(Filter::new(predicate, Arc::new(plan)))
1684 } else {
1685 plan
1686 }
1687}
1688
1689#[allow(clippy::allow_attributes, clippy::mutable_key_type)] fn reads_only_partition_keys(
1705 expr: &Expr,
1706 partition_keys: &HashSet<&Expr>,
1707) -> Result<bool> {
1708 let mut reads_something_else = false;
1709 expr.apply(|node| {
1710 Ok(if partition_keys.contains(&node) {
1711 TreeNodeRecursion::Jump
1713 } else if reads_beyond_this_node(node) {
1714 reads_something_else = true;
1715 TreeNodeRecursion::Stop
1716 } else {
1717 TreeNodeRecursion::Continue
1718 })
1719 })?;
1720 Ok(!reads_something_else)
1721}
1722
1723fn reads_beyond_this_node(node: &Expr) -> bool {
1727 matches!(
1728 node,
1729 Expr::Column(_)
1730 | Expr::OuterReferenceColumn(..)
1731 | Expr::ScalarSubquery(_)
1732 | Expr::Exists(_)
1733 | Expr::InSubquery(_)
1734 | Expr::SetComparison(_)
1735 )
1736}
1737
1738fn expr_columns(exprs: &[Expr]) -> HashSet<Column> {
1739 exprs
1740 .iter()
1741 .map(|expr| {
1742 let (relation, name) = expr.qualified_name();
1743 Column::new(relation, name)
1744 })
1745 .collect()
1746}
1747
1748#[cfg(test)]
1749mod tests {
1750 use std::cmp::Ordering;
1751 use std::fmt::{Debug, Formatter};
1752
1753 use arrow::datatypes::{Field, Metadata, Schema, SchemaRef};
1754 use async_trait::async_trait;
1755
1756 use datafusion_common::{DFSchemaRef, DataFusionError, ScalarValue, Spans};
1757 use datafusion_expr::expr::{ScalarFunction, SetComparison, SetQuantifier};
1758 use datafusion_expr::logical_plan::table_scan;
1759 use datafusion_expr::{
1760 ColumnarValue, ExprFunctionExt, Extension, LogicalPlanBuilder,
1761 ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, Subquery, TableScan,
1762 TableSource, TableType, UserDefinedLogicalNodeCore, Volatility,
1763 WindowFunctionDefinition, col, exists, in_list, in_subquery, lit, out_ref_col,
1764 };
1765
1766 use crate::OptimizerContext;
1767 use crate::assert_optimized_plan_eq_snapshot;
1768 use crate::optimizer::Optimizer;
1769 use crate::simplify_expressions::SimplifyExpressions;
1770 use crate::test::udfs::leaf_udf_expr;
1771 use crate::test::*;
1772 use datafusion_expr::test::function_stub::{count, sum};
1773 use insta::assert_snapshot;
1774
1775 use super::*;
1776
1777 fn observe(_plan: &LogicalPlan, _rule: &dyn OptimizerRule) {}
1778
1779 macro_rules! assert_optimized_plan_equal {
1780 (
1781 $plan:expr,
1782 @ $expected:literal $(,)?
1783 ) => {{
1784 let optimizer_ctx = OptimizerContext::new().with_max_passes(1);
1785 let rules: Vec<Arc<dyn crate::OptimizerRule + Send + Sync>> = vec![Arc::new(PushDownFilter::new())];
1786 assert_optimized_plan_eq_snapshot!(
1787 optimizer_ctx,
1788 rules,
1789 $plan,
1790 @ $expected,
1791 )
1792 }};
1793 }
1794
1795 macro_rules! assert_optimized_plan_eq_with_rewrite_predicate {
1796 (
1797 $plan:expr,
1798 @ $expected:literal $(,)?
1799 ) => {{
1800 let optimizer = Optimizer::with_rules(vec![
1801 Arc::new(SimplifyExpressions::new()),
1802 Arc::new(PushDownFilter::new()),
1803 ]);
1804 let optimized_plan = optimizer.optimize($plan, &OptimizerContext::new(), observe)?;
1805 assert_snapshot!(optimized_plan, @ $expected);
1806 Ok::<(), DataFusionError>(())
1807 }};
1808 }
1809
1810 macro_rules! assert_plan_not_transformed {
1813 ($plan:expr) => {{
1814 let transformed = PushDownFilter::new()
1815 .rewrite($plan, &OptimizerContext::new())
1816 .expect("failed to optimize plan");
1817 assert!(!transformed.transformed);
1818 }};
1819 }
1820
1821 #[test]
1822 fn filter_before_projection() -> Result<()> {
1823 let table_scan = test_table_scan()?;
1824 let plan = LogicalPlanBuilder::from(table_scan)
1825 .project(vec![col("a"), col("b")])?
1826 .filter(col("a").eq(lit(1i64)))?
1827 .build()?;
1828 assert_optimized_plan_equal!(
1830 plan,
1831 @r"
1832 Projection: test.a, test.b
1833 TableScan: test, full_filters=[test.a = Int64(1)]
1834 "
1835 )
1836 }
1837
1838 #[test]
1839 fn filter_after_limit() -> Result<()> {
1840 let table_scan = test_table_scan()?;
1841 let plan = LogicalPlanBuilder::from(table_scan)
1842 .project(vec![col("a"), col("b")])?
1843 .limit(0, Some(10))?
1844 .filter(col("a").eq(lit(1i64)))?
1845 .build()?;
1846 assert_optimized_plan_equal!(
1848 plan,
1849 @r"
1850 Filter: test.a = Int64(1)
1851 Limit: skip=0, fetch=10
1852 Projection: test.a, test.b
1853 TableScan: test
1854 "
1855 )
1856 }
1857
1858 #[test]
1859 fn filter_no_columns() -> Result<()> {
1860 let table_scan = test_table_scan()?;
1861 let plan = LogicalPlanBuilder::from(table_scan)
1862 .filter(lit(0i64).eq(lit(1i64)))?
1863 .build()?;
1864 assert_optimized_plan_equal!(
1865 plan,
1866 @"TableScan: test, full_filters=[Int64(0) = Int64(1)]"
1867 )
1868 }
1869
1870 #[test]
1871 fn filter_jump_2_plans() -> Result<()> {
1872 let table_scan = test_table_scan()?;
1873 let plan = LogicalPlanBuilder::from(table_scan)
1874 .project(vec![col("a"), col("b"), col("c")])?
1875 .project(vec![col("c"), col("b")])?
1876 .filter(col("a").eq(lit(1i64)))?
1877 .build()?;
1878 assert_optimized_plan_equal!(
1880 plan,
1881 @r"
1882 Projection: test.c, test.b
1883 Projection: test.a, test.b, test.c
1884 TableScan: test, full_filters=[test.a = Int64(1)]
1885 "
1886 )
1887 }
1888
1889 #[test]
1890 fn filter_move_agg() -> Result<()> {
1891 let table_scan = test_table_scan()?;
1892 let plan = LogicalPlanBuilder::from(table_scan)
1893 .aggregate(vec![col("a")], vec![sum(col("b")).alias("total_salary")])?
1894 .filter(col("a").gt(lit(10i64)))?
1895 .build()?;
1896 assert_optimized_plan_equal!(
1898 plan,
1899 @r"
1900 Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS total_salary]]
1901 TableScan: test, full_filters=[test.a > Int64(10)]
1902 "
1903 )
1904 }
1905
1906 #[test]
1908 fn filter_move_agg_special() -> Result<()> {
1909 let schema = Schema::new(vec![
1910 Field::new("$a", DataType::UInt32, false),
1911 Field::new("$b", DataType::UInt32, false),
1912 Field::new("$c", DataType::UInt32, false),
1913 ]);
1914 let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
1915
1916 let plan = LogicalPlanBuilder::from(table_scan)
1917 .aggregate(vec![col("$a")], vec![sum(col("$b")).alias("total_salary")])?
1918 .filter(col("$a").gt(lit(10i64)))?
1919 .build()?;
1920 assert_optimized_plan_equal!(
1922 plan,
1923 @r"
1924 Aggregate: groupBy=[[test.$a]], aggr=[[sum(test.$b) AS total_salary]]
1925 TableScan: test, full_filters=[test.$a > Int64(10)]
1926 "
1927 )
1928 }
1929
1930 #[test]
1931 fn filter_complex_group_by() -> Result<()> {
1932 let table_scan = test_table_scan()?;
1933 let plan = LogicalPlanBuilder::from(table_scan)
1934 .aggregate(vec![add(col("b"), col("a"))], vec![sum(col("a")), col("b")])?
1935 .filter(col("b").gt(lit(10i64)))?
1936 .build()?;
1937 assert_optimized_plan_equal!(
1938 plan,
1939 @r"
1940 Filter: test.b > Int64(10)
1941 Aggregate: groupBy=[[test.b + test.a]], aggr=[[sum(test.a), test.b]]
1942 TableScan: test
1943 "
1944 )
1945 }
1946
1947 #[test]
1948 fn push_agg_need_replace_expr() -> Result<()> {
1949 let plan = LogicalPlanBuilder::from(test_table_scan()?)
1950 .aggregate(vec![add(col("b"), col("a"))], vec![sum(col("a")), col("b")])?
1951 .filter(col("test.b + test.a").gt(lit(10i64)))?
1952 .build()?;
1953 assert_optimized_plan_equal!(
1954 plan,
1955 @r"
1956 Aggregate: groupBy=[[test.b + test.a]], aggr=[[sum(test.a), test.b]]
1957 TableScan: test, full_filters=[test.b + test.a > Int64(10)]
1958 "
1959 )
1960 }
1961
1962 #[test]
1963 fn filter_keep_agg() -> Result<()> {
1964 let table_scan = test_table_scan()?;
1965 let plan = LogicalPlanBuilder::from(table_scan)
1966 .aggregate(vec![col("a")], vec![sum(col("b")).alias("b")])?
1967 .filter(col("b").gt(lit(10i64)))?
1968 .build()?;
1969 assert_plan_not_transformed!(plan.clone());
1970
1971 assert_optimized_plan_equal!(
1973 plan,
1974 @r"
1975 Filter: b > Int64(10)
1976 Aggregate: groupBy=[[test.a]], aggr=[[sum(test.b) AS b]]
1977 TableScan: test
1978 "
1979 )
1980 }
1981
1982 #[test]
1984 fn filter_move_window() -> Result<()> {
1985 let table_scan = test_table_scan()?;
1986
1987 let window = Expr::from(WindowFunction::new(
1988 WindowFunctionDefinition::WindowUDF(
1989 datafusion_functions_window::rank::rank_udwf(),
1990 ),
1991 vec![],
1992 ))
1993 .partition_by(vec![col("a"), col("b")])
1994 .order_by(vec![col("c").sort(true, true)])
1995 .build()
1996 .unwrap();
1997
1998 let plan = LogicalPlanBuilder::from(table_scan)
1999 .window(vec![window])?
2000 .filter(col("b").gt(lit(10i64)))?
2001 .build()?;
2002
2003 assert_optimized_plan_equal!(
2004 plan,
2005 @r"
2006 WindowAggr: windowExpr=[[rank() PARTITION BY [test.a, test.b] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2007 TableScan: test, full_filters=[test.b > Int64(10)]
2008 "
2009 )
2010 }
2011
2012 #[test]
2014 fn filter_window_special_identifier() -> Result<()> {
2015 let schema = Schema::new(vec![
2016 Field::new("$a", DataType::UInt32, false),
2017 Field::new("$b", DataType::UInt32, false),
2018 Field::new("$c", DataType::UInt32, false),
2019 ]);
2020 let table_scan = table_scan(Some("test"), &schema, None)?.build()?;
2021
2022 let window = Expr::from(WindowFunction::new(
2023 WindowFunctionDefinition::WindowUDF(
2024 datafusion_functions_window::rank::rank_udwf(),
2025 ),
2026 vec![],
2027 ))
2028 .partition_by(vec![col("$a"), col("$b")])
2029 .order_by(vec![col("$c").sort(true, true)])
2030 .build()
2031 .unwrap();
2032
2033 let plan = LogicalPlanBuilder::from(table_scan)
2034 .window(vec![window])?
2035 .filter(col("$b").gt(lit(10i64)))?
2036 .build()?;
2037
2038 assert_optimized_plan_equal!(
2039 plan,
2040 @r"
2041 WindowAggr: windowExpr=[[rank() PARTITION BY [test.$a, test.$b] ORDER BY [test.$c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2042 TableScan: test, full_filters=[test.$b > Int64(10)]
2043 "
2044 )
2045 }
2046
2047 #[test]
2050 fn filter_move_complex_window() -> Result<()> {
2051 let table_scan = test_table_scan()?;
2052
2053 let window = Expr::from(WindowFunction::new(
2054 WindowFunctionDefinition::WindowUDF(
2055 datafusion_functions_window::rank::rank_udwf(),
2056 ),
2057 vec![],
2058 ))
2059 .partition_by(vec![col("a"), col("b")])
2060 .order_by(vec![col("c").sort(true, true)])
2061 .build()
2062 .unwrap();
2063
2064 let plan = LogicalPlanBuilder::from(table_scan)
2065 .window(vec![window])?
2066 .filter(and(col("a").gt(lit(10i64)), col("b").eq(lit(1i64))))?
2067 .build()?;
2068
2069 assert_optimized_plan_equal!(
2070 plan,
2071 @r"
2072 WindowAggr: windowExpr=[[rank() PARTITION BY [test.a, test.b] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2073 TableScan: test, full_filters=[test.a > Int64(10), test.b = Int64(1)]
2074 "
2075 )
2076 }
2077
2078 #[test]
2080 fn filter_move_partial_window() -> Result<()> {
2081 let table_scan = test_table_scan()?;
2082
2083 let window = Expr::from(WindowFunction::new(
2084 WindowFunctionDefinition::WindowUDF(
2085 datafusion_functions_window::rank::rank_udwf(),
2086 ),
2087 vec![],
2088 ))
2089 .partition_by(vec![col("a")])
2090 .order_by(vec![col("c").sort(true, true)])
2091 .build()
2092 .unwrap();
2093
2094 let plan = LogicalPlanBuilder::from(table_scan)
2095 .window(vec![window])?
2096 .filter(and(col("a").gt(lit(10i64)), col("b").eq(lit(1i64))))?
2097 .build()?;
2098
2099 assert_optimized_plan_equal!(
2100 plan,
2101 @r"
2102 Filter: test.b = Int64(1)
2103 WindowAggr: windowExpr=[[rank() PARTITION BY [test.a] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2104 TableScan: test, full_filters=[test.a > Int64(10)]
2105 "
2106 )
2107 }
2108
2109 #[test]
2114 fn filter_expression_move_window() -> Result<()> {
2115 let table_scan = test_table_scan()?;
2116
2117 let window = Expr::from(WindowFunction::new(
2118 WindowFunctionDefinition::WindowUDF(
2119 datafusion_functions_window::rank::rank_udwf(),
2120 ),
2121 vec![],
2122 ))
2123 .partition_by(vec![add(col("a"), col("b"))]) .order_by(vec![col("c").sort(true, true)])
2125 .build()
2126 .unwrap();
2127
2128 let plan = LogicalPlanBuilder::from(table_scan)
2129 .window(vec![window])?
2130 .filter(add(col("a"), col("b")).gt(lit(10i64)))? .build()?;
2132
2133 assert_optimized_plan_equal!(
2134 plan,
2135 @r"
2136 WindowAggr: windowExpr=[[rank() PARTITION BY [test.a + test.b] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2137 TableScan: test, full_filters=[test.a + test.b > Int64(10)]
2138 "
2139 )
2140 }
2141
2142 #[test]
2145 fn filter_multiple_windows_common_partitions() -> Result<()> {
2146 let table_scan = test_table_scan()?;
2147
2148 let window1 = Expr::from(WindowFunction::new(
2149 WindowFunctionDefinition::WindowUDF(
2150 datafusion_functions_window::rank::rank_udwf(),
2151 ),
2152 vec![],
2153 ))
2154 .partition_by(vec![col("a")])
2155 .order_by(vec![col("c").sort(true, true)])
2156 .build()
2157 .unwrap();
2158
2159 let window2 = Expr::from(WindowFunction::new(
2160 WindowFunctionDefinition::WindowUDF(
2161 datafusion_functions_window::rank::rank_udwf(),
2162 ),
2163 vec![],
2164 ))
2165 .partition_by(vec![col("b"), col("a")])
2166 .order_by(vec![col("c").sort(true, true)])
2167 .build()
2168 .unwrap();
2169
2170 let plan = LogicalPlanBuilder::from(table_scan)
2171 .window(vec![window1, window2])?
2172 .filter(col("a").gt(lit(10i64)))? .build()?;
2174
2175 assert_optimized_plan_equal!(
2176 plan,
2177 @r"
2178 WindowAggr: windowExpr=[[rank() PARTITION BY [test.a] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, rank() PARTITION BY [test.b, test.a] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2179 TableScan: test, full_filters=[test.a > Int64(10)]
2180 "
2181 )
2182 }
2183
2184 #[test]
2187 fn filter_multiple_windows_disjoint_partitions() -> Result<()> {
2188 let table_scan = test_table_scan()?;
2189
2190 let window1 = Expr::from(WindowFunction::new(
2191 WindowFunctionDefinition::WindowUDF(
2192 datafusion_functions_window::rank::rank_udwf(),
2193 ),
2194 vec![],
2195 ))
2196 .partition_by(vec![col("a")])
2197 .order_by(vec![col("c").sort(true, true)])
2198 .build()
2199 .unwrap();
2200
2201 let window2 = Expr::from(WindowFunction::new(
2202 WindowFunctionDefinition::WindowUDF(
2203 datafusion_functions_window::rank::rank_udwf(),
2204 ),
2205 vec![],
2206 ))
2207 .partition_by(vec![col("b"), col("a")])
2208 .order_by(vec![col("c").sort(true, true)])
2209 .build()
2210 .unwrap();
2211
2212 let plan = LogicalPlanBuilder::from(table_scan)
2213 .window(vec![window1, window2])?
2214 .filter(col("b").gt(lit(10i64)))? .build()?;
2216
2217 assert_optimized_plan_equal!(
2218 plan,
2219 @r"
2220 Filter: test.b > Int64(10)
2221 WindowAggr: windowExpr=[[rank() PARTITION BY [test.a] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, rank() PARTITION BY [test.b, test.a] ORDER BY [test.c ASC NULLS FIRST] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
2222 TableScan: test
2223 "
2224 )
2225 }
2226
2227 #[test]
2229 fn alias() -> Result<()> {
2230 let table_scan = test_table_scan()?;
2231 let plan = LogicalPlanBuilder::from(table_scan)
2232 .project(vec![col("a").alias("b"), col("c")])?
2233 .filter(col("b").eq(lit(1i64)))?
2234 .build()?;
2235 assert_optimized_plan_equal!(
2237 plan,
2238 @r"
2239 Projection: test.a AS b, test.c
2240 TableScan: test, full_filters=[test.a = Int64(1)]
2241 "
2242 )
2243 }
2244
2245 fn add(left: Expr, right: Expr) -> Expr {
2246 Expr::BinaryExpr(BinaryExpr::new(
2247 Box::new(left),
2248 Operator::Plus,
2249 Box::new(right),
2250 ))
2251 }
2252
2253 fn multiply(left: Expr, right: Expr) -> Expr {
2254 Expr::BinaryExpr(BinaryExpr::new(
2255 Box::new(left),
2256 Operator::Multiply,
2257 Box::new(right),
2258 ))
2259 }
2260
2261 #[test]
2263 fn complex_expression() -> Result<()> {
2264 let table_scan = test_table_scan()?;
2265 let plan = LogicalPlanBuilder::from(table_scan)
2266 .project(vec![
2267 add(multiply(col("a"), lit(2)), col("c")).alias("b"),
2268 col("c"),
2269 ])?
2270 .filter(col("b").eq(lit(1i64)))?
2271 .build()?;
2272
2273 assert_snapshot!(plan,
2275 @r"
2276 Filter: b = Int64(1)
2277 Projection: test.a * Int32(2) + test.c AS b, test.c
2278 TableScan: test
2279 ",
2280 );
2281 assert_optimized_plan_equal!(
2283 plan,
2284 @r"
2285 Projection: test.a * Int32(2) + test.c AS b, test.c
2286 TableScan: test, full_filters=[test.a * Int32(2) + test.c = Int64(1)]
2287 "
2288 )
2289 }
2290
2291 #[test]
2293 fn complex_plan() -> Result<()> {
2294 let table_scan = test_table_scan()?;
2295 let plan = LogicalPlanBuilder::from(table_scan)
2296 .project(vec![
2297 add(multiply(col("a"), lit(2)), col("c")).alias("b"),
2298 col("c"),
2299 ])?
2300 .project(vec![multiply(col("b"), lit(3)).alias("a"), col("c")])?
2302 .filter(col("a").eq(lit(1i64)))?
2303 .build()?;
2304
2305 assert_snapshot!(plan,
2307 @r"
2308 Filter: a = Int64(1)
2309 Projection: b * Int32(3) AS a, test.c
2310 Projection: test.a * Int32(2) + test.c AS b, test.c
2311 TableScan: test
2312 ",
2313 );
2314 assert_optimized_plan_equal!(
2316 plan,
2317 @r"
2318 Projection: b * Int32(3) AS a, test.c
2319 Projection: test.a * Int32(2) + test.c AS b, test.c
2320 TableScan: test, full_filters=[(test.a * Int32(2) + test.c) * Int32(3) = Int64(1)]
2321 "
2322 )
2323 }
2324
2325 #[derive(Debug, PartialEq, Eq, Hash)]
2326 struct NoopPlan {
2327 input: Vec<LogicalPlan>,
2328 schema: DFSchemaRef,
2329 }
2330
2331 impl PartialOrd for NoopPlan {
2333 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2334 self.input
2335 .partial_cmp(&other.input)
2336 .filter(|cmp| *cmp != Ordering::Equal || self == other)
2338 }
2339 }
2340
2341 impl UserDefinedLogicalNodeCore for NoopPlan {
2342 fn name(&self) -> &str {
2343 "NoopPlan"
2344 }
2345
2346 fn inputs(&self) -> Vec<&LogicalPlan> {
2347 self.input.iter().collect()
2348 }
2349
2350 fn schema(&self) -> &DFSchemaRef {
2351 &self.schema
2352 }
2353
2354 fn expressions(&self) -> Vec<Expr> {
2355 self.input
2356 .iter()
2357 .flat_map(|child| child.expressions())
2358 .collect()
2359 }
2360
2361 fn prevent_predicate_push_down_columns(&self) -> HashSet<String> {
2362 HashSet::from_iter(vec!["c".to_string()])
2363 }
2364
2365 fn fmt_for_explain(&self, f: &mut Formatter) -> std::fmt::Result {
2366 write!(f, "NoopPlan")
2367 }
2368
2369 fn with_exprs_and_inputs(
2370 &self,
2371 _exprs: Vec<Expr>,
2372 inputs: Vec<LogicalPlan>,
2373 ) -> Result<Self> {
2374 Ok(Self {
2375 input: inputs,
2376 schema: Arc::clone(&self.schema),
2377 })
2378 }
2379
2380 fn supports_limit_pushdown(&self) -> bool {
2381 false }
2383 }
2384
2385 #[test]
2386 fn user_defined_plan_outer_referenced_column() -> Result<()> {
2387 let table_scan = test_table_scan()?;
2388
2389 let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
2394 .filter(out_ref_col(DataType::UInt32, "test.c").eq(col("sq.a")))?
2395 .project(vec![col("sq.a")])?
2396 .build()?;
2397
2398 let custom_plan = LogicalPlan::Extension(Extension {
2399 node: Arc::new(NoopPlan {
2400 input: vec![table_scan.clone()],
2401 schema: Arc::clone(table_scan.schema()),
2402 }),
2403 });
2404 let plan = LogicalPlanBuilder::from(custom_plan)
2405 .filter(exists(Arc::new(subquery)))?
2406 .build()?;
2407
2408 assert_optimized_plan_equal!(
2410 plan,
2411 @r"
2412 Filter: EXISTS (<subquery>)
2413 Subquery:
2414 Projection: sq.a
2415 TableScan: sq, full_filters=[outer_ref(test.c) = sq.a]
2416 NoopPlan
2417 TableScan: test
2418 "
2419 )
2420 }
2421
2422 #[test]
2423 fn user_defined_plan_outer_referenced_column_set_comparison() -> Result<()> {
2424 let table_scan = test_table_scan()?;
2425
2426 let subquery = LogicalPlanBuilder::from(test_table_scan_with_name("sq")?)
2430 .filter(out_ref_col(DataType::UInt32, "test.c").eq(col("sq.a")))?
2431 .project(vec![col("sq.a")])?
2432 .build()?;
2433 let outer_ref_columns = subquery.all_out_ref_exprs();
2434 let set_comparison = Expr::SetComparison(SetComparison::new(
2435 Box::new(col("test.a")),
2436 Subquery {
2437 subquery: Arc::new(subquery),
2438 outer_ref_columns,
2439 spans: Spans::new(),
2440 },
2441 Operator::Gt,
2442 SetQuantifier::Any,
2443 ));
2444
2445 let custom_plan = LogicalPlan::Extension(Extension {
2446 node: Arc::new(NoopPlan {
2447 input: vec![table_scan.clone()],
2448 schema: Arc::clone(table_scan.schema()),
2449 }),
2450 });
2451 let plan = LogicalPlanBuilder::from(custom_plan)
2452 .filter(set_comparison)?
2453 .build()?;
2454
2455 assert_optimized_plan_equal!(
2457 plan,
2458 @r"
2459 Filter: test.a > ANY (<subquery>)
2460 Subquery:
2461 Projection: sq.a
2462 TableScan: sq, full_filters=[outer_ref(test.c) = sq.a]
2463 NoopPlan
2464 TableScan: test
2465 "
2466 )
2467 }
2468
2469 #[test]
2470 fn user_defined_plan() -> Result<()> {
2471 let table_scan = test_table_scan()?;
2472
2473 let custom_plan = LogicalPlan::Extension(Extension {
2474 node: Arc::new(NoopPlan {
2475 input: vec![table_scan.clone()],
2476 schema: Arc::clone(table_scan.schema()),
2477 }),
2478 });
2479 let plan = LogicalPlanBuilder::from(custom_plan)
2480 .filter(col("a").eq(lit(1i64)))?
2481 .build()?;
2482
2483 assert_optimized_plan_equal!(
2485 plan,
2486 @r"
2487 NoopPlan
2488 TableScan: test, full_filters=[test.a = Int64(1)]
2489 "
2490 )?;
2491
2492 let custom_plan = LogicalPlan::Extension(Extension {
2493 node: Arc::new(NoopPlan {
2494 input: vec![table_scan.clone()],
2495 schema: Arc::clone(table_scan.schema()),
2496 }),
2497 });
2498 let plan = LogicalPlanBuilder::from(custom_plan)
2499 .filter(col("a").eq(lit(1i64)).and(col("c").eq(lit(2i64))))?
2500 .build()?;
2501
2502 assert_optimized_plan_equal!(
2504 plan,
2505 @r"
2506 Filter: test.c = Int64(2)
2507 NoopPlan
2508 TableScan: test, full_filters=[test.a = Int64(1)]
2509 "
2510 )?;
2511
2512 let custom_plan = LogicalPlan::Extension(Extension {
2513 node: Arc::new(NoopPlan {
2514 input: vec![table_scan.clone(), table_scan.clone()],
2515 schema: Arc::clone(table_scan.schema()),
2516 }),
2517 });
2518 let plan = LogicalPlanBuilder::from(custom_plan)
2519 .filter(col("a").eq(lit(1i64)))?
2520 .build()?;
2521
2522 assert_optimized_plan_equal!(
2524 plan,
2525 @r"
2526 NoopPlan
2527 TableScan: test, full_filters=[test.a = Int64(1)]
2528 TableScan: test, full_filters=[test.a = Int64(1)]
2529 "
2530 )?;
2531
2532 let custom_plan = LogicalPlan::Extension(Extension {
2533 node: Arc::new(NoopPlan {
2534 input: vec![table_scan.clone(), table_scan.clone()],
2535 schema: Arc::clone(table_scan.schema()),
2536 }),
2537 });
2538 let plan = LogicalPlanBuilder::from(custom_plan)
2539 .filter(col("a").eq(lit(1i64)).and(col("c").eq(lit(2i64))))?
2540 .build()?;
2541
2542 assert_optimized_plan_equal!(
2544 plan,
2545 @r"
2546 Filter: test.c = Int64(2)
2547 NoopPlan
2548 TableScan: test, full_filters=[test.a = Int64(1)]
2549 TableScan: test, full_filters=[test.a = Int64(1)]
2550 "
2551 )
2552 }
2553
2554 #[test]
2557 fn multi_filter() -> Result<()> {
2558 let table_scan = test_table_scan()?;
2560 let plan = LogicalPlanBuilder::from(table_scan)
2561 .project(vec![col("a").alias("b"), col("c")])?
2562 .aggregate(vec![col("b")], vec![sum(col("c"))])?
2563 .filter(col("b").gt(lit(10i64)))?
2564 .filter(col("sum(test.c)").gt(lit(10i64)))?
2565 .build()?;
2566
2567 assert_snapshot!(plan,
2569 @r"
2570 Filter: sum(test.c) > Int64(10)
2571 Filter: b > Int64(10)
2572 Aggregate: groupBy=[[b]], aggr=[[sum(test.c)]]
2573 Projection: test.a AS b, test.c
2574 TableScan: test
2575 ",
2576 );
2577 assert_optimized_plan_equal!(
2579 plan,
2580 @r"
2581 Filter: sum(test.c) > Int64(10)
2582 Aggregate: groupBy=[[b]], aggr=[[sum(test.c)]]
2583 Projection: test.a AS b, test.c
2584 TableScan: test, full_filters=[test.a > Int64(10)]
2585 "
2586 )
2587 }
2588
2589 #[test]
2592 fn split_filter() -> Result<()> {
2593 let table_scan = test_table_scan()?;
2595 let plan = LogicalPlanBuilder::from(table_scan)
2596 .project(vec![col("a").alias("b"), col("c")])?
2597 .aggregate(vec![col("b")], vec![sum(col("c"))])?
2598 .filter(and(
2599 col("sum(test.c)").gt(lit(10i64)),
2600 and(col("b").gt(lit(10i64)), col("sum(test.c)").lt(lit(20i64))),
2601 ))?
2602 .build()?;
2603
2604 assert_snapshot!(plan,
2606 @r"
2607 Filter: sum(test.c) > Int64(10) AND b > Int64(10) AND sum(test.c) < Int64(20)
2608 Aggregate: groupBy=[[b]], aggr=[[sum(test.c)]]
2609 Projection: test.a AS b, test.c
2610 TableScan: test
2611 ",
2612 );
2613 assert_optimized_plan_equal!(
2615 plan,
2616 @r"
2617 Filter: sum(test.c) > Int64(10) AND sum(test.c) < Int64(20)
2618 Aggregate: groupBy=[[b]], aggr=[[sum(test.c)]]
2619 Projection: test.a AS b, test.c
2620 TableScan: test, full_filters=[test.a > Int64(10)]
2621 "
2622 )
2623 }
2624
2625 #[test]
2627 fn double_limit() -> Result<()> {
2628 let table_scan = test_table_scan()?;
2629 let plan = LogicalPlanBuilder::from(table_scan)
2630 .project(vec![col("a"), col("b")])?
2631 .limit(0, Some(20))?
2632 .limit(0, Some(10))?
2633 .project(vec![col("a"), col("b")])?
2634 .filter(col("a").eq(lit(1i64)))?
2635 .build()?;
2636 assert_optimized_plan_equal!(
2638 plan,
2639 @r"
2640 Projection: test.a, test.b
2641 Filter: test.a = Int64(1)
2642 Limit: skip=0, fetch=10
2643 Limit: skip=0, fetch=20
2644 Projection: test.a, test.b
2645 TableScan: test
2646 "
2647 )
2648 }
2649
2650 #[test]
2651 fn union_all() -> Result<()> {
2652 let table_scan = test_table_scan()?;
2653 let table_scan2 = test_table_scan_with_name("test2")?;
2654 let plan = LogicalPlanBuilder::from(table_scan)
2655 .union(LogicalPlanBuilder::from(table_scan2).build()?)?
2656 .filter(col("a").eq(lit(1i64)))?
2657 .build()?;
2658 assert_optimized_plan_equal!(
2660 plan,
2661 @r"
2662 Union
2663 TableScan: test, full_filters=[test.a = Int64(1)]
2664 TableScan: test2, full_filters=[test2.a = Int64(1)]
2665 "
2666 )
2667 }
2668
2669 #[test]
2670 fn union_all_on_projection() -> Result<()> {
2671 let table_scan = test_table_scan()?;
2672 let table = LogicalPlanBuilder::from(table_scan)
2673 .project(vec![col("a").alias("b")])?
2674 .alias("test2")?;
2675
2676 let plan = table
2677 .clone()
2678 .union(table.build()?)?
2679 .filter(col("b").eq(lit(1i64)))?
2680 .build()?;
2681
2682 assert_optimized_plan_equal!(
2684 plan,
2685 @r"
2686 Union
2687 SubqueryAlias: test2
2688 Projection: test.a AS b
2689 TableScan: test, full_filters=[test.a = Int64(1)]
2690 SubqueryAlias: test2
2691 Projection: test.a AS b
2692 TableScan: test, full_filters=[test.a = Int64(1)]
2693 "
2694 )
2695 }
2696
2697 #[test]
2698 fn test_union_different_schema() -> Result<()> {
2699 let left = LogicalPlanBuilder::from(test_table_scan()?)
2700 .project(vec![col("a"), col("b"), col("c")])?
2701 .build()?;
2702
2703 let schema = Schema::new(vec![
2704 Field::new("d", DataType::UInt32, false),
2705 Field::new("e", DataType::UInt32, false),
2706 Field::new("f", DataType::UInt32, false),
2707 ]);
2708 let right = table_scan(Some("test1"), &schema, None)?
2709 .project(vec![col("d"), col("e"), col("f")])?
2710 .build()?;
2711 let filter = and(col("test.a").eq(lit(1)), col("test1.d").gt(lit(2)));
2712 let plan = LogicalPlanBuilder::from(left)
2713 .cross_join(right)?
2714 .project(vec![col("test.a"), col("test1.d")])?
2715 .filter(filter)?
2716 .build()?;
2717
2718 assert_optimized_plan_equal!(
2719 plan,
2720 @r"
2721 Projection: test.a, test1.d
2722 Cross Join:
2723 Projection: test.a, test.b, test.c
2724 TableScan: test, full_filters=[test.a = Int32(1)]
2725 Projection: test1.d, test1.e, test1.f
2726 TableScan: test1, full_filters=[test1.d > Int32(2)]
2727 "
2728 )
2729 }
2730
2731 #[test]
2732 fn test_project_same_name_different_qualifier() -> Result<()> {
2733 let table_scan = test_table_scan()?;
2734 let left = LogicalPlanBuilder::from(table_scan)
2735 .project(vec![col("a"), col("b"), col("c")])?
2736 .build()?;
2737 let right_table_scan = test_table_scan_with_name("test1")?;
2738 let right = LogicalPlanBuilder::from(right_table_scan)
2739 .project(vec![col("a"), col("b"), col("c")])?
2740 .build()?;
2741 let filter = and(col("test.a").eq(lit(1)), col("test1.a").gt(lit(2)));
2742 let plan = LogicalPlanBuilder::from(left)
2743 .cross_join(right)?
2744 .project(vec![col("test.a"), col("test1.a")])?
2745 .filter(filter)?
2746 .build()?;
2747
2748 assert_optimized_plan_equal!(
2749 plan,
2750 @r"
2751 Projection: test.a, test1.a
2752 Cross Join:
2753 Projection: test.a, test.b, test.c
2754 TableScan: test, full_filters=[test.a = Int32(1)]
2755 Projection: test1.a, test1.b, test1.c
2756 TableScan: test1, full_filters=[test1.a > Int32(2)]
2757 "
2758 )
2759 }
2760
2761 #[test]
2763 fn filter_2_breaks_limits() -> Result<()> {
2764 let table_scan = test_table_scan()?;
2765 let plan = LogicalPlanBuilder::from(table_scan)
2766 .project(vec![col("a")])?
2767 .filter(col("a").lt_eq(lit(1i64)))?
2768 .limit(0, Some(1))?
2769 .project(vec![col("a")])?
2770 .filter(col("a").gt_eq(lit(1i64)))?
2771 .build()?;
2772 assert_snapshot!(plan,
2776 @r"
2777 Filter: test.a >= Int64(1)
2778 Projection: test.a
2779 Limit: skip=0, fetch=1
2780 Filter: test.a <= Int64(1)
2781 Projection: test.a
2782 TableScan: test
2783 ",
2784 );
2785 assert_optimized_plan_equal!(
2786 plan,
2787 @r"
2788 Projection: test.a
2789 Filter: test.a >= Int64(1)
2790 Limit: skip=0, fetch=1
2791 Projection: test.a
2792 TableScan: test, full_filters=[test.a <= Int64(1)]
2793 "
2794 )
2795 }
2796
2797 #[test]
2799 fn two_filters_on_same_depth() -> Result<()> {
2800 let table_scan = test_table_scan()?;
2801 let plan = LogicalPlanBuilder::from(table_scan)
2802 .limit(0, Some(1))?
2803 .filter(col("a").lt_eq(lit(1i64)))?
2804 .filter(col("a").gt_eq(lit(1i64)))?
2805 .project(vec![col("a")])?
2806 .build()?;
2807
2808 assert_snapshot!(plan,
2810 @r"
2811 Projection: test.a
2812 Filter: test.a >= Int64(1)
2813 Filter: test.a <= Int64(1)
2814 Limit: skip=0, fetch=1
2815 TableScan: test
2816 ",
2817 );
2818 assert_optimized_plan_equal!(
2819 plan,
2820 @r"
2821 Projection: test.a
2822 Filter: test.a <= Int64(1) AND test.a >= Int64(1)
2823 Limit: skip=0, fetch=1
2824 TableScan: test
2825 "
2826 )
2827 }
2828
2829 #[test]
2832 fn filters_user_defined_node() -> Result<()> {
2833 let table_scan = test_table_scan()?;
2834 let plan = LogicalPlanBuilder::from(table_scan)
2835 .filter(col("a").lt_eq(lit(1i64)))?
2836 .build()?;
2837
2838 let plan = user_defined::new(plan);
2839
2840 assert_snapshot!(plan,
2842 @r"
2843 TestUserDefined
2844 Filter: test.a <= Int64(1)
2845 TableScan: test
2846 ",
2847 );
2848 assert_optimized_plan_equal!(
2849 plan,
2850 @r"
2851 TestUserDefined
2852 TableScan: test, full_filters=[test.a <= Int64(1)]
2853 "
2854 )
2855 }
2856
2857 #[test]
2859 fn filter_on_join_on_common_independent() -> Result<()> {
2860 let table_scan = test_table_scan()?;
2861 let left = LogicalPlanBuilder::from(table_scan).build()?;
2862 let right_table_scan = test_table_scan_with_name("test2")?;
2863 let right = LogicalPlanBuilder::from(right_table_scan)
2864 .project(vec![col("a")])?
2865 .build()?;
2866 let plan = LogicalPlanBuilder::from(left)
2867 .join(
2868 right,
2869 JoinType::Inner,
2870 (vec![Column::from_name("a")], vec![Column::from_name("a")]),
2871 None,
2872 )?
2873 .filter(col("test.a").lt_eq(lit(1i64)))?
2874 .build()?;
2875
2876 assert_snapshot!(plan,
2878 @r"
2879 Filter: test.a <= Int64(1)
2880 Inner Join: test.a = test2.a
2881 TableScan: test
2882 Projection: test2.a
2883 TableScan: test2
2884 ",
2885 );
2886 assert_optimized_plan_equal!(
2888 plan,
2889 @r"
2890 Inner Join: test.a = test2.a
2891 TableScan: test, full_filters=[test.a <= Int64(1)]
2892 Projection: test2.a
2893 TableScan: test2, full_filters=[test2.a <= Int64(1)]
2894 "
2895 )
2896 }
2897
2898 #[test]
2900 fn filter_using_join_on_common_independent() -> Result<()> {
2901 let table_scan = test_table_scan()?;
2902 let left = LogicalPlanBuilder::from(table_scan).build()?;
2903 let right_table_scan = test_table_scan_with_name("test2")?;
2904 let right = LogicalPlanBuilder::from(right_table_scan)
2905 .project(vec![col("a")])?
2906 .build()?;
2907 let plan = LogicalPlanBuilder::from(left)
2908 .join_using(
2909 right,
2910 JoinType::Inner,
2911 vec![Column::from_name("a".to_string())],
2912 )?
2913 .filter(col("a").lt_eq(lit(1i64)))?
2914 .build()?;
2915
2916 assert_snapshot!(plan,
2918 @r"
2919 Filter: test.a <= Int64(1)
2920 Inner Join: Using test.a = test2.a
2921 TableScan: test
2922 Projection: test2.a
2923 TableScan: test2
2924 ",
2925 );
2926 assert_optimized_plan_equal!(
2928 plan,
2929 @r"
2930 Inner Join: Using test.a = test2.a
2931 TableScan: test, full_filters=[test.a <= Int64(1)]
2932 Projection: test2.a
2933 TableScan: test2, full_filters=[test2.a <= Int64(1)]
2934 "
2935 )
2936 }
2937
2938 #[test]
2940 fn filter_join_on_common_dependent() -> Result<()> {
2941 let table_scan = test_table_scan()?;
2942 let left = LogicalPlanBuilder::from(table_scan)
2943 .project(vec![col("a"), col("c")])?
2944 .build()?;
2945 let right_table_scan = test_table_scan_with_name("test2")?;
2946 let right = LogicalPlanBuilder::from(right_table_scan)
2947 .project(vec![col("a"), col("b")])?
2948 .build()?;
2949 let plan = LogicalPlanBuilder::from(left)
2950 .join(
2951 right,
2952 JoinType::Inner,
2953 (vec![Column::from_name("a")], vec![Column::from_name("a")]),
2954 None,
2955 )?
2956 .filter(col("c").lt_eq(col("b")))?
2957 .build()?;
2958
2959 assert_snapshot!(plan,
2961 @r"
2962 Filter: test.c <= test2.b
2963 Inner Join: test.a = test2.a
2964 Projection: test.a, test.c
2965 TableScan: test
2966 Projection: test2.a, test2.b
2967 TableScan: test2
2968 ",
2969 );
2970 assert_optimized_plan_equal!(
2972 plan,
2973 @r"
2974 Inner Join: test.a = test2.a Filter: test.c <= test2.b
2975 Projection: test.a, test.c
2976 TableScan: test
2977 Projection: test2.a, test2.b
2978 TableScan: test2
2979 "
2980 )
2981 }
2982
2983 #[test]
2985 fn filter_join_on_one_side() -> Result<()> {
2986 let table_scan = test_table_scan()?;
2987 let left = LogicalPlanBuilder::from(table_scan)
2988 .project(vec![col("a"), col("b")])?
2989 .build()?;
2990 let table_scan_right = test_table_scan_with_name("test2")?;
2991 let right = LogicalPlanBuilder::from(table_scan_right)
2992 .project(vec![col("a"), col("c")])?
2993 .build()?;
2994
2995 let plan = LogicalPlanBuilder::from(left)
2996 .join(
2997 right,
2998 JoinType::Inner,
2999 (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3000 None,
3001 )?
3002 .filter(col("b").lt_eq(lit(1i64)))?
3003 .build()?;
3004
3005 assert_snapshot!(plan,
3007 @r"
3008 Filter: test.b <= Int64(1)
3009 Inner Join: test.a = test2.a
3010 Projection: test.a, test.b
3011 TableScan: test
3012 Projection: test2.a, test2.c
3013 TableScan: test2
3014 ",
3015 );
3016 assert_optimized_plan_equal!(
3017 plan,
3018 @r"
3019 Inner Join: test.a = test2.a
3020 Projection: test.a, test.b
3021 TableScan: test, full_filters=[test.b <= Int64(1)]
3022 Projection: test2.a, test2.c
3023 TableScan: test2
3024 "
3025 )
3026 }
3027
3028 #[test]
3031 fn filter_using_left_join() -> Result<()> {
3032 let table_scan = test_table_scan()?;
3033 let left = LogicalPlanBuilder::from(table_scan).build()?;
3034 let right_table_scan = test_table_scan_with_name("test2")?;
3035 let right = LogicalPlanBuilder::from(right_table_scan)
3036 .project(vec![col("a")])?
3037 .build()?;
3038 let plan = LogicalPlanBuilder::from(left)
3039 .join_using(
3040 right,
3041 JoinType::Left,
3042 vec![Column::from_name("a".to_string())],
3043 )?
3044 .filter(col("test2.a").lt_eq(lit(1i64)))?
3045 .build()?;
3046
3047 assert_snapshot!(plan,
3049 @r"
3050 Filter: test2.a <= Int64(1)
3051 Left Join: Using test.a = test2.a
3052 TableScan: test
3053 Projection: test2.a
3054 TableScan: test2
3055 ",
3056 );
3057 assert_optimized_plan_equal!(
3059 plan,
3060 @r"
3061 Filter: test2.a <= Int64(1)
3062 Left Join: Using test.a = test2.a
3063 TableScan: test, full_filters=[test.a <= Int64(1)]
3064 Projection: test2.a
3065 TableScan: test2
3066 "
3067 )
3068 }
3069
3070 #[test]
3072 fn filter_using_right_join() -> Result<()> {
3073 let table_scan = test_table_scan()?;
3074 let left = LogicalPlanBuilder::from(table_scan).build()?;
3075 let right_table_scan = test_table_scan_with_name("test2")?;
3076 let right = LogicalPlanBuilder::from(right_table_scan)
3077 .project(vec![col("a")])?
3078 .build()?;
3079 let plan = LogicalPlanBuilder::from(left)
3080 .join_using(
3081 right,
3082 JoinType::Right,
3083 vec![Column::from_name("a".to_string())],
3084 )?
3085 .filter(col("test.a").lt_eq(lit(1i64)))?
3086 .build()?;
3087
3088 assert_snapshot!(plan,
3090 @r"
3091 Filter: test.a <= Int64(1)
3092 Right Join: Using test.a = test2.a
3093 TableScan: test
3094 Projection: test2.a
3095 TableScan: test2
3096 ",
3097 );
3098 assert_optimized_plan_equal!(
3100 plan,
3101 @r"
3102 Filter: test.a <= Int64(1)
3103 Right Join: Using test.a = test2.a
3104 TableScan: test
3105 Projection: test2.a
3106 TableScan: test2, full_filters=[test2.a <= Int64(1)]
3107 "
3108 )
3109 }
3110
3111 #[test]
3113 fn filter_using_left_join_on_common() -> Result<()> {
3114 let table_scan = test_table_scan()?;
3115 let left = LogicalPlanBuilder::from(table_scan).build()?;
3116 let right_table_scan = test_table_scan_with_name("test2")?;
3117 let right = LogicalPlanBuilder::from(right_table_scan)
3118 .project(vec![col("a")])?
3119 .build()?;
3120 let plan = LogicalPlanBuilder::from(left)
3121 .join_using(
3122 right,
3123 JoinType::Left,
3124 vec![Column::from_name("a".to_string())],
3125 )?
3126 .filter(col("a").lt_eq(lit(1i64)))?
3127 .build()?;
3128
3129 assert_snapshot!(plan,
3131 @r"
3132 Filter: test.a <= Int64(1)
3133 Left Join: Using test.a = test2.a
3134 TableScan: test
3135 Projection: test2.a
3136 TableScan: test2
3137 ",
3138 );
3139 assert_optimized_plan_equal!(
3141 plan,
3142 @r"
3143 Left Join: Using test.a = test2.a
3144 TableScan: test, full_filters=[test.a <= Int64(1)]
3145 Projection: test2.a
3146 TableScan: test2, full_filters=[test2.a <= Int64(1)]
3147 "
3148 )
3149 }
3150
3151 #[test]
3153 fn filter_using_right_join_on_common() -> Result<()> {
3154 let table_scan = test_table_scan()?;
3155 let left = LogicalPlanBuilder::from(table_scan).build()?;
3156 let right_table_scan = test_table_scan_with_name("test2")?;
3157 let right = LogicalPlanBuilder::from(right_table_scan)
3158 .project(vec![col("a")])?
3159 .build()?;
3160 let plan = LogicalPlanBuilder::from(left)
3161 .join_using(
3162 right,
3163 JoinType::Right,
3164 vec![Column::from_name("a".to_string())],
3165 )?
3166 .filter(col("test2.a").lt_eq(lit(1i64)))?
3167 .build()?;
3168
3169 assert_snapshot!(plan,
3171 @r"
3172 Filter: test2.a <= Int64(1)
3173 Right Join: Using test.a = test2.a
3174 TableScan: test
3175 Projection: test2.a
3176 TableScan: test2
3177 ",
3178 );
3179 assert_optimized_plan_equal!(
3181 plan,
3182 @r"
3183 Right Join: Using test.a = test2.a
3184 TableScan: test, full_filters=[test.a <= Int64(1)]
3185 Projection: test2.a
3186 TableScan: test2, full_filters=[test2.a <= Int64(1)]
3187 "
3188 )
3189 }
3190
3191 #[test]
3193 fn join_on_with_filter() -> Result<()> {
3194 let table_scan = test_table_scan()?;
3195 let left = LogicalPlanBuilder::from(table_scan)
3196 .project(vec![col("a"), col("b"), col("c")])?
3197 .build()?;
3198 let right_table_scan = test_table_scan_with_name("test2")?;
3199 let right = LogicalPlanBuilder::from(right_table_scan)
3200 .project(vec![col("a"), col("b"), col("c")])?
3201 .build()?;
3202 let filter = col("test.c")
3203 .gt(lit(1u32))
3204 .and(col("test.b").lt(col("test2.b")))
3205 .and(col("test2.c").gt(lit(4u32)));
3206 let plan = LogicalPlanBuilder::from(left)
3207 .join(
3208 right,
3209 JoinType::Inner,
3210 (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3211 Some(filter),
3212 )?
3213 .build()?;
3214
3215 assert_snapshot!(plan,
3217 @r"
3218 Inner Join: test.a = test2.a Filter: test.c > UInt32(1) AND test.b < test2.b AND test2.c > UInt32(4)
3219 Projection: test.a, test.b, test.c
3220 TableScan: test
3221 Projection: test2.a, test2.b, test2.c
3222 TableScan: test2
3223 ",
3224 );
3225 assert_optimized_plan_equal!(
3226 plan,
3227 @r"
3228 Inner Join: test.a = test2.a Filter: test.b < test2.b
3229 Projection: test.a, test.b, test.c
3230 TableScan: test, full_filters=[test.c > UInt32(1)]
3231 Projection: test2.a, test2.b, test2.c
3232 TableScan: test2, full_filters=[test2.c > UInt32(4)]
3233 "
3234 )
3235 }
3236
3237 #[test]
3239 fn join_filter_removed() -> Result<()> {
3240 let table_scan = test_table_scan()?;
3241 let left = LogicalPlanBuilder::from(table_scan)
3242 .project(vec![col("a"), col("b"), col("c")])?
3243 .build()?;
3244 let right_table_scan = test_table_scan_with_name("test2")?;
3245 let right = LogicalPlanBuilder::from(right_table_scan)
3246 .project(vec![col("a"), col("b"), col("c")])?
3247 .build()?;
3248 let filter = col("test.b")
3249 .gt(lit(1u32))
3250 .and(col("test2.c").gt(lit(4u32)));
3251 let plan = LogicalPlanBuilder::from(left)
3252 .join(
3253 right,
3254 JoinType::Inner,
3255 (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3256 Some(filter),
3257 )?
3258 .build()?;
3259
3260 assert_snapshot!(plan,
3262 @r"
3263 Inner Join: test.a = test2.a Filter: test.b > UInt32(1) AND test2.c > UInt32(4)
3264 Projection: test.a, test.b, test.c
3265 TableScan: test
3266 Projection: test2.a, test2.b, test2.c
3267 TableScan: test2
3268 ",
3269 );
3270 assert_optimized_plan_equal!(
3271 plan,
3272 @r"
3273 Inner Join: test.a = test2.a
3274 Projection: test.a, test.b, test.c
3275 TableScan: test, full_filters=[test.b > UInt32(1)]
3276 Projection: test2.a, test2.b, test2.c
3277 TableScan: test2, full_filters=[test2.c > UInt32(4)]
3278 "
3279 )
3280 }
3281
3282 #[test]
3284 fn join_filter_on_common() -> Result<()> {
3285 let table_scan = test_table_scan()?;
3286 let left = LogicalPlanBuilder::from(table_scan)
3287 .project(vec![col("a")])?
3288 .build()?;
3289 let right_table_scan = test_table_scan_with_name("test2")?;
3290 let right = LogicalPlanBuilder::from(right_table_scan)
3291 .project(vec![col("b")])?
3292 .build()?;
3293 let filter = col("test.a").gt(lit(1u32));
3294 let plan = LogicalPlanBuilder::from(left)
3295 .join(
3296 right,
3297 JoinType::Inner,
3298 (vec![Column::from_name("a")], vec![Column::from_name("b")]),
3299 Some(filter),
3300 )?
3301 .build()?;
3302
3303 assert_snapshot!(plan,
3305 @r"
3306 Inner Join: test.a = test2.b Filter: test.a > UInt32(1)
3307 Projection: test.a
3308 TableScan: test
3309 Projection: test2.b
3310 TableScan: test2
3311 ",
3312 );
3313 assert_optimized_plan_equal!(
3314 plan,
3315 @r"
3316 Inner Join: test.a = test2.b
3317 Projection: test.a
3318 TableScan: test, full_filters=[test.a > UInt32(1)]
3319 Projection: test2.b
3320 TableScan: test2, full_filters=[test2.b > UInt32(1)]
3321 "
3322 )
3323 }
3324
3325 #[test]
3327 fn left_join_on_with_filter() -> Result<()> {
3328 let table_scan = test_table_scan()?;
3329 let left = LogicalPlanBuilder::from(table_scan)
3330 .project(vec![col("a"), col("b"), col("c")])?
3331 .build()?;
3332 let right_table_scan = test_table_scan_with_name("test2")?;
3333 let right = LogicalPlanBuilder::from(right_table_scan)
3334 .project(vec![col("a"), col("b"), col("c")])?
3335 .build()?;
3336 let filter = col("test.a")
3337 .gt(lit(1u32))
3338 .and(col("test.b").lt(col("test2.b")))
3339 .and(col("test2.c").gt(lit(4u32)));
3340 let plan = LogicalPlanBuilder::from(left)
3341 .join(
3342 right,
3343 JoinType::Left,
3344 (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3345 Some(filter),
3346 )?
3347 .build()?;
3348
3349 assert_snapshot!(plan,
3351 @r"
3352 Left Join: test.a = test2.a Filter: test.a > UInt32(1) AND test.b < test2.b AND test2.c > UInt32(4)
3353 Projection: test.a, test.b, test.c
3354 TableScan: test
3355 Projection: test2.a, test2.b, test2.c
3356 TableScan: test2
3357 ",
3358 );
3359 assert_optimized_plan_equal!(
3360 plan,
3361 @r"
3362 Left Join: test.a = test2.a Filter: test.a > UInt32(1) AND test.b < test2.b
3363 Projection: test.a, test.b, test.c
3364 TableScan: test
3365 Projection: test2.a, test2.b, test2.c
3366 TableScan: test2, full_filters=[test2.a > UInt32(1), test2.c > UInt32(4)]
3367 "
3368 )
3369 }
3370
3371 #[test]
3373 fn right_join_on_with_filter() -> Result<()> {
3374 let table_scan = test_table_scan()?;
3375 let left = LogicalPlanBuilder::from(table_scan)
3376 .project(vec![col("a"), col("b"), col("c")])?
3377 .build()?;
3378 let right_table_scan = test_table_scan_with_name("test2")?;
3379 let right = LogicalPlanBuilder::from(right_table_scan)
3380 .project(vec![col("a"), col("b"), col("c")])?
3381 .build()?;
3382 let filter = col("test.a")
3383 .gt(lit(1u32))
3384 .and(col("test.b").lt(col("test2.b")))
3385 .and(col("test2.c").gt(lit(4u32)));
3386 let plan = LogicalPlanBuilder::from(left)
3387 .join(
3388 right,
3389 JoinType::Right,
3390 (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3391 Some(filter),
3392 )?
3393 .build()?;
3394
3395 assert_snapshot!(plan,
3397 @r"
3398 Right Join: test.a = test2.a Filter: test.a > UInt32(1) AND test.b < test2.b AND test2.c > UInt32(4)
3399 Projection: test.a, test.b, test.c
3400 TableScan: test
3401 Projection: test2.a, test2.b, test2.c
3402 TableScan: test2
3403 ",
3404 );
3405 assert_optimized_plan_equal!(
3406 plan,
3407 @r"
3408 Right Join: test.a = test2.a Filter: test.b < test2.b AND test2.c > UInt32(4)
3409 Projection: test.a, test.b, test.c
3410 TableScan: test, full_filters=[test.a > UInt32(1)]
3411 Projection: test2.a, test2.b, test2.c
3412 TableScan: test2
3413 "
3414 )
3415 }
3416
3417 #[test]
3419 fn full_join_on_with_filter() -> Result<()> {
3420 let table_scan = test_table_scan()?;
3421 let left = LogicalPlanBuilder::from(table_scan)
3422 .project(vec![col("a"), col("b"), col("c")])?
3423 .build()?;
3424 let right_table_scan = test_table_scan_with_name("test2")?;
3425 let right = LogicalPlanBuilder::from(right_table_scan)
3426 .project(vec![col("a"), col("b"), col("c")])?
3427 .build()?;
3428 let filter = col("test.a")
3429 .gt(lit(1u32))
3430 .and(col("test.b").lt(col("test2.b")))
3431 .and(col("test2.c").gt(lit(4u32)));
3432 let plan = LogicalPlanBuilder::from(left)
3433 .join(
3434 right,
3435 JoinType::Full,
3436 (vec![Column::from_name("a")], vec![Column::from_name("a")]),
3437 Some(filter),
3438 )?
3439 .build()?;
3440 assert_plan_not_transformed!(plan.clone());
3441
3442 assert_snapshot!(plan,
3444 @r"
3445 Full Join: test.a = test2.a Filter: test.a > UInt32(1) AND test.b < test2.b AND test2.c > UInt32(4)
3446 Projection: test.a, test.b, test.c
3447 TableScan: test
3448 Projection: test2.a, test2.b, test2.c
3449 TableScan: test2
3450 ",
3451 );
3452 assert_optimized_plan_equal!(
3453 plan,
3454 @r"
3455 Full Join: test.a = test2.a Filter: test.a > UInt32(1) AND test.b < test2.b AND test2.c > UInt32(4)
3456 Projection: test.a, test.b, test.c
3457 TableScan: test
3458 Projection: test2.a, test2.b, test2.c
3459 TableScan: test2
3460 "
3461 )
3462 }
3463
3464 struct PushDownProvider {
3465 pub filter_support: TableProviderFilterPushDown,
3466 }
3467
3468 #[async_trait]
3469 impl TableSource for PushDownProvider {
3470 fn schema(&self) -> SchemaRef {
3471 Arc::new(Schema::new(vec![
3472 Field::new("a", DataType::Int32, true),
3473 Field::new("b", DataType::Int32, true),
3474 ]))
3475 }
3476
3477 fn table_type(&self) -> TableType {
3478 TableType::Base
3479 }
3480
3481 fn supports_filters_pushdown(
3482 &self,
3483 filters: &[&Expr],
3484 ) -> Result<Vec<TableProviderFilterPushDown>> {
3485 Ok((0..filters.len())
3486 .map(|_| self.filter_support.clone())
3487 .collect())
3488 }
3489 }
3490
3491 fn table_scan_with_pushdown_provider_builder(
3492 filter_support: TableProviderFilterPushDown,
3493 filters: Vec<Expr>,
3494 projection: Option<Vec<usize>>,
3495 ) -> Result<LogicalPlanBuilder> {
3496 let test_provider = PushDownProvider { filter_support };
3497
3498 let table_scan = LogicalPlan::TableScan(TableScan {
3499 table_name: "test".into(),
3500 filters,
3501 projected_schema: Arc::new(DFSchema::try_from(test_provider.schema())?),
3502 projection,
3503 source: Arc::new(test_provider),
3504 fetch: None,
3505 skip: None,
3506 statistics_requests: Box::default(),
3507 });
3508
3509 Ok(LogicalPlanBuilder::from(table_scan))
3510 }
3511
3512 fn table_scan_with_pushdown_provider(
3513 filter_support: TableProviderFilterPushDown,
3514 ) -> Result<LogicalPlan> {
3515 table_scan_with_pushdown_provider_builder(filter_support, vec![], None)?
3516 .filter(col("a").eq(lit(1i64)))?
3517 .build()
3518 }
3519
3520 #[test]
3521 fn filter_with_table_provider_exact() -> Result<()> {
3522 let plan = table_scan_with_pushdown_provider(TableProviderFilterPushDown::Exact)?;
3523
3524 assert_optimized_plan_equal!(
3525 plan,
3526 @"TableScan: test, full_filters=[a = Int64(1)]"
3527 )
3528 }
3529
3530 #[test]
3531 fn filter_with_table_provider_inexact() -> Result<()> {
3532 let plan =
3533 table_scan_with_pushdown_provider(TableProviderFilterPushDown::Inexact)?;
3534
3535 assert_optimized_plan_equal!(
3536 plan,
3537 @r"
3538 Filter: a = Int64(1)
3539 TableScan: test, partial_filters=[a = Int64(1)]
3540 "
3541 )
3542 }
3543
3544 #[test]
3545 fn filter_with_table_provider_multiple_invocations() -> Result<()> {
3546 let plan =
3547 table_scan_with_pushdown_provider(TableProviderFilterPushDown::Inexact)?;
3548
3549 let optimized = PushDownFilter::new()
3550 .rewrite(plan, &OptimizerContext::new())
3551 .expect("failed to optimize plan");
3552 assert!(optimized.transformed);
3553 assert_plan_not_transformed!(optimized.data.clone());
3554
3555 assert_optimized_plan_equal!(
3558 optimized.data,
3559 @r"
3560 Filter: a = Int64(1)
3561 TableScan: test, partial_filters=[a = Int64(1)]
3562 "
3563 )
3564 }
3565
3566 #[test]
3567 fn filter_with_table_provider_unsupported() -> Result<()> {
3568 let plan =
3569 table_scan_with_pushdown_provider(TableProviderFilterPushDown::Unsupported)?;
3570 assert_plan_not_transformed!(plan.clone());
3571
3572 assert_optimized_plan_equal!(
3573 plan,
3574 @r"
3575 Filter: a = Int64(1)
3576 TableScan: test
3577 "
3578 )
3579 }
3580
3581 #[test]
3582 fn multi_combined_filter() -> Result<()> {
3583 let plan = table_scan_with_pushdown_provider_builder(
3584 TableProviderFilterPushDown::Inexact,
3585 vec![col("a").eq(lit(10i64)), col("b").gt(lit(11i64))],
3586 Some(vec![0]),
3587 )?
3588 .filter(and(col("a").eq(lit(10i64)), col("b").gt(lit(11i64))))?
3589 .project(vec![col("a"), col("b")])?
3590 .build()?;
3591
3592 assert_optimized_plan_equal!(
3593 plan,
3594 @r"
3595 Projection: a, b
3596 Filter: a = Int64(10) AND b > Int64(11)
3597 TableScan: test projection=[a], partial_filters=[a = Int64(10), b > Int64(11)]
3598 "
3599 )
3600 }
3601
3602 #[test]
3603 fn multi_combined_two_filters() -> Result<()> {
3604 let plan = table_scan_with_pushdown_provider_builder(
3605 TableProviderFilterPushDown::Inexact,
3606 vec![col("a").eq(lit(10i64)), col("b").gt(lit(11i64))],
3607 Some(vec![0]),
3608 )?
3609 .filter(col("a").eq(lit(10i64)))?
3610 .filter(col("b").gt(lit(11i64)))?
3611 .project(vec![col("a"), col("b")])?
3612 .build()?;
3613
3614 assert_optimized_plan_equal!(
3615 plan,
3616 @r"
3617 Projection: a, b
3618 Filter: a = Int64(10) AND b > Int64(11)
3619 TableScan: test projection=[a], partial_filters=[a = Int64(10), b > Int64(11)]
3620 "
3621 )
3622 }
3623
3624 #[test]
3625 fn multi_combined_filter_exact() -> Result<()> {
3626 let plan = table_scan_with_pushdown_provider_builder(
3627 TableProviderFilterPushDown::Exact,
3628 vec![],
3629 Some(vec![0]),
3630 )?
3631 .filter(and(col("a").eq(lit(10i64)), col("b").gt(lit(11i64))))?
3632 .project(vec![col("a"), col("b")])?
3633 .build()?;
3634
3635 assert_optimized_plan_equal!(
3636 plan,
3637 @r"
3638 Projection: a, b
3639 TableScan: test projection=[a], full_filters=[a = Int64(10), b > Int64(11)]
3640 "
3641 )
3642 }
3643
3644 #[test]
3645 fn multi_combined_two_filters_exact() -> Result<()> {
3646 let plan = table_scan_with_pushdown_provider_builder(
3647 TableProviderFilterPushDown::Exact,
3648 vec![],
3649 Some(vec![0]),
3650 )?
3651 .filter(col("a").eq(lit(10i64)))?
3652 .filter(col("b").gt(lit(11i64)))?
3653 .project(vec![col("a"), col("b")])?
3654 .build()?;
3655
3656 assert_optimized_plan_equal!(
3657 plan,
3658 @r"
3659 Projection: a, b
3660 TableScan: test projection=[a], full_filters=[a = Int64(10), b > Int64(11)]
3661 "
3662 )
3663 }
3664
3665 #[test]
3666 fn test_filter_with_alias() -> Result<()> {
3667 let table_scan = test_table_scan()?;
3671 let plan = LogicalPlanBuilder::from(table_scan)
3672 .project(vec![col("a").alias("b"), col("c")])?
3673 .filter(and(col("b").gt(lit(10i64)), col("c").gt(lit(10i64))))?
3674 .build()?;
3675
3676 assert_snapshot!(plan,
3678 @r"
3679 Filter: b > Int64(10) AND test.c > Int64(10)
3680 Projection: test.a AS b, test.c
3681 TableScan: test
3682 ",
3683 );
3684 assert_optimized_plan_equal!(
3686 plan,
3687 @r"
3688 Projection: test.a AS b, test.c
3689 TableScan: test, full_filters=[test.a > Int64(10), test.c > Int64(10)]
3690 "
3691 )
3692 }
3693
3694 #[test]
3695 fn test_filter_with_alias_2() -> Result<()> {
3696 let table_scan = test_table_scan()?;
3700 let plan = LogicalPlanBuilder::from(table_scan)
3701 .project(vec![col("a").alias("b"), col("c")])?
3702 .project(vec![col("b"), col("c")])?
3703 .filter(and(col("b").gt(lit(10i64)), col("c").gt(lit(10i64))))?
3704 .build()?;
3705
3706 assert_snapshot!(plan,
3708 @r"
3709 Filter: b > Int64(10) AND test.c > Int64(10)
3710 Projection: b, test.c
3711 Projection: test.a AS b, test.c
3712 TableScan: test
3713 ",
3714 );
3715 assert_optimized_plan_equal!(
3717 plan,
3718 @r"
3719 Projection: b, test.c
3720 Projection: test.a AS b, test.c
3721 TableScan: test, full_filters=[test.a > Int64(10), test.c > Int64(10)]
3722 "
3723 )
3724 }
3725
3726 #[test]
3727 fn test_filter_with_multi_alias() -> Result<()> {
3728 let table_scan = test_table_scan()?;
3729 let plan = LogicalPlanBuilder::from(table_scan)
3730 .project(vec![col("a").alias("b"), col("c").alias("d")])?
3731 .filter(and(col("b").gt(lit(10i64)), col("d").gt(lit(10i64))))?
3732 .build()?;
3733
3734 assert_snapshot!(plan,
3736 @r"
3737 Filter: b > Int64(10) AND d > Int64(10)
3738 Projection: test.a AS b, test.c AS d
3739 TableScan: test
3740 ",
3741 );
3742 assert_optimized_plan_equal!(
3744 plan,
3745 @r"
3746 Projection: test.a AS b, test.c AS d
3747 TableScan: test, full_filters=[test.a > Int64(10), test.c > Int64(10)]
3748 "
3749 )
3750 }
3751
3752 #[test]
3754 fn join_filter_with_alias() -> Result<()> {
3755 let table_scan = test_table_scan()?;
3756 let left = LogicalPlanBuilder::from(table_scan)
3757 .project(vec![col("a").alias("c")])?
3758 .build()?;
3759 let right_table_scan = test_table_scan_with_name("test2")?;
3760 let right = LogicalPlanBuilder::from(right_table_scan)
3761 .project(vec![col("b").alias("d")])?
3762 .build()?;
3763 let filter = col("c").gt(lit(1u32));
3764 let plan = LogicalPlanBuilder::from(left)
3765 .join(
3766 right,
3767 JoinType::Inner,
3768 (vec![Column::from_name("c")], vec![Column::from_name("d")]),
3769 Some(filter),
3770 )?
3771 .build()?;
3772
3773 assert_snapshot!(plan,
3774 @r"
3775 Inner Join: c = d Filter: c > UInt32(1)
3776 Projection: test.a AS c
3777 TableScan: test
3778 Projection: test2.b AS d
3779 TableScan: test2
3780 ",
3781 );
3782 assert_optimized_plan_equal!(
3784 plan,
3785 @r"
3786 Inner Join: c = d
3787 Projection: test.a AS c
3788 TableScan: test, full_filters=[test.a > UInt32(1)]
3789 Projection: test2.b AS d
3790 TableScan: test2, full_filters=[test2.b > UInt32(1)]
3791 "
3792 )
3793 }
3794
3795 #[test]
3796 fn test_in_filter_with_alias() -> Result<()> {
3797 let table_scan = test_table_scan()?;
3801 let filter_value = vec![lit(1u32), lit(2u32), lit(3u32), lit(4u32)];
3802 let plan = LogicalPlanBuilder::from(table_scan)
3803 .project(vec![col("a").alias("b"), col("c")])?
3804 .filter(in_list(col("b"), filter_value, false))?
3805 .build()?;
3806
3807 assert_snapshot!(plan,
3809 @r"
3810 Filter: b IN ([UInt32(1), UInt32(2), UInt32(3), UInt32(4)])
3811 Projection: test.a AS b, test.c
3812 TableScan: test
3813 ",
3814 );
3815 assert_optimized_plan_equal!(
3817 plan,
3818 @r"
3819 Projection: test.a AS b, test.c
3820 TableScan: test, full_filters=[test.a IN ([UInt32(1), UInt32(2), UInt32(3), UInt32(4)])]
3821 "
3822 )
3823 }
3824
3825 #[test]
3826 fn test_in_filter_with_alias_2() -> Result<()> {
3827 let table_scan = test_table_scan()?;
3831 let filter_value = vec![lit(1u32), lit(2u32), lit(3u32), lit(4u32)];
3832 let plan = LogicalPlanBuilder::from(table_scan)
3833 .project(vec![col("a").alias("b"), col("c")])?
3834 .project(vec![col("b"), col("c")])?
3835 .filter(in_list(col("b"), filter_value, false))?
3836 .build()?;
3837
3838 assert_snapshot!(plan,
3840 @r"
3841 Filter: b IN ([UInt32(1), UInt32(2), UInt32(3), UInt32(4)])
3842 Projection: b, test.c
3843 Projection: test.a AS b, test.c
3844 TableScan: test
3845 ",
3846 );
3847 assert_optimized_plan_equal!(
3849 plan,
3850 @r"
3851 Projection: b, test.c
3852 Projection: test.a AS b, test.c
3853 TableScan: test, full_filters=[test.a IN ([UInt32(1), UInt32(2), UInt32(3), UInt32(4)])]
3854 "
3855 )
3856 }
3857
3858 #[test]
3859 fn test_in_subquery_with_alias() -> Result<()> {
3860 let table_scan = test_table_scan()?;
3863 let table_scan_sq = test_table_scan_with_name("sq")?;
3864 let subplan = Arc::new(
3865 LogicalPlanBuilder::from(table_scan_sq)
3866 .project(vec![col("c")])?
3867 .build()?,
3868 );
3869 let plan = LogicalPlanBuilder::from(table_scan)
3870 .project(vec![col("a").alias("b"), col("c")])?
3871 .filter(in_subquery(col("b"), subplan))?
3872 .build()?;
3873
3874 assert_snapshot!(plan,
3876 @r"
3877 Filter: b IN (<subquery>)
3878 Subquery:
3879 Projection: sq.c
3880 TableScan: sq
3881 Projection: test.a AS b, test.c
3882 TableScan: test
3883 ",
3884 );
3885 assert_optimized_plan_equal!(
3887 plan,
3888 @r"
3889 Projection: test.a AS b, test.c
3890 TableScan: test, full_filters=[test.a IN (<subquery>)]
3891 Subquery:
3892 Projection: sq.c
3893 TableScan: sq
3894 "
3895 )
3896 }
3897
3898 #[test]
3899 fn test_propagation_of_optimized_inner_filters_with_projections() -> Result<()> {
3900 let plan = LogicalPlanBuilder::empty(true)
3902 .project(vec![lit(0i64).alias("a")])?
3903 .alias("b")?
3904 .project(vec![col("b.a")])?
3905 .alias("b")?
3906 .filter(col("b.a").eq(lit(1i64)))?
3907 .project(vec![col("b.a")])?
3908 .build()?;
3909
3910 assert_snapshot!(plan,
3911 @r"
3912 Projection: b.a
3913 Filter: b.a = Int64(1)
3914 SubqueryAlias: b
3915 Projection: b.a
3916 SubqueryAlias: b
3917 Projection: Int64(0) AS a
3918 EmptyRelation: rows=1
3919 ",
3920 );
3921 assert_optimized_plan_equal!(
3924 plan,
3925 @r"
3926 Projection: b.a
3927 SubqueryAlias: b
3928 Projection: b.a
3929 SubqueryAlias: b
3930 Projection: Int64(0) AS a
3931 Filter: Int64(0) = Int64(1)
3932 EmptyRelation: rows=1
3933 "
3934 )
3935 }
3936
3937 #[test]
3938 fn test_crossjoin_with_or_clause() -> Result<()> {
3939 let table_scan = test_table_scan()?;
3941 let left = LogicalPlanBuilder::from(table_scan)
3942 .project(vec![col("a"), col("b"), col("c")])?
3943 .build()?;
3944 let right_table_scan = test_table_scan_with_name("test1")?;
3945 let right = LogicalPlanBuilder::from(right_table_scan)
3946 .project(vec![col("a").alias("d"), col("a").alias("e")])?
3947 .build()?;
3948 let filter = or(
3949 and(col("a").eq(col("d")), col("b").gt(lit(1u32))),
3950 and(col("b").eq(col("e")), col("c").lt(lit(10u32))),
3951 );
3952 let plan = LogicalPlanBuilder::from(left)
3953 .cross_join(right)?
3954 .filter(filter)?
3955 .build()?;
3956
3957 assert_optimized_plan_eq_with_rewrite_predicate!(plan.clone(), @r"
3958 Inner Join: Filter: test.a = d AND test.b > UInt32(1) OR test.b = e AND test.c < UInt32(10)
3959 Projection: test.a, test.b, test.c
3960 TableScan: test, full_filters=[test.b > UInt32(1) OR test.c < UInt32(10)]
3961 Projection: test1.a AS d, test1.a AS e
3962 TableScan: test1
3963 ")?;
3964
3965 let optimized_plan = PushDownFilter::new()
3968 .rewrite(plan, &OptimizerContext::new())
3969 .expect("failed to optimize plan")
3970 .data;
3971 assert_optimized_plan_equal!(
3972 optimized_plan,
3973 @r"
3974 Inner Join: Filter: test.a = d AND test.b > UInt32(1) OR test.b = e AND test.c < UInt32(10)
3975 Projection: test.a, test.b, test.c
3976 TableScan: test, full_filters=[test.b > UInt32(1) OR test.c < UInt32(10)]
3977 Projection: test1.a AS d, test1.a AS e
3978 TableScan: test1
3979 "
3980 )
3981 }
3982
3983 #[test]
3984 fn left_semi_join() -> Result<()> {
3985 let left = test_table_scan_with_name("test1")?;
3986 let right_table_scan = test_table_scan_with_name("test2")?;
3987 let right = LogicalPlanBuilder::from(right_table_scan)
3988 .project(vec![col("a"), col("b")])?
3989 .build()?;
3990 let plan = LogicalPlanBuilder::from(left)
3991 .join(
3992 right,
3993 JoinType::LeftSemi,
3994 (
3995 vec![Column::from_qualified_name("test1.a")],
3996 vec![Column::from_qualified_name("test2.a")],
3997 ),
3998 None,
3999 )?
4000 .filter(col("test2.a").lt_eq(lit(1i64)))?
4001 .build()?;
4002
4003 assert_snapshot!(plan,
4005 @r"
4006 Filter: test2.a <= Int64(1)
4007 LeftSemi Join: test1.a = test2.a
4008 TableScan: test1
4009 Projection: test2.a, test2.b
4010 TableScan: test2
4011 ",
4012 );
4013 assert_optimized_plan_equal!(
4015 plan,
4016 @r"
4017 Filter: test2.a <= Int64(1)
4018 LeftSemi Join: test1.a = test2.a
4019 TableScan: test1, full_filters=[test1.a <= Int64(1)]
4020 Projection: test2.a, test2.b
4021 TableScan: test2
4022 "
4023 )
4024 }
4025
4026 #[test]
4027 fn left_semi_join_with_filters() -> Result<()> {
4028 let left = test_table_scan_with_name("test1")?;
4029 let right_table_scan = test_table_scan_with_name("test2")?;
4030 let right = LogicalPlanBuilder::from(right_table_scan)
4031 .project(vec![col("a"), col("b")])?
4032 .build()?;
4033 let plan = LogicalPlanBuilder::from(left)
4034 .join(
4035 right,
4036 JoinType::LeftSemi,
4037 (
4038 vec![Column::from_qualified_name("test1.a")],
4039 vec![Column::from_qualified_name("test2.a")],
4040 ),
4041 Some(
4042 col("test1.b")
4043 .gt(lit(1u32))
4044 .and(col("test2.b").gt(lit(2u32))),
4045 ),
4046 )?
4047 .build()?;
4048
4049 assert_snapshot!(plan,
4051 @r"
4052 LeftSemi Join: test1.a = test2.a Filter: test1.b > UInt32(1) AND test2.b > UInt32(2)
4053 TableScan: test1
4054 Projection: test2.a, test2.b
4055 TableScan: test2
4056 ",
4057 );
4058 assert_optimized_plan_equal!(
4060 plan,
4061 @r"
4062 LeftSemi Join: test1.a = test2.a
4063 TableScan: test1, full_filters=[test1.b > UInt32(1)]
4064 Projection: test2.a, test2.b
4065 TableScan: test2, full_filters=[test2.b > UInt32(2)]
4066 "
4067 )
4068 }
4069
4070 #[test]
4071 fn right_semi_join() -> Result<()> {
4072 let left = test_table_scan_with_name("test1")?;
4073 let right_table_scan = test_table_scan_with_name("test2")?;
4074 let right = LogicalPlanBuilder::from(right_table_scan)
4075 .project(vec![col("a"), col("b")])?
4076 .build()?;
4077 let plan = LogicalPlanBuilder::from(left)
4078 .join(
4079 right,
4080 JoinType::RightSemi,
4081 (
4082 vec![Column::from_qualified_name("test1.a")],
4083 vec![Column::from_qualified_name("test2.a")],
4084 ),
4085 None,
4086 )?
4087 .filter(col("test1.a").lt_eq(lit(1i64)))?
4088 .build()?;
4089
4090 assert_snapshot!(plan,
4092 @r"
4093 Filter: test1.a <= Int64(1)
4094 RightSemi Join: test1.a = test2.a
4095 TableScan: test1
4096 Projection: test2.a, test2.b
4097 TableScan: test2
4098 ",
4099 );
4100 assert_optimized_plan_equal!(
4102 plan,
4103 @r"
4104 Filter: test1.a <= Int64(1)
4105 RightSemi Join: test1.a = test2.a
4106 TableScan: test1
4107 Projection: test2.a, test2.b
4108 TableScan: test2, full_filters=[test2.a <= Int64(1)]
4109 "
4110 )
4111 }
4112
4113 #[test]
4114 fn right_semi_join_with_filters() -> Result<()> {
4115 let left = test_table_scan_with_name("test1")?;
4116 let right_table_scan = test_table_scan_with_name("test2")?;
4117 let right = LogicalPlanBuilder::from(right_table_scan)
4118 .project(vec![col("a"), col("b")])?
4119 .build()?;
4120 let plan = LogicalPlanBuilder::from(left)
4121 .join(
4122 right,
4123 JoinType::RightSemi,
4124 (
4125 vec![Column::from_qualified_name("test1.a")],
4126 vec![Column::from_qualified_name("test2.a")],
4127 ),
4128 Some(
4129 col("test1.b")
4130 .gt(lit(1u32))
4131 .and(col("test2.b").gt(lit(2u32))),
4132 ),
4133 )?
4134 .build()?;
4135
4136 assert_snapshot!(plan,
4138 @r"
4139 RightSemi Join: test1.a = test2.a Filter: test1.b > UInt32(1) AND test2.b > UInt32(2)
4140 TableScan: test1
4141 Projection: test2.a, test2.b
4142 TableScan: test2
4143 ",
4144 );
4145 assert_optimized_plan_equal!(
4147 plan,
4148 @r"
4149 RightSemi Join: test1.a = test2.a
4150 TableScan: test1, full_filters=[test1.b > UInt32(1)]
4151 Projection: test2.a, test2.b
4152 TableScan: test2, full_filters=[test2.b > UInt32(2)]
4153 "
4154 )
4155 }
4156
4157 #[test]
4158 fn left_anti_join() -> Result<()> {
4159 let table_scan = test_table_scan_with_name("test1")?;
4160 let left = LogicalPlanBuilder::from(table_scan)
4161 .project(vec![col("a"), col("b")])?
4162 .build()?;
4163 let right_table_scan = test_table_scan_with_name("test2")?;
4164 let right = LogicalPlanBuilder::from(right_table_scan)
4165 .project(vec![col("a"), col("b")])?
4166 .build()?;
4167 let plan = LogicalPlanBuilder::from(left)
4168 .join(
4169 right,
4170 JoinType::LeftAnti,
4171 (
4172 vec![Column::from_qualified_name("test1.a")],
4173 vec![Column::from_qualified_name("test2.a")],
4174 ),
4175 None,
4176 )?
4177 .filter(col("test2.a").gt(lit(2u32)))?
4178 .build()?;
4179
4180 assert_snapshot!(plan,
4182 @r"
4183 Filter: test2.a > UInt32(2)
4184 LeftAnti Join: test1.a = test2.a
4185 Projection: test1.a, test1.b
4186 TableScan: test1
4187 Projection: test2.a, test2.b
4188 TableScan: test2
4189 ",
4190 );
4191 assert_optimized_plan_equal!(
4193 plan,
4194 @r"
4195 Filter: test2.a > UInt32(2)
4196 LeftAnti Join: test1.a = test2.a
4197 Projection: test1.a, test1.b
4198 TableScan: test1, full_filters=[test1.a > UInt32(2)]
4199 Projection: test2.a, test2.b
4200 TableScan: test2
4201 "
4202 )
4203 }
4204
4205 #[test]
4211 fn null_aware_left_anti_join_no_inferred_pushdown() -> Result<()> {
4212 let table_scan = test_table_scan_with_name("test1")?;
4213 let left = LogicalPlanBuilder::from(table_scan)
4214 .project(vec![col("a"), col("b")])?
4215 .build()?;
4216 let right_table_scan = test_table_scan_with_name("test2")?;
4217 let right = LogicalPlanBuilder::from(right_table_scan)
4218 .project(vec![col("a"), col("b")])?
4219 .build()?;
4220 let plan = LogicalPlanBuilder::from(left)
4221 .join_detailed_with_options(
4222 right,
4223 JoinType::LeftAnti,
4224 (
4225 vec![Column::from_qualified_name("test1.a")],
4226 vec![Column::from_qualified_name("test2.a")],
4227 ),
4228 None,
4229 datafusion_common::NullEquality::NullEqualsNothing,
4230 true,
4231 )?
4232 .filter(col("test1.a").gt(lit(2u32)))?
4233 .build()?;
4234
4235 assert_optimized_plan_equal!(
4239 plan,
4240 @r"
4241 LeftAnti Join: test1.a = test2.a null_aware
4242 Projection: test1.a, test1.b
4243 TableScan: test1, full_filters=[test1.a > UInt32(2)]
4244 Projection: test2.a, test2.b
4245 TableScan: test2
4246 "
4247 )
4248 }
4249
4250 #[test]
4256 fn null_aware_left_anti_join_keeps_right_only_join_filter() -> Result<()> {
4257 let table_scan = test_table_scan_with_name("test1")?;
4258 let left = LogicalPlanBuilder::from(table_scan)
4259 .project(vec![col("a"), col("b")])?
4260 .build()?;
4261 let right_table_scan = test_table_scan_with_name("test2")?;
4262 let right = LogicalPlanBuilder::from(right_table_scan)
4263 .project(vec![col("a"), col("b")])?
4264 .build()?;
4265 let plan = LogicalPlanBuilder::from(left)
4266 .join_detailed_with_options(
4267 right,
4268 JoinType::LeftAnti,
4269 (Vec::<Column>::new(), Vec::<Column>::new()),
4270 Some(lit(3u32).eq(col("test2.a"))),
4271 datafusion_common::NullEquality::NullEqualsNothing,
4272 true,
4273 )?
4274 .build()?;
4275
4276 assert_optimized_plan_equal!(
4279 plan,
4280 @r"
4281 LeftAnti Join: Filter: UInt32(3) = test2.a null_aware
4282 Projection: test1.a, test1.b
4283 TableScan: test1
4284 Projection: test2.a, test2.b
4285 TableScan: test2
4286 "
4287 )
4288 }
4289
4290 #[test]
4291 fn left_anti_join_with_filters() -> Result<()> {
4292 let table_scan = test_table_scan_with_name("test1")?;
4293 let left = LogicalPlanBuilder::from(table_scan)
4294 .project(vec![col("a"), col("b")])?
4295 .build()?;
4296 let right_table_scan = test_table_scan_with_name("test2")?;
4297 let right = LogicalPlanBuilder::from(right_table_scan)
4298 .project(vec![col("a"), col("b")])?
4299 .build()?;
4300 let plan = LogicalPlanBuilder::from(left)
4301 .join(
4302 right,
4303 JoinType::LeftAnti,
4304 (
4305 vec![Column::from_qualified_name("test1.a")],
4306 vec![Column::from_qualified_name("test2.a")],
4307 ),
4308 Some(
4309 col("test1.b")
4310 .gt(lit(1u32))
4311 .and(col("test2.b").gt(lit(2u32))),
4312 ),
4313 )?
4314 .build()?;
4315
4316 assert_snapshot!(plan,
4318 @r"
4319 LeftAnti Join: test1.a = test2.a Filter: test1.b > UInt32(1) AND test2.b > UInt32(2)
4320 Projection: test1.a, test1.b
4321 TableScan: test1
4322 Projection: test2.a, test2.b
4323 TableScan: test2
4324 ",
4325 );
4326 assert_optimized_plan_equal!(
4328 plan,
4329 @r"
4330 LeftAnti Join: test1.a = test2.a Filter: test1.b > UInt32(1)
4331 Projection: test1.a, test1.b
4332 TableScan: test1
4333 Projection: test2.a, test2.b
4334 TableScan: test2, full_filters=[test2.b > UInt32(2)]
4335 "
4336 )
4337 }
4338
4339 #[test]
4340 fn right_anti_join() -> Result<()> {
4341 let table_scan = test_table_scan_with_name("test1")?;
4342 let left = LogicalPlanBuilder::from(table_scan)
4343 .project(vec![col("a"), col("b")])?
4344 .build()?;
4345 let right_table_scan = test_table_scan_with_name("test2")?;
4346 let right = LogicalPlanBuilder::from(right_table_scan)
4347 .project(vec![col("a"), col("b")])?
4348 .build()?;
4349 let plan = LogicalPlanBuilder::from(left)
4350 .join(
4351 right,
4352 JoinType::RightAnti,
4353 (
4354 vec![Column::from_qualified_name("test1.a")],
4355 vec![Column::from_qualified_name("test2.a")],
4356 ),
4357 None,
4358 )?
4359 .filter(col("test1.a").gt(lit(2u32)))?
4360 .build()?;
4361
4362 assert_snapshot!(plan,
4364 @r"
4365 Filter: test1.a > UInt32(2)
4366 RightAnti Join: test1.a = test2.a
4367 Projection: test1.a, test1.b
4368 TableScan: test1
4369 Projection: test2.a, test2.b
4370 TableScan: test2
4371 ",
4372 );
4373 assert_optimized_plan_equal!(
4375 plan,
4376 @r"
4377 Filter: test1.a > UInt32(2)
4378 RightAnti Join: test1.a = test2.a
4379 Projection: test1.a, test1.b
4380 TableScan: test1
4381 Projection: test2.a, test2.b
4382 TableScan: test2, full_filters=[test2.a > UInt32(2)]
4383 "
4384 )
4385 }
4386
4387 #[test]
4388 fn right_anti_join_with_filters() -> Result<()> {
4389 let table_scan = test_table_scan_with_name("test1")?;
4390 let left = LogicalPlanBuilder::from(table_scan)
4391 .project(vec![col("a"), col("b")])?
4392 .build()?;
4393 let right_table_scan = test_table_scan_with_name("test2")?;
4394 let right = LogicalPlanBuilder::from(right_table_scan)
4395 .project(vec![col("a"), col("b")])?
4396 .build()?;
4397 let plan = LogicalPlanBuilder::from(left)
4398 .join(
4399 right,
4400 JoinType::RightAnti,
4401 (
4402 vec![Column::from_qualified_name("test1.a")],
4403 vec![Column::from_qualified_name("test2.a")],
4404 ),
4405 Some(
4406 col("test1.b")
4407 .gt(lit(1u32))
4408 .and(col("test2.b").gt(lit(2u32))),
4409 ),
4410 )?
4411 .build()?;
4412
4413 assert_snapshot!(plan,
4415 @r"
4416 RightAnti Join: test1.a = test2.a Filter: test1.b > UInt32(1) AND test2.b > UInt32(2)
4417 Projection: test1.a, test1.b
4418 TableScan: test1
4419 Projection: test2.a, test2.b
4420 TableScan: test2
4421 ",
4422 );
4423 assert_optimized_plan_equal!(
4425 plan,
4426 @r"
4427 RightAnti Join: test1.a = test2.a Filter: test2.b > UInt32(2)
4428 Projection: test1.a, test1.b
4429 TableScan: test1, full_filters=[test1.b > UInt32(1)]
4430 Projection: test2.a, test2.b
4431 TableScan: test2
4432 "
4433 )
4434 }
4435
4436 #[derive(Debug, PartialEq, Eq, Hash)]
4437 struct TestScalarUDF {
4438 signature: Signature,
4439 }
4440
4441 impl ScalarUDFImpl for TestScalarUDF {
4442 fn name(&self) -> &str {
4443 "TestScalarUDF"
4444 }
4445
4446 fn signature(&self) -> &Signature {
4447 &self.signature
4448 }
4449
4450 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
4451 Ok(DataType::Int32)
4452 }
4453
4454 fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
4455 Ok(ColumnarValue::Scalar(ScalarValue::from(1)))
4456 }
4457 }
4458
4459 #[test]
4460 fn test_push_down_volatile_function_in_aggregate() -> Result<()> {
4461 let table_scan = test_table_scan_with_name("test1")?;
4463 let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4464 signature: Signature::exact(vec![], Volatility::Volatile),
4465 });
4466 let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4467
4468 let plan = LogicalPlanBuilder::from(table_scan)
4469 .aggregate(vec![col("a")], vec![sum(col("b"))])?
4470 .project(vec![col("a"), sum(col("b")), add(expr, lit(1)).alias("r")])?
4471 .alias("t")?
4472 .filter(col("t.a").gt(lit(5)).and(col("t.r").gt(lit(0.5))))?
4473 .project(vec![col("t.a"), col("t.r")])?
4474 .build()?;
4475
4476 assert_snapshot!(plan,
4477 @r"
4478 Projection: t.a, t.r
4479 Filter: t.a > Int32(5) AND t.r > Float64(0.5)
4480 SubqueryAlias: t
4481 Projection: test1.a, sum(test1.b), TestScalarUDF() + Int32(1) AS r
4482 Aggregate: groupBy=[[test1.a]], aggr=[[sum(test1.b)]]
4483 TableScan: test1
4484 ",
4485 );
4486 assert_optimized_plan_equal!(
4487 plan,
4488 @r"
4489 Projection: t.a, t.r
4490 SubqueryAlias: t
4491 Filter: r > Float64(0.5)
4492 Projection: test1.a, sum(test1.b), TestScalarUDF() + Int32(1) AS r
4493 Aggregate: groupBy=[[test1.a]], aggr=[[sum(test1.b)]]
4494 TableScan: test1, full_filters=[test1.a > Int32(5)]
4495 "
4496 )
4497 }
4498
4499 #[test]
4500 fn test_filter_on_volatile_group_key_not_pushed_below_aggregate() -> Result<()> {
4501 let table_scan = test_table_scan_with_name("test1")?;
4503 let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4504 signature: Signature::exact(vec![], Volatility::Volatile),
4505 });
4506 let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4507
4508 let plan = LogicalPlanBuilder::from(table_scan)
4509 .aggregate(
4510 vec![col("a"), add(expr, lit(1)).alias("r")],
4511 vec![sum(col("b"))],
4512 )?
4513 .filter(col("a").gt(lit(5)).and(col("r").gt(lit(0.5))))?
4514 .build()?;
4515
4516 assert_optimized_plan_equal!(
4518 plan,
4519 @r"
4520 Filter: r > Float64(0.5)
4521 Aggregate: groupBy=[[test1.a, TestScalarUDF() + Int32(1) AS r]], aggr=[[sum(test1.b)]]
4522 TableScan: test1, full_filters=[test1.a > Int32(5)]
4523 "
4524 )
4525 }
4526
4527 #[test]
4528 fn test_push_down_volatile_function_in_join() -> Result<()> {
4529 let table_scan = test_table_scan_with_name("test1")?;
4531 let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4532 signature: Signature::exact(vec![], Volatility::Volatile),
4533 });
4534 let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4535 let left = LogicalPlanBuilder::from(table_scan).build()?;
4536 let right_table_scan = test_table_scan_with_name("test2")?;
4537 let right = LogicalPlanBuilder::from(right_table_scan).build()?;
4538 let plan = LogicalPlanBuilder::from(left)
4539 .join(
4540 right,
4541 JoinType::Inner,
4542 (
4543 vec![Column::from_qualified_name("test1.a")],
4544 vec![Column::from_qualified_name("test2.a")],
4545 ),
4546 None,
4547 )?
4548 .project(vec![col("test1.a").alias("a"), expr.alias("r")])?
4549 .alias("t")?
4550 .filter(col("t.r").gt(lit(0.8)))?
4551 .project(vec![col("t.a"), col("t.r")])?
4552 .build()?;
4553
4554 assert_snapshot!(plan,
4555 @r"
4556 Projection: t.a, t.r
4557 Filter: t.r > Float64(0.8)
4558 SubqueryAlias: t
4559 Projection: test1.a AS a, TestScalarUDF() AS r
4560 Inner Join: test1.a = test2.a
4561 TableScan: test1
4562 TableScan: test2
4563 ",
4564 );
4565 assert_optimized_plan_equal!(
4566 plan,
4567 @r"
4568 Projection: t.a, t.r
4569 SubqueryAlias: t
4570 Filter: r > Float64(0.8)
4571 Projection: test1.a AS a, TestScalarUDF() AS r
4572 Inner Join: test1.a = test2.a
4573 TableScan: test1
4574 TableScan: test2
4575 "
4576 )
4577 }
4578
4579 #[test]
4580 fn test_push_down_volatile_table_scan() -> Result<()> {
4581 let table_scan = test_table_scan()?;
4583 let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4584 signature: Signature::exact(vec![], Volatility::Volatile),
4585 });
4586 let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4587 let plan = LogicalPlanBuilder::from(table_scan)
4588 .project(vec![col("a"), col("b")])?
4589 .filter(expr.gt(lit(0.1)))?
4590 .build()?;
4591
4592 assert_snapshot!(plan,
4593 @r"
4594 Filter: TestScalarUDF() > Float64(0.1)
4595 Projection: test.a, test.b
4596 TableScan: test
4597 ",
4598 );
4599 assert_optimized_plan_equal!(
4600 plan,
4601 @r"
4602 Projection: test.a, test.b
4603 Filter: TestScalarUDF() > Float64(0.1)
4604 TableScan: test
4605 "
4606 )
4607 }
4608
4609 #[test]
4610 fn test_push_down_volatile_mixed_table_scan() -> Result<()> {
4611 let table_scan = test_table_scan()?;
4613 let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4614 signature: Signature::exact(vec![], Volatility::Volatile),
4615 });
4616 let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4617 let plan = LogicalPlanBuilder::from(table_scan)
4618 .project(vec![col("a"), col("b")])?
4619 .filter(
4620 expr.gt(lit(0.1))
4621 .and(col("t.a").gt(lit(5)))
4622 .and(col("t.b").gt(lit(10))),
4623 )?
4624 .build()?;
4625
4626 assert_snapshot!(plan,
4627 @r"
4628 Filter: TestScalarUDF() > Float64(0.1) AND t.a > Int32(5) AND t.b > Int32(10)
4629 Projection: test.a, test.b
4630 TableScan: test
4631 ",
4632 );
4633 assert_optimized_plan_equal!(
4634 plan,
4635 @r"
4636 Projection: test.a, test.b
4637 Filter: TestScalarUDF() > Float64(0.1)
4638 TableScan: test, full_filters=[t.a > Int32(5), t.b > Int32(10)]
4639 "
4640 )
4641 }
4642
4643 #[test]
4644 fn test_push_down_volatile_mixed_unsupported_table_scan() -> Result<()> {
4645 let fun = ScalarUDF::new_from_impl(TestScalarUDF {
4647 signature: Signature::exact(vec![], Volatility::Volatile),
4648 });
4649 let expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(fun), vec![]));
4650 let plan = table_scan_with_pushdown_provider_builder(
4651 TableProviderFilterPushDown::Unsupported,
4652 vec![],
4653 None,
4654 )?
4655 .project(vec![col("a"), col("b")])?
4656 .filter(
4657 expr.gt(lit(0.1))
4658 .and(col("t.a").gt(lit(5)))
4659 .and(col("t.b").gt(lit(10))),
4660 )?
4661 .build()?;
4662
4663 assert_snapshot!(plan,
4664 @r"
4665 Filter: TestScalarUDF() > Float64(0.1) AND t.a > Int32(5) AND t.b > Int32(10)
4666 Projection: a, b
4667 TableScan: test
4668 ",
4669 );
4670 assert_optimized_plan_equal!(
4671 plan,
4672 @r"
4673 Projection: a, b
4674 Filter: TestScalarUDF() > Float64(0.1) AND t.a > Int32(5) AND t.b > Int32(10)
4675 TableScan: test
4676 "
4677 )
4678 }
4679
4680 #[test]
4681 fn test_push_down_filter_to_user_defined_node() -> Result<()> {
4682 #[derive(Debug, Hash, Eq, PartialEq)]
4684 struct TestUserNode {
4685 schema: DFSchemaRef,
4686 }
4687
4688 impl PartialOrd for TestUserNode {
4689 fn partial_cmp(&self, _other: &Self) -> Option<Ordering> {
4690 None
4691 }
4692 }
4693
4694 impl TestUserNode {
4695 fn new() -> Self {
4696 let schema = Arc::new(
4697 DFSchema::new_with_metadata(
4698 vec![(None, Field::new("a", DataType::Int64, false).into())],
4699 Metadata::new(),
4700 )
4701 .unwrap(),
4702 );
4703
4704 Self { schema }
4705 }
4706 }
4707
4708 impl UserDefinedLogicalNodeCore for TestUserNode {
4709 fn name(&self) -> &str {
4710 "test_node"
4711 }
4712
4713 fn inputs(&self) -> Vec<&LogicalPlan> {
4714 vec![]
4715 }
4716
4717 fn schema(&self) -> &DFSchemaRef {
4718 &self.schema
4719 }
4720
4721 fn expressions(&self) -> Vec<Expr> {
4722 vec![]
4723 }
4724
4725 fn fmt_for_explain(&self, f: &mut Formatter) -> std::fmt::Result {
4726 write!(f, "TestUserNode")
4727 }
4728
4729 fn with_exprs_and_inputs(
4730 &self,
4731 exprs: Vec<Expr>,
4732 inputs: Vec<LogicalPlan>,
4733 ) -> Result<Self> {
4734 assert!(exprs.is_empty());
4735 assert!(inputs.is_empty());
4736 Ok(Self {
4737 schema: Arc::clone(&self.schema),
4738 })
4739 }
4740 }
4741
4742 let node = LogicalPlan::Extension(Extension {
4744 node: Arc::new(TestUserNode::new()),
4745 });
4746
4747 let plan = LogicalPlanBuilder::from(node).filter(lit(false))?.build()?;
4748
4749 assert_snapshot!(plan,
4751 @r"
4752 Filter: Boolean(false)
4753 TestUserNode
4754 ",
4755 );
4756 assert_optimized_plan_equal!(plan, @"EmptyRelation: rows=0")
4758 }
4759
4760 #[test]
4766 fn filter_not_pushed_through_move_towards_leaves_projection() -> Result<()> {
4767 let table_scan = test_table_scan()?;
4768
4769 let proj = LogicalPlanBuilder::from(table_scan)
4771 .project(vec![
4772 leaf_udf_expr(col("a")).alias("val"),
4773 col("b"),
4774 col("c"),
4775 ])?
4776 .build()?;
4777
4778 let plan = LogicalPlanBuilder::from(proj)
4780 .filter(col("val").gt(lit(150i64)))?
4781 .build()?;
4782
4783 assert_optimized_plan_equal!(
4785 plan,
4786 @r"
4787 Filter: val > Int64(150)
4788 Projection: leaf_udf(test.a) AS val, test.b, test.c
4789 TableScan: test
4790 "
4791 )
4792 }
4793
4794 #[test]
4796 fn filter_mixed_predicates_partial_push() -> Result<()> {
4797 let table_scan = test_table_scan()?;
4798
4799 let proj = LogicalPlanBuilder::from(table_scan)
4801 .project(vec![
4802 leaf_udf_expr(col("a")).alias("val"),
4803 col("b"),
4804 col("c"),
4805 ])?
4806 .build()?;
4807
4808 let plan = LogicalPlanBuilder::from(proj)
4810 .filter(col("val").gt(lit(150i64)).and(col("b").gt(lit(5i64))))?
4811 .build()?;
4812
4813 assert_optimized_plan_equal!(
4815 plan,
4816 @r"
4817 Filter: val > Int64(150)
4818 Projection: leaf_udf(test.a) AS val, test.b, test.c
4819 TableScan: test, full_filters=[test.b > Int64(5)]
4820 "
4821 )
4822 }
4823
4824 #[test]
4832 fn filter_not_pushed_through_pure_extraction_projection() -> Result<()> {
4833 let table_scan = test_table_scan()?;
4834
4835 let proj = LogicalPlanBuilder::from(table_scan)
4838 .project(vec![
4839 leaf_udf_expr(col("a")).alias("__datafusion_extracted_1"),
4840 col("b"),
4841 col("c"),
4842 ])?
4843 .build()?;
4844
4845 let plan = LogicalPlanBuilder::from(proj)
4848 .filter(col("b").gt(lit(5i64)))?
4849 .build()?;
4850
4851 assert_optimized_plan_equal!(
4852 plan,
4853 @r"
4854 Filter: test.b > Int64(5)
4855 Projection: leaf_udf(test.a) AS __datafusion_extracted_1, test.b, test.c
4856 TableScan: test
4857 "
4858 )
4859 }
4860
4861 fn rules_that_changed_plan_per_pass(plan: LogicalPlan) -> Result<Vec<Vec<String>>> {
4864 let optimizer = Optimizer::new();
4865 let rules_per_pass = optimizer.rules.len();
4866 let mut previous = plan.display_indent().to_string();
4867 let mut calls = 0;
4868 let mut passes: Vec<Vec<String>> = vec![];
4869 optimizer.optimize(plan, &OptimizerContext::new(), |plan, rule| {
4870 if calls % rules_per_pass == 0 {
4871 passes.push(vec![]);
4872 }
4873 calls += 1;
4874 let current = plan.display_indent().to_string();
4875 if current != previous {
4876 passes.last_mut().unwrap().push(rule.name().to_string());
4877 previous = current;
4878 }
4879 })?;
4880 Ok(passes)
4881 }
4882
4883 #[test]
4891 fn filter_and_extraction_projection_reach_fixed_point() -> Result<()> {
4892 let scan = || {
4893 table_scan_with_pushdown_provider_builder(
4894 TableProviderFilterPushDown::Unsupported,
4895 vec![],
4896 None,
4897 )
4898 };
4899 let simple = scan()?
4900 .filter(col("b").gt(lit(5)))?
4901 .project(vec![leaf_udf_expr(col("a"))])?
4902 .build()?;
4903 let two_filters = scan()?
4905 .filter(col("b").gt(lit(5)))?
4906 .filter(leaf_udf_expr(col("a")).eq(lit(1)))?
4907 .project(vec![leaf_udf_expr(col("a")), col("b")])?
4908 .build()?;
4909
4910 let no_filter = LogicalPlanBuilder::from(test_table_scan()?)
4912 .project(vec![leaf_udf_expr(col("a"))])?
4913 .build()?;
4914
4915 let above_aggregate = LogicalPlanBuilder::from(test_table_scan_with_struct()?)
4917 .aggregate(vec![col("user")], vec![count(lit(1))])?
4918 .project(vec![
4919 leaf_udf_expr(col("user")).is_not_null().alias("has_name"),
4920 col("COUNT(Int32(1))"),
4921 ])?
4922 .build()?;
4923
4924 for plan in [simple, two_filters, no_filter, above_aggregate] {
4925 let passes = rules_that_changed_plan_per_pass(plan)?;
4926 let last = passes.last().unwrap();
4927 assert!(
4928 last.is_empty(),
4929 "rules changed the plan in the last pass: {passes:?}"
4930 );
4931 }
4932 Ok(())
4933 }
4934
4935 #[test]
4938 fn filter_pushed_through_mixed_extraction_projection() -> Result<()> {
4939 let table_scan = test_table_scan()?;
4940
4941 let proj = LogicalPlanBuilder::from(table_scan)
4942 .project(vec![
4943 leaf_udf_expr(col("a")).alias("__datafusion_extracted_1"),
4944 (col("b") + lit(1i64)).alias("b_plus"),
4945 col("c"),
4946 ])?
4947 .build()?;
4948
4949 let plan = LogicalPlanBuilder::from(proj)
4950 .filter(col("c").gt(lit(5i64)))?
4951 .build()?;
4952
4953 assert_optimized_plan_equal!(
4954 plan,
4955 @r"
4956 Projection: leaf_udf(test.a) AS __datafusion_extracted_1, test.b + Int64(1) AS b_plus, test.c
4957 TableScan: test, full_filters=[test.c > Int64(5)]
4958 "
4959 )
4960 }
4961
4962 #[test]
4963 fn filter_not_pushed_down_through_table_scan_with_fetch() -> Result<()> {
4964 let scan = test_table_scan()?;
4965 let scan_with_fetch = match scan {
4966 LogicalPlan::TableScan(scan) => LogicalPlan::TableScan(TableScan {
4967 fetch: Some(10),
4968 ..scan
4969 }),
4970 _ => unreachable!(),
4971 };
4972 let plan = LogicalPlanBuilder::from(scan_with_fetch)
4973 .filter(col("a").gt(lit(10i64)))?
4974 .build()?;
4975 assert_optimized_plan_equal!(
4977 plan,
4978 @r"
4979 Filter: test.a > Int64(10)
4980 TableScan: test, fetch=10
4981 "
4982 )
4983 }
4984
4985 #[test]
4986 fn filter_push_down_through_sort_without_fetch() -> Result<()> {
4987 let table_scan = test_table_scan()?;
4988 let plan = LogicalPlanBuilder::from(table_scan)
4989 .sort(vec![col("a").sort(true, true)])?
4990 .filter(col("a").gt(lit(10i64)))?
4991 .build()?;
4992 assert_optimized_plan_equal!(
4994 plan,
4995 @r"
4996 Sort: test.a ASC NULLS FIRST
4997 TableScan: test, full_filters=[test.a > Int64(10)]
4998 "
4999 )
5000 }
5001
5002 #[test]
5003 fn filter_not_pushed_down_through_sort_with_fetch() -> Result<()> {
5004 let table_scan = test_table_scan()?;
5005 let plan = LogicalPlanBuilder::from(table_scan)
5006 .sort_with_limit(vec![col("a").sort(true, true)], Some(5))?
5007 .filter(col("a").gt(lit(10i64)))?
5008 .build()?;
5009 assert_optimized_plan_equal!(
5012 plan,
5013 @r"
5014 Filter: test.a > Int64(10)
5015 Sort: test.a ASC NULLS FIRST, fetch=5
5016 TableScan: test
5017 "
5018 )
5019 }
5020}