1use std::cmp::Ordering;
8use std::collections::{BTreeSet, HashMap, HashSet};
9use std::fmt::{self, Debug, Display, Formatter};
10use std::hash::{Hash, Hasher};
11use std::sync::{Arc, LazyLock};
12
13use super::dml::CopyTo;
14use super::invariants::{
15 InvariantLevel, assert_always_invariants_at_current_node,
16 assert_executable_invariants,
17};
18use super::{DdlStatement, information_schema};
19use crate::builder::{unique_field_aliases, unnest_with_options};
20use crate::expr::{
21 Alias, Placeholder, Sort as SortExpr, WindowFunction, WindowFunctionParams,
22};
23use crate::expr_rewriter::{
24 NamePreserver, create_col_from_scalar_expr, normalize_cols, normalize_sorts,
25};
26use crate::logical_plan::display::{GraphvizVisitor, IndentVisitor};
27use crate::logical_plan::extension::UserDefinedLogicalNode;
28use crate::logical_plan::materialized_cte::{
29 MaterializedCte, MaterializedCtePlan, MaterializedCteScan,
30};
31use crate::logical_plan::{DmlStatement, Statement, WriteOp};
32use crate::type_coercion::other::coerce_union_type;
33use crate::utils::{
34 check_aggregate_and_window_nesting, check_no_window_functions,
35 enumerate_grouping_sets, expr_to_columns, exprlist_to_fields,
36 find_out_reference_exprs, get_unnested_list_field, grouping_set_expr_count,
37 grouping_set_to_exprlist, merge_schema, passthrough_field_index, split_conjunction,
38};
39use crate::{
40 BinaryExpr, CreateMemoryTable, CreateView, Execute, Expr, ExprSchemable, GroupingSet,
41 LogicalPlanBuilder, Operator, Prepare, TableProviderFilterPushDown, TableSource,
42 WindowFunctionDefinition, build_asof_join_schema, build_join_schema, expr_vec_fmt,
43 requalify_sides_if_needed,
44};
45
46use crate::logical_plan::information_schema::ColumnsDetail;
47use crate::statistics::StatisticsRequest;
48use arrow::compute::SortOptions;
49use arrow::datatypes::{DataType, Field, FieldRef, Schema, SchemaRef};
50use datafusion_common::cse::{NormalizeEq, Normalizeable};
51use datafusion_common::format::{ExplainAnalyzeCategories, ExplainFormat, MetricType};
52use datafusion_common::metadata::{
53 check_metadata_with_storage_equal, merge_metadata_for_union,
54};
55use datafusion_common::tree_node::{
56 Transformed, TreeNode, TreeNodeContainer, TreeNodeRecursion,
57};
58use datafusion_common::{
59 Column, Constraints, DFSchema, DFSchemaRef, DataFusionError, Dependency,
60 FunctionalDependence, FunctionalDependencies, NullEquality, ParamValues, Result,
61 ScalarValue, Spans, SplitPoint, TableReference, UnnestOptions,
62 aggregate_functional_dependencies, assert_eq_or_internal_err, assert_or_internal_err,
63 internal_err, plan_datafusion_err, plan_err, validate_range_split_points,
64};
65use itertools::Itertools as _;
66
67use crate::display::PgJsonVisitor;
69pub use datafusion_common::display::{PlanType, StringifiedPlan, ToStringifiedPlan};
70pub use datafusion_common::{JoinConstraint, JoinType};
71
72#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
268pub enum LogicalPlan {
269 Projection(Projection),
272 Filter(Filter),
281 Window(Window),
287 Aggregate(Aggregate),
293 Sort(Sort),
296 Join(Join),
299 Repartition(Repartition),
303 Union(Union),
307 TableScan(TableScan),
310 EmptyRelation(EmptyRelation),
314 Subquery(Subquery),
317 SubqueryAlias(SubqueryAlias),
319 Limit(Limit),
321 Statement(Statement),
323 Values(Values),
328 Explain(Explain),
331 Analyze(Analyze),
335 Extension(Extension),
338 Distinct(Distinct),
341 Dml(DmlStatement),
343 Ddl(DdlStatement),
345 Copy(CopyTo),
347 Show(Show),
351 Unnest(Unnest),
354 RecursiveQuery(RecursiveQuery),
356 AsOfJoin(AsOfJoin),
359 MaterializedCte(MaterializedCtePlan),
362}
363
364impl Default for LogicalPlan {
365 fn default() -> Self {
366 LogicalPlan::EmptyRelation(EmptyRelation {
370 produce_one_row: false,
371 schema: Arc::clone(DFSchema::empty_ref()),
372 })
373 }
374}
375
376impl<'a> TreeNodeContainer<'a, Self> for LogicalPlan {
377 fn apply_elements<F: FnMut(&'a Self) -> Result<TreeNodeRecursion>>(
378 &'a self,
379 mut f: F,
380 ) -> Result<TreeNodeRecursion> {
381 f(self)
382 }
383
384 fn map_elements<F: FnMut(Self) -> Result<Transformed<Self>>>(
385 self,
386 mut f: F,
387 ) -> Result<Transformed<Self>> {
388 f(self)
389 }
390}
391
392impl LogicalPlan {
393 pub fn schema(&self) -> &DFSchemaRef {
395 match self {
396 LogicalPlan::EmptyRelation(EmptyRelation { schema, .. }) => schema,
397 LogicalPlan::Values(Values { schema, .. }) => schema,
398 LogicalPlan::TableScan(TableScan {
399 projected_schema, ..
400 }) => projected_schema,
401 LogicalPlan::Projection(Projection { schema, .. }) => schema,
402 LogicalPlan::Filter(Filter { input, .. }) => input.schema(),
403 LogicalPlan::Distinct(Distinct::All(input)) => input.schema(),
404 LogicalPlan::Distinct(Distinct::On(DistinctOn { schema, .. })) => schema,
405 LogicalPlan::Window(Window { schema, .. }) => schema,
406 LogicalPlan::Aggregate(Aggregate { schema, .. }) => schema,
407 LogicalPlan::Sort(Sort { input, .. }) => input.schema(),
408 LogicalPlan::Join(Join { schema, .. }) => schema,
409 LogicalPlan::AsOfJoin(AsOfJoin { schema, .. }) => schema,
410 LogicalPlan::Repartition(Repartition { input, .. }) => input.schema(),
411 LogicalPlan::Limit(Limit { input, .. }) => input.schema(),
412 LogicalPlan::Statement(statement) => statement.schema(),
413 LogicalPlan::Subquery(Subquery { subquery, .. }) => subquery.schema(),
414 LogicalPlan::SubqueryAlias(SubqueryAlias { schema, .. }) => schema,
415 LogicalPlan::Explain(explain) => &explain.schema,
416 LogicalPlan::Analyze(analyze) => &analyze.schema,
417 LogicalPlan::Extension(extension) => extension.node.schema(),
418 LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => cte.schema(),
419 LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan)) => &scan.schema,
420 LogicalPlan::Union(Union { schema, .. }) => schema,
421 LogicalPlan::Show(Show { output_schema, .. }) => output_schema,
422 LogicalPlan::Dml(DmlStatement { output_schema, .. }) => output_schema,
423 LogicalPlan::Copy(CopyTo { output_schema, .. }) => output_schema,
424 LogicalPlan::Ddl(ddl) => ddl.schema(),
425 LogicalPlan::Unnest(Unnest { schema, .. }) => schema,
426 LogicalPlan::RecursiveQuery(RecursiveQuery { schema, .. }) => schema,
427 }
428 }
429
430 pub fn fallback_normalize_schemas(&self) -> Vec<&DFSchema> {
433 match self {
434 LogicalPlan::Window(_)
435 | LogicalPlan::Projection(_)
436 | LogicalPlan::Aggregate(_)
437 | LogicalPlan::Unnest(_)
438 | LogicalPlan::Join(_)
439 | LogicalPlan::AsOfJoin(_) => self
440 .inputs()
441 .iter()
442 .map(|input| input.schema().as_ref())
443 .collect(),
444 _ => vec![],
445 }
446 }
447
448 pub fn explain_schema() -> SchemaRef {
450 SchemaRef::new(Schema::new(vec![
451 Field::new("plan_type", DataType::Utf8, false),
452 Field::new("plan", DataType::Utf8, false),
453 ]))
454 }
455
456 pub fn describe_schema() -> Schema {
458 information_schema::columns_schema(ColumnsDetail::Describe)
459 }
460
461 pub fn expressions(self: &LogicalPlan) -> Vec<Expr> {
478 let mut exprs = vec![];
479 self.apply_expressions(|e| {
480 exprs.push(e.clone());
481 Ok(TreeNodeRecursion::Continue)
482 })
483 .unwrap();
485 exprs
486 }
487
488 pub fn all_out_ref_exprs(self: &LogicalPlan) -> Vec<Expr> {
491 let mut exprs = vec![];
492 self.apply_expressions(|e| {
493 for e in find_out_reference_exprs(e) {
494 if !exprs.contains(&e) {
495 exprs.push(e)
496 }
497 }
498 Ok(TreeNodeRecursion::Continue)
499 })
500 .unwrap();
502 self.inputs()
503 .into_iter()
504 .flat_map(|child| child.all_out_ref_exprs())
505 .for_each(|e| {
506 if !exprs.contains(&e) {
507 exprs.push(e)
508 }
509 });
510 exprs
511 }
512
513 pub fn inputs(&self) -> Vec<&LogicalPlan> {
517 match self {
518 LogicalPlan::Projection(Projection { input, .. }) => vec![input],
519 LogicalPlan::Filter(Filter { input, .. }) => vec![input],
520 LogicalPlan::Repartition(Repartition { input, .. }) => vec![input],
521 LogicalPlan::Window(Window { input, .. }) => vec![input],
522 LogicalPlan::Aggregate(Aggregate { input, .. }) => vec![input],
523 LogicalPlan::Sort(Sort { input, .. }) => vec![input],
524 LogicalPlan::Join(Join { left, right, .. }) => vec![left, right],
525 LogicalPlan::AsOfJoin(AsOfJoin { left, right, .. }) => {
526 vec![left, right]
527 }
528 LogicalPlan::Limit(Limit { input, .. }) => vec![input],
529 LogicalPlan::Subquery(Subquery { subquery, .. }) => vec![subquery],
530 LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => vec![input],
531 LogicalPlan::Extension(extension) => extension.node.inputs(),
532 LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(MaterializedCte {
533 cte,
534 continuation,
535 ..
536 })) => vec![cte, continuation],
537 LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => vec![],
538 LogicalPlan::Union(Union { inputs, .. }) => {
539 inputs.iter().map(|arc| arc.as_ref()).collect()
540 }
541 LogicalPlan::Distinct(
542 Distinct::All(input) | Distinct::On(DistinctOn { input, .. }),
543 ) => vec![input],
544 LogicalPlan::Explain(explain) => vec![&explain.plan],
545 LogicalPlan::Analyze(analyze) => vec![&analyze.input],
546 LogicalPlan::Dml(write) => vec![&write.input],
547 LogicalPlan::Copy(copy) => vec![©.input],
548 LogicalPlan::Ddl(ddl) => ddl.inputs(),
549 LogicalPlan::Unnest(Unnest { input, .. }) => vec![input],
550 LogicalPlan::RecursiveQuery(RecursiveQuery {
551 static_term,
552 recursive_term,
553 ..
554 }) => vec![static_term, recursive_term],
555 LogicalPlan::Statement(stmt) => stmt.inputs(),
556 LogicalPlan::TableScan { .. }
558 | LogicalPlan::EmptyRelation { .. }
559 | LogicalPlan::Values { .. }
560 | LogicalPlan::Show(_) => vec![],
561 }
562 }
563
564 pub fn using_columns(&self) -> Result<Vec<HashSet<Column>>, DataFusionError> {
566 let mut using_columns: Vec<HashSet<Column>> = vec![];
567
568 self.apply_with_subqueries(|plan| {
569 let on = match plan {
570 LogicalPlan::Join(Join {
571 join_constraint: JoinConstraint::Using,
572 on,
573 ..
574 })
575 | LogicalPlan::AsOfJoin(AsOfJoin {
576 join_constraint: JoinConstraint::Using,
577 on,
578 ..
579 }) => Some(on),
580 _ => None,
581 };
582 if let Some(on) = on {
583 let columns = on.iter().try_fold(
585 HashSet::with_capacity(on.len() * 2),
586 |mut accumu, (l, r)| {
587 let Some(l) = l.get_as_join_column() else {
588 return internal_err!(
589 "Invalid join key. Expected column, found {l:?}"
590 );
591 };
592 let Some(r) = r.get_as_join_column() else {
593 return internal_err!(
594 "Invalid join key. Expected column, found {r:?}"
595 );
596 };
597 accumu.insert(l.to_owned());
598 accumu.insert(r.to_owned());
599 Result::<_, DataFusionError>::Ok(accumu)
600 },
601 )?;
602 using_columns.push(columns);
603 }
604 Ok(TreeNodeRecursion::Continue)
605 })?;
606
607 Ok(using_columns)
608 }
609
610 pub fn head_output_expr(&self) -> Result<Option<Expr>> {
612 match self {
613 LogicalPlan::Projection(projection) => {
614 Ok(Some(projection.expr.as_slice()[0].clone()))
615 }
616 LogicalPlan::Aggregate(agg) => {
617 if agg.group_expr.is_empty() {
618 Ok(Some(agg.aggr_expr.as_slice()[0].clone()))
619 } else {
620 Ok(Some(agg.group_expr.as_slice()[0].clone()))
621 }
622 }
623 LogicalPlan::Distinct(Distinct::On(DistinctOn { select_expr, .. })) => {
624 Ok(Some(select_expr[0].clone()))
625 }
626 LogicalPlan::Filter(Filter { input, .. })
627 | LogicalPlan::Distinct(Distinct::All(input))
628 | LogicalPlan::Sort(Sort { input, .. })
629 | LogicalPlan::Limit(Limit { input, .. })
630 | LogicalPlan::Repartition(Repartition { input, .. })
631 | LogicalPlan::Window(Window { input, .. }) => input.head_output_expr(),
632 LogicalPlan::Join(Join {
633 left,
634 right,
635 join_type,
636 ..
637 }) => match join_type {
638 JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {
639 if left.schema().fields().is_empty() {
640 right.head_output_expr()
641 } else {
642 left.head_output_expr()
643 }
644 }
645 JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
646 left.head_output_expr()
647 }
648 JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => {
649 right.head_output_expr()
650 }
651 },
652 LogicalPlan::AsOfJoin(AsOfJoin { left, .. }) => left.head_output_expr(),
653 LogicalPlan::RecursiveQuery(RecursiveQuery { static_term, .. }) => {
654 static_term.head_output_expr()
655 }
656 LogicalPlan::Union(union) => Ok(Some(Expr::Column(Column::from(
657 union.schema.qualified_field(0),
658 )))),
659 LogicalPlan::TableScan(table) => Ok(Some(Expr::Column(Column::from(
660 table.projected_schema.qualified_field(0),
661 )))),
662 LogicalPlan::SubqueryAlias(subquery_alias) => {
663 let expr_opt = subquery_alias.input.head_output_expr()?;
664 expr_opt
665 .map(|expr| {
666 Ok(Expr::Column(create_col_from_scalar_expr(
667 &expr,
668 subquery_alias.alias.to_string(),
669 )?))
670 })
671 .map_or(Ok(None), |v| v.map(Some))
672 }
673 LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
675 cte.continuation.head_output_expr()
676 }
677 LogicalPlan::Extension(_)
678 | LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => Ok(None),
679 LogicalPlan::Subquery(_) => Ok(None),
680 LogicalPlan::EmptyRelation(_)
681 | LogicalPlan::Statement(_)
682 | LogicalPlan::Values(_)
683 | LogicalPlan::Explain(_)
684 | LogicalPlan::Analyze(_)
685 | LogicalPlan::Dml(_)
686 | LogicalPlan::Copy(_)
687 | LogicalPlan::Ddl(_)
688 | LogicalPlan::Show(_)
689 | LogicalPlan::Unnest(_) => Ok(None),
690 }
691 }
692
693 pub fn recompute_schema(self) -> Result<Self> {
716 match self {
717 LogicalPlan::Projection(Projection {
720 expr,
721 input,
722 schema: _,
723 }) => Projection::try_new(expr, input).map(LogicalPlan::Projection),
724 LogicalPlan::Dml(_) => Ok(self),
725 LogicalPlan::Copy(_) => Ok(self),
726 LogicalPlan::Values(Values { schema, values }) => {
727 Ok(LogicalPlan::Values(Values { schema, values }))
729 }
730 LogicalPlan::Filter(Filter { predicate, input }) => {
731 Filter::try_new(predicate, input).map(LogicalPlan::Filter)
732 }
733 LogicalPlan::Repartition(_) => Ok(self),
734 LogicalPlan::Window(Window {
735 input,
736 window_expr,
737 schema: _,
738 }) => Window::try_new(window_expr, input).map(LogicalPlan::Window),
739 LogicalPlan::Aggregate(Aggregate {
740 input,
741 group_expr,
742 aggr_expr,
743 schema: _,
744 }) => Aggregate::try_new(input, group_expr, aggr_expr)
745 .map(LogicalPlan::Aggregate),
746 LogicalPlan::Sort(_) => Ok(self),
747 LogicalPlan::Join(Join {
748 left,
749 right,
750 filter,
751 join_type,
752 join_constraint,
753 on,
754 schema: _,
755 null_equality,
756 null_aware,
757 null_aware_value_keys,
758 }) => {
759 let schema =
760 build_join_schema(left.schema(), right.schema(), &join_type)?;
761
762 let new_on: Vec<_> = on
763 .into_iter()
764 .map(|equi_expr| {
765 (equi_expr.0.unalias(), equi_expr.1.unalias())
767 })
768 .collect();
769
770 Ok(LogicalPlan::Join(Join {
771 left,
772 right,
773 join_type,
774 join_constraint,
775 on: new_on,
776 filter,
777 schema: DFSchemaRef::new(schema),
778 null_equality,
779 null_aware,
780 null_aware_value_keys,
781 }))
782 }
783 LogicalPlan::AsOfJoin(AsOfJoin {
784 left,
785 right,
786 on,
787 match_condition,
788 join_constraint,
789 schema: _,
790 }) => Ok(LogicalPlan::AsOfJoin(AsOfJoin::try_new(
791 left,
792 right,
793 on.into_iter()
794 .map(|(left, right)| (left.unalias(), right.unalias()))
795 .collect(),
796 AsOfMatch {
797 left: match_condition.left.unalias(),
798 op: match_condition.op,
799 right: match_condition.right.unalias(),
800 },
801 join_constraint,
802 )?)),
803 LogicalPlan::Subquery(_) => Ok(self),
804 LogicalPlan::SubqueryAlias(SubqueryAlias {
805 input,
806 alias,
807 schema: _,
808 }) => SubqueryAlias::try_new(input, alias).map(LogicalPlan::SubqueryAlias),
809 LogicalPlan::Limit(_) => Ok(self),
810 LogicalPlan::Ddl(_) => Ok(self),
811 LogicalPlan::MaterializedCte(_) => Ok(self),
815 LogicalPlan::Extension(Extension { node }) => {
816 let expr = node.expressions();
819 let inputs: Vec<_> = node.inputs().into_iter().cloned().collect();
820 Ok(LogicalPlan::Extension(Extension {
821 node: node.with_exprs_and_inputs(expr, inputs)?,
822 }))
823 }
824 LogicalPlan::Union(Union { inputs, schema }) => {
825 let first_input_schema = inputs[0].schema();
826 if schema.fields().len() == first_input_schema.fields().len() {
827 Ok(LogicalPlan::Union(Union { inputs, schema }))
829 } else {
830 Ok(LogicalPlan::Union(Union::try_new(inputs)?))
838 }
839 }
840 LogicalPlan::Distinct(distinct) => {
841 let distinct = match distinct {
842 Distinct::All(input) => Distinct::All(input),
843 Distinct::On(DistinctOn {
844 on_expr,
845 select_expr,
846 sort_expr,
847 input,
848 schema: _,
849 }) => Distinct::On(DistinctOn::try_new(
850 on_expr,
851 select_expr,
852 sort_expr,
853 input,
854 )?),
855 };
856 Ok(LogicalPlan::Distinct(distinct))
857 }
858 LogicalPlan::RecursiveQuery(RecursiveQuery {
859 name,
860 static_term,
861 recursive_term,
862 is_distinct,
863 schema: _,
864 }) => RecursiveQuery::try_new(name, static_term, recursive_term, is_distinct)
865 .map(LogicalPlan::RecursiveQuery),
866 LogicalPlan::Analyze(_) => Ok(self),
867 LogicalPlan::Explain(_) => Ok(self),
868 LogicalPlan::TableScan(_) => Ok(self),
869 LogicalPlan::EmptyRelation(_) => Ok(self),
870 LogicalPlan::Statement(_) => Ok(self),
871 LogicalPlan::Show(_) => Ok(self),
872 LogicalPlan::Unnest(Unnest {
873 input,
874 exec_columns,
875 options,
876 ..
877 }) => {
878 unnest_with_options(Arc::unwrap_or_clone(input), exec_columns, options)
880 }
881 }
882 }
883
884 pub fn with_new_exprs(
910 &self,
911 mut expr: Vec<Expr>,
912 inputs: Vec<LogicalPlan>,
913 ) -> Result<LogicalPlan> {
914 match self {
915 LogicalPlan::Projection(Projection { .. }) => {
918 let input = self.only_input(inputs)?;
919 Projection::try_new(expr, Arc::new(input)).map(LogicalPlan::Projection)
920 }
921 LogicalPlan::Dml(DmlStatement {
922 table_name,
923 target,
924 op,
925 ..
926 }) => {
927 let input = self.only_input(inputs)?;
928 let op = match op {
929 WriteOp::MergeInto(merge_op) => {
930 WriteOp::MergeInto(Box::new(merge_op.with_new_exprs(expr)?))
931 }
932 other => {
933 self.assert_no_expressions(expr)?;
934 other.clone()
935 }
936 };
937 Ok(LogicalPlan::Dml(DmlStatement::new(
938 table_name.clone(),
939 Arc::clone(target),
940 op,
941 Arc::new(input),
942 )))
943 }
944 LogicalPlan::Copy(CopyTo {
945 input: _,
946 output_url,
947 file_type,
948 options,
949 partition_by,
950 output_schema: _,
951 }) => {
952 self.assert_no_expressions(expr)?;
953 let input = self.only_input(inputs)?;
954 Ok(LogicalPlan::Copy(CopyTo::new(
955 Arc::new(input),
956 output_url.clone(),
957 partition_by.clone(),
958 Arc::clone(file_type),
959 options.clone(),
960 )))
961 }
962 LogicalPlan::Values(Values { schema, .. }) => {
963 self.assert_no_inputs(inputs)?;
964 Ok(LogicalPlan::Values(Values {
965 schema: Arc::clone(schema),
966 values: expr
967 .chunks_exact(schema.fields().len())
968 .map(|s| s.to_vec())
969 .collect(),
970 }))
971 }
972 LogicalPlan::Filter { .. } => {
973 let predicate = self.only_expr(expr)?;
974 let input = self.only_input(inputs)?;
975
976 Filter::try_new(predicate, Arc::new(input)).map(LogicalPlan::Filter)
977 }
978 LogicalPlan::Repartition(Repartition {
979 partitioning_scheme,
980 ..
981 }) => match partitioning_scheme {
982 Partitioning::RoundRobinBatch(n) => {
983 self.assert_no_expressions(expr)?;
984 let input = self.only_input(inputs)?;
985 Ok(LogicalPlan::Repartition(Repartition {
986 partitioning_scheme: Partitioning::RoundRobinBatch(*n),
987 input: Arc::new(input),
988 }))
989 }
990 Partitioning::Hash(_, n) => {
991 let input = self.only_input(inputs)?;
992 Ok(LogicalPlan::Repartition(Repartition {
993 partitioning_scheme: Partitioning::Hash(expr, *n),
994 input: Arc::new(input),
995 }))
996 }
997 Partitioning::Range(range) => {
998 if expr.len() != range.ordering().len() {
999 return internal_err!(
1000 "Incorrect number of expressions for Range partitioning"
1001 );
1002 }
1003 let input = self.only_input(inputs)?;
1004 let ordering = range
1005 .ordering()
1006 .iter()
1007 .zip(expr)
1008 .map(|(sort_expr, expr)| SortExpr {
1009 expr,
1010 asc: sort_expr.asc,
1011 nulls_first: sort_expr.nulls_first,
1012 })
1013 .collect();
1014 let range = RangePartitioning::try_new(
1015 ordering,
1016 range.split_points().to_vec(),
1017 )?;
1018 Ok(LogicalPlan::Repartition(Repartition {
1019 partitioning_scheme: Partitioning::Range(range),
1020 input: Arc::new(input),
1021 }))
1022 }
1023 Partitioning::DistributeBy(_) => {
1024 let input = self.only_input(inputs)?;
1025 Ok(LogicalPlan::Repartition(Repartition {
1026 partitioning_scheme: Partitioning::DistributeBy(expr),
1027 input: Arc::new(input),
1028 }))
1029 }
1030 },
1031 LogicalPlan::Window(Window { window_expr, .. }) => {
1032 assert_eq!(window_expr.len(), expr.len());
1033 let input = self.only_input(inputs)?;
1034 Window::try_new(expr, Arc::new(input)).map(LogicalPlan::Window)
1035 }
1036 LogicalPlan::Aggregate(Aggregate { group_expr, .. }) => {
1037 let input = self.only_input(inputs)?;
1038 let agg_expr = expr.split_off(group_expr.len());
1040
1041 Aggregate::try_new(Arc::new(input), expr, agg_expr)
1042 .map(LogicalPlan::Aggregate)
1043 }
1044 LogicalPlan::Sort(Sort {
1045 expr: sort_expr,
1046 fetch,
1047 ..
1048 }) => {
1049 let input = self.only_input(inputs)?;
1050 Ok(LogicalPlan::Sort(Sort {
1051 expr: expr
1052 .into_iter()
1053 .zip(sort_expr.iter())
1054 .map(|(expr, sort)| sort.with_expr(expr))
1055 .collect(),
1056 input: Arc::new(input),
1057 fetch: *fetch,
1058 }))
1059 }
1060 LogicalPlan::Join(Join {
1061 join_type,
1062 join_constraint,
1063 on,
1064 null_equality,
1065 null_aware,
1066 null_aware_value_keys,
1067 ..
1068 }) => {
1069 let (left, right) = self.only_two_inputs(inputs)?;
1070 let schema = build_join_schema(left.schema(), right.schema(), join_type)?;
1071
1072 let equi_expr_count = on.len() * 2;
1073 assert!(expr.len() >= equi_expr_count);
1074
1075 let filter_expr = if expr.len() > equi_expr_count {
1078 expr.pop()
1079 } else {
1080 None
1081 };
1082
1083 assert_eq!(expr.len(), equi_expr_count);
1086 let mut new_on = Vec::with_capacity(on.len());
1087 let mut iter = expr.into_iter();
1088 while let Some(left) = iter.next() {
1089 let Some(right) = iter.next() else {
1090 internal_err!(
1091 "Expected a pair of expressions to construct the join on expression"
1092 )?
1093 };
1094
1095 new_on.push((left.unalias(), right.unalias()));
1097 }
1098
1099 Ok(LogicalPlan::Join(Join {
1100 left: Arc::new(left),
1101 right: Arc::new(right),
1102 join_type: *join_type,
1103 join_constraint: *join_constraint,
1104 on: new_on,
1105 filter: filter_expr,
1106 schema: DFSchemaRef::new(schema),
1107 null_equality: *null_equality,
1108 null_aware: *null_aware,
1109 null_aware_value_keys: *null_aware_value_keys,
1110 }))
1111 }
1112 LogicalPlan::AsOfJoin(AsOfJoin {
1113 on,
1114 match_condition,
1115 join_constraint,
1116 ..
1117 }) => {
1118 let (left, right) = self.only_two_inputs(inputs)?;
1119 let expected = on.len() * 2 + 2;
1120 assert_eq_or_internal_err!(
1121 expected,
1122 expr.len(),
1123 "Invalid number of new ASOF join expressions: expected {}, got {}",
1124 expected,
1125 expr.len()
1126 );
1127
1128 let mut iter = expr.into_iter();
1129 let mut new_on = Vec::with_capacity(on.len());
1130 for _ in 0..on.len() {
1131 let left = iter.next().expect("expression count checked").unalias();
1132 let right = iter.next().expect("expression count checked").unalias();
1133 new_on.push((left, right));
1134 }
1135 let match_left = iter.next().expect("expression count checked").unalias();
1136 let match_right =
1137 iter.next().expect("expression count checked").unalias();
1138
1139 Ok(LogicalPlan::AsOfJoin(AsOfJoin::try_new(
1140 Arc::new(left),
1141 Arc::new(right),
1142 new_on,
1143 AsOfMatch {
1144 left: match_left,
1145 op: match_condition.op,
1146 right: match_right,
1147 },
1148 *join_constraint,
1149 )?))
1150 }
1151 LogicalPlan::Subquery(Subquery {
1152 outer_ref_columns,
1153 spans,
1154 ..
1155 }) => {
1156 self.assert_no_expressions(expr)?;
1157 let input = self.only_input(inputs)?;
1158 let subquery = LogicalPlanBuilder::from(input).build()?;
1159 Ok(LogicalPlan::Subquery(Subquery {
1160 subquery: Arc::new(subquery),
1161 outer_ref_columns: outer_ref_columns.clone(),
1162 spans: spans.clone(),
1163 }))
1164 }
1165 LogicalPlan::SubqueryAlias(SubqueryAlias { alias, .. }) => {
1166 self.assert_no_expressions(expr)?;
1167 let input = self.only_input(inputs)?;
1168 SubqueryAlias::try_new(Arc::new(input), alias.clone())
1169 .map(LogicalPlan::SubqueryAlias)
1170 }
1171 LogicalPlan::Limit(Limit { skip, fetch, .. }) => {
1172 let old_expr_len = skip.iter().chain(fetch.iter()).count();
1173 assert_eq_or_internal_err!(
1174 old_expr_len,
1175 expr.len(),
1176 "Invalid number of new Limit expressions: expected {}, got {}",
1177 old_expr_len,
1178 expr.len()
1179 );
1180 let new_fetch = fetch.as_ref().and_then(|_| expr.pop());
1182 let new_skip = skip.as_ref().and_then(|_| expr.pop());
1183 let input = self.only_input(inputs)?;
1184 Ok(LogicalPlan::Limit(Limit {
1185 skip: new_skip.map(Box::new),
1186 fetch: new_fetch.map(Box::new),
1187 input: Arc::new(input),
1188 }))
1189 }
1190 LogicalPlan::Ddl(DdlStatement::CreateMemoryTable(CreateMemoryTable {
1191 name,
1192 if_not_exists,
1193 or_replace,
1194 column_defaults,
1195 temporary,
1196 ..
1197 })) => {
1198 self.assert_no_expressions(expr)?;
1199 let input = self.only_input(inputs)?;
1200 Ok(LogicalPlan::Ddl(DdlStatement::CreateMemoryTable(
1201 CreateMemoryTable {
1202 input: Arc::new(input),
1203 constraints: Constraints::default(),
1204 name: name.clone(),
1205 if_not_exists: *if_not_exists,
1206 or_replace: *or_replace,
1207 column_defaults: column_defaults.clone(),
1208 temporary: *temporary,
1209 },
1210 )))
1211 }
1212 LogicalPlan::Ddl(DdlStatement::CreateView(CreateView {
1213 name,
1214 or_replace,
1215 definition,
1216 temporary,
1217 ..
1218 })) => {
1219 self.assert_no_expressions(expr)?;
1220 let input = self.only_input(inputs)?;
1221 Ok(LogicalPlan::Ddl(DdlStatement::CreateView(CreateView {
1222 input: Arc::new(input),
1223 name: name.clone(),
1224 or_replace: *or_replace,
1225 temporary: *temporary,
1226 definition: definition.clone(),
1227 })))
1228 }
1229 LogicalPlan::Extension(e) => Ok(LogicalPlan::Extension(Extension {
1230 node: e.node.with_exprs_and_inputs(expr, inputs)?,
1231 })),
1232 LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte)) => {
1233 self.assert_no_expressions(expr)?;
1234 let (body, continuation) = self.only_two_inputs(inputs)?;
1235 Ok(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
1236 cte.with_new_inputs(Arc::new(body), Arc::new(continuation)),
1237 )))
1238 }
1239 LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(_)) => {
1240 self.assert_no_expressions(expr)?;
1241 self.assert_no_inputs(inputs)?;
1242 Ok(self.clone())
1243 }
1244 LogicalPlan::Union(Union { schema, .. }) => {
1245 self.assert_no_expressions(expr)?;
1246 let input_schema = inputs[0].schema();
1247 let schema = if schema.fields().len() == input_schema.fields().len() {
1249 Arc::clone(schema)
1250 } else {
1251 Arc::clone(input_schema)
1252 };
1253 Ok(LogicalPlan::Union(Union {
1254 inputs: inputs.into_iter().map(Arc::new).collect(),
1255 schema,
1256 }))
1257 }
1258 LogicalPlan::Distinct(distinct) => {
1259 let distinct = match distinct {
1260 Distinct::All(_) => {
1261 self.assert_no_expressions(expr)?;
1262 let input = self.only_input(inputs)?;
1263 Distinct::All(Arc::new(input))
1264 }
1265 Distinct::On(DistinctOn {
1266 on_expr,
1267 select_expr,
1268 ..
1269 }) => {
1270 let input = self.only_input(inputs)?;
1271 let sort_expr = expr.split_off(on_expr.len() + select_expr.len());
1272 let select_expr = expr.split_off(on_expr.len());
1273 assert!(
1274 sort_expr.is_empty(),
1275 "with_new_exprs for Distinct does not support sort expressions"
1276 );
1277 Distinct::On(DistinctOn::try_new(
1278 expr,
1279 select_expr,
1280 None, Arc::new(input),
1282 )?)
1283 }
1284 };
1285 Ok(LogicalPlan::Distinct(distinct))
1286 }
1287 LogicalPlan::RecursiveQuery(RecursiveQuery {
1288 name, is_distinct, ..
1289 }) => {
1290 self.assert_no_expressions(expr)?;
1291 let (static_term, recursive_term) = self.only_two_inputs(inputs)?;
1292 RecursiveQuery::try_new(
1293 name.clone(),
1294 Arc::new(static_term),
1295 Arc::new(recursive_term),
1296 *is_distinct,
1297 )
1298 .map(LogicalPlan::RecursiveQuery)
1299 }
1300 LogicalPlan::Analyze(a) => {
1301 self.assert_no_expressions(expr)?;
1302 let input = self.only_input(inputs)?;
1303 Ok(LogicalPlan::Analyze(Analyze {
1304 verbose: a.verbose,
1305 format: a.format.clone(),
1306 schema: Arc::clone(&a.schema),
1307 input: Arc::new(input),
1308 analyze_level: a.analyze_level,
1309 analyze_categories: a.analyze_categories.clone(),
1310 }))
1311 }
1312 LogicalPlan::Explain(e) => {
1313 self.assert_no_expressions(expr)?;
1314 let input = self.only_input(inputs)?;
1315 Ok(LogicalPlan::Explain(Explain {
1316 verbose: e.verbose,
1317 plan: Arc::new(input),
1318 explain_format: e.explain_format.clone(),
1319 stringified_plans: e.stringified_plans.clone(),
1320 schema: Arc::clone(&e.schema),
1321 logical_optimization_succeeded: e.logical_optimization_succeeded,
1322 show_statistics: e.show_statistics,
1323 }))
1324 }
1325 LogicalPlan::Statement(Statement::Prepare(Prepare {
1326 name, fields, ..
1327 })) => {
1328 self.assert_no_expressions(expr)?;
1329 let input = self.only_input(inputs)?;
1330 Ok(LogicalPlan::Statement(Statement::Prepare(Prepare {
1331 name: name.clone(),
1332 fields: fields.clone(),
1333 input: Arc::new(input),
1334 })))
1335 }
1336 LogicalPlan::Statement(Statement::Execute(Execute { name, .. })) => {
1337 self.assert_no_inputs(inputs)?;
1338 Ok(LogicalPlan::Statement(Statement::Execute(Execute {
1339 name: name.clone(),
1340 parameters: expr,
1341 })))
1342 }
1343 LogicalPlan::TableScan(ts) => {
1344 self.assert_no_inputs(inputs)?;
1345 Ok(LogicalPlan::TableScan(TableScan {
1346 filters: expr,
1347 ..ts.clone()
1348 }))
1349 }
1350 LogicalPlan::EmptyRelation(_)
1351 | LogicalPlan::Ddl(_)
1352 | LogicalPlan::Statement(_)
1353 | LogicalPlan::Show(_) => {
1354 self.assert_no_expressions(expr)?;
1356 self.assert_no_inputs(inputs)?;
1357 Ok(self.clone())
1358 }
1359 LogicalPlan::Unnest(Unnest {
1360 exec_columns: columns,
1361 options,
1362 ..
1363 }) => {
1364 let exec_columns = if expr.is_empty() {
1365 columns.clone()
1366 } else {
1367 expr.into_iter()
1368 .map(|e| match e {
1369 Expr::Column(c) => Ok(c),
1370 other => internal_err!(
1371 "Expected Expr::Column for Unnest exec_columns, got {other:?}"
1372 ),
1373 })
1374 .collect::<Result<Vec<_>>>()?
1375 };
1376 let input = self.only_input(inputs)?;
1377 Ok(unnest_with_options(input, exec_columns, options.clone())?)
1378 }
1379 }
1380 }
1381
1382 pub fn check_invariants(&self, check: InvariantLevel) -> Result<()> {
1384 match check {
1385 InvariantLevel::Always => assert_always_invariants_at_current_node(self),
1386 InvariantLevel::Executable => assert_executable_invariants(self),
1387 }
1388 }
1389
1390 #[inline]
1392 #[expect(clippy::needless_pass_by_value)] fn assert_no_expressions(&self, expr: Vec<Expr>) -> Result<()> {
1394 assert_or_internal_err!(
1395 expr.is_empty(),
1396 "{self:?} should have no exprs, got {:?}",
1397 expr
1398 );
1399 Ok(())
1400 }
1401
1402 #[inline]
1404 #[expect(clippy::needless_pass_by_value)] fn assert_no_inputs(&self, inputs: Vec<LogicalPlan>) -> Result<()> {
1406 assert_or_internal_err!(
1407 inputs.is_empty(),
1408 "{self:?} should have no inputs, got: {:?}",
1409 inputs
1410 );
1411 Ok(())
1412 }
1413
1414 #[inline]
1416 fn only_expr(&self, mut expr: Vec<Expr>) -> Result<Expr> {
1417 assert_eq_or_internal_err!(
1418 expr.len(),
1419 1,
1420 "{self:?} should have exactly one expr, got {:?}",
1421 &expr
1422 );
1423 Ok(expr.remove(0))
1424 }
1425
1426 #[inline]
1428 fn only_input(&self, mut inputs: Vec<LogicalPlan>) -> Result<LogicalPlan> {
1429 assert_eq_or_internal_err!(
1430 inputs.len(),
1431 1,
1432 "{self:?} should have exactly one input, got {:?}",
1433 &inputs
1434 );
1435 Ok(inputs.remove(0))
1436 }
1437
1438 #[inline]
1440 fn only_two_inputs(
1441 &self,
1442 mut inputs: Vec<LogicalPlan>,
1443 ) -> Result<(LogicalPlan, LogicalPlan)> {
1444 assert_eq_or_internal_err!(
1445 inputs.len(),
1446 2,
1447 "{self:?} should have exactly two inputs, got {:?}",
1448 &inputs
1449 );
1450 let right = inputs.remove(1);
1451 let left = inputs.remove(0);
1452 Ok((left, right))
1453 }
1454
1455 pub fn with_param_values(
1508 self,
1509 param_values: impl Into<ParamValues>,
1510 ) -> Result<LogicalPlan> {
1511 let param_values = param_values.into();
1512 let plan_with_values = self.replace_params_with_values(¶m_values)?;
1513
1514 Ok(
1516 if let LogicalPlan::Statement(Statement::Prepare(prepare_lp)) =
1517 plan_with_values
1518 {
1519 param_values.verify_fields(&prepare_lp.fields)?;
1520 Arc::unwrap_or_clone(prepare_lp.input)
1522 } else {
1523 plan_with_values
1524 },
1525 )
1526 }
1527
1528 pub fn max_rows(self: &LogicalPlan) -> Option<usize> {
1533 match self {
1534 LogicalPlan::Projection(Projection { input, .. }) => input.max_rows(),
1535 LogicalPlan::Filter(filter) => {
1536 if filter.is_scalar() {
1537 Some(1)
1538 } else {
1539 filter.input.max_rows()
1540 }
1541 }
1542 LogicalPlan::Window(Window { input, .. }) => input.max_rows(),
1543 LogicalPlan::Aggregate(Aggregate {
1544 input, group_expr, ..
1545 }) => {
1546 if group_expr
1548 .iter()
1549 .all(|expr| matches!(expr, Expr::Literal(_, _)))
1550 {
1551 Some(1)
1552 } else {
1553 input.max_rows()
1554 }
1555 }
1556 LogicalPlan::Sort(Sort { input, fetch, .. }) => {
1557 match (fetch, input.max_rows()) {
1558 (Some(fetch_limit), Some(input_max)) => {
1559 Some(input_max.min(*fetch_limit))
1560 }
1561 (Some(fetch_limit), None) => Some(*fetch_limit),
1562 (None, Some(input_max)) => Some(input_max),
1563 (None, None) => None,
1564 }
1565 }
1566 LogicalPlan::Join(Join {
1567 left,
1568 right,
1569 join_type,
1570 ..
1571 }) => match join_type {
1572 JoinType::Inner => Some(left.max_rows()? * right.max_rows()?),
1573 JoinType::Left | JoinType::Right | JoinType::Full => {
1574 match (left.max_rows()?, right.max_rows()?, join_type) {
1575 (0, 0, _) => Some(0),
1576 (max_rows, 0, JoinType::Left | JoinType::Full) => Some(max_rows),
1577 (0, max_rows, JoinType::Right | JoinType::Full) => Some(max_rows),
1578 (left_max, right_max, _) => Some(left_max * right_max),
1579 }
1580 }
1581 JoinType::LeftSemi | JoinType::LeftAnti | JoinType::LeftMark => {
1582 left.max_rows()
1583 }
1584 JoinType::RightSemi | JoinType::RightAnti | JoinType::RightMark => {
1585 right.max_rows()
1586 }
1587 },
1588 LogicalPlan::AsOfJoin(AsOfJoin { left, .. }) => left.max_rows(),
1589 LogicalPlan::Repartition(Repartition { input, .. }) => input.max_rows(),
1590 LogicalPlan::Union(Union { inputs, .. }) => {
1591 inputs.iter().try_fold(0usize, |mut acc, plan| {
1592 acc += plan.max_rows()?;
1593 Some(acc)
1594 })
1595 }
1596 LogicalPlan::TableScan(TableScan { fetch, .. }) => *fetch,
1597 LogicalPlan::EmptyRelation(EmptyRelation {
1598 produce_one_row, ..
1599 }) => Some(usize::from(*produce_one_row)),
1600 LogicalPlan::RecursiveQuery(_) => None,
1601 LogicalPlan::Subquery(_) => None,
1602 LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => input.max_rows(),
1603 LogicalPlan::Limit(limit) => match limit.get_fetch_type() {
1604 Ok(FetchType::Literal(s)) => s,
1605 _ => None,
1606 },
1607 LogicalPlan::Distinct(
1608 Distinct::All(input) | Distinct::On(DistinctOn { input, .. }),
1609 ) => input.max_rows(),
1610 LogicalPlan::Values(v) => Some(v.values.len()),
1611 LogicalPlan::Unnest(_) => None,
1612 LogicalPlan::Ddl(_)
1613 | LogicalPlan::Explain(_)
1614 | LogicalPlan::Analyze(_)
1615 | LogicalPlan::Dml(_)
1616 | LogicalPlan::Copy(_)
1617 | LogicalPlan::Show(_)
1618 | LogicalPlan::Statement(_)
1619 | LogicalPlan::Extension(_)
1620 | LogicalPlan::MaterializedCte(_) => None,
1621 }
1622 }
1623
1624 pub fn min_rows(&self) -> usize {
1631 match self {
1632 LogicalPlan::Projection(Projection { input, .. })
1633 | LogicalPlan::Window(Window { input, .. })
1634 | LogicalPlan::Repartition(Repartition { input, .. })
1635 | LogicalPlan::SubqueryAlias(SubqueryAlias { input, .. }) => input.min_rows(),
1636 LogicalPlan::Filter(_) => 0,
1637 LogicalPlan::Aggregate(Aggregate { group_expr, .. }) => {
1638 usize::from(group_expr.is_empty())
1641 }
1642 LogicalPlan::Sort(Sort { input, fetch, .. }) => fetch
1643 .map(|fetch| input.min_rows().min(fetch))
1644 .unwrap_or_else(|| input.min_rows()),
1645 LogicalPlan::Join(Join {
1646 left,
1647 right,
1648 on,
1649 filter,
1650 join_type,
1651 ..
1652 }) => match join_type {
1653 JoinType::Inner if on.is_empty() && filter.is_none() => {
1654 left.min_rows().saturating_mul(right.min_rows())
1655 }
1656 JoinType::Left | JoinType::LeftMark => left.min_rows(),
1657 JoinType::Right | JoinType::RightMark => right.min_rows(),
1658 JoinType::Full => left.min_rows().max(right.min_rows()),
1659 JoinType::Inner
1660 | JoinType::LeftSemi
1661 | JoinType::RightSemi
1662 | JoinType::LeftAnti
1663 | JoinType::RightAnti => 0,
1664 },
1665 LogicalPlan::AsOfJoin(AsOfJoin { left, .. }) => left.min_rows(),
1666 LogicalPlan::Union(Union { inputs, .. }) => inputs
1667 .iter()
1668 .fold(0, |rows, input| rows.saturating_add(input.min_rows())),
1669 LogicalPlan::EmptyRelation(EmptyRelation {
1670 produce_one_row, ..
1671 }) => usize::from(*produce_one_row),
1672 LogicalPlan::Subquery(Subquery { subquery, .. }) => subquery.min_rows(),
1673 LogicalPlan::Limit(limit) => {
1674 match (limit.get_skip_type(), limit.get_fetch_type()) {
1675 (Ok(SkipType::Literal(skip)), Ok(FetchType::Literal(fetch))) => fetch
1676 .map(|fetch| {
1677 limit.input.min_rows().saturating_sub(skip).min(fetch)
1678 })
1679 .unwrap_or_else(|| limit.input.min_rows().saturating_sub(skip)),
1680 _ => 0,
1681 }
1682 }
1683 LogicalPlan::Distinct(
1684 Distinct::All(input) | Distinct::On(DistinctOn { input, .. }),
1685 ) => usize::from(input.min_rows() > 0),
1686 LogicalPlan::Values(values) => values.values.len(),
1687 LogicalPlan::TableScan(_)
1688 | LogicalPlan::RecursiveQuery(_)
1689 | LogicalPlan::Unnest(_)
1690 | LogicalPlan::Ddl(_)
1691 | LogicalPlan::Explain(_)
1692 | LogicalPlan::Analyze(_)
1693 | LogicalPlan::Dml(_)
1694 | LogicalPlan::Copy(_)
1695 | LogicalPlan::Show(_)
1696 | LogicalPlan::Statement(_)
1697 | LogicalPlan::Extension(_)
1698 | LogicalPlan::MaterializedCte(_) => 0,
1699 }
1700 }
1701
1702 pub fn skip(&self) -> Result<Option<usize>> {
1707 match self {
1708 LogicalPlan::Limit(limit) => match limit.get_skip_type()? {
1709 SkipType::Literal(0) => Ok(None),
1710 SkipType::Literal(n) => Ok(Some(n)),
1711 SkipType::UnsupportedExpr => Ok(None),
1712 },
1713 LogicalPlan::Sort(_) => Ok(None),
1714 LogicalPlan::TableScan(_) => Ok(None),
1715 LogicalPlan::Projection(_) => Ok(None),
1716 LogicalPlan::Filter(_) => Ok(None),
1717 LogicalPlan::Window(_) => Ok(None),
1718 LogicalPlan::Aggregate(_) => Ok(None),
1719 LogicalPlan::Join(_) => Ok(None),
1720 LogicalPlan::AsOfJoin(_) => Ok(None),
1721 LogicalPlan::Repartition(_) => Ok(None),
1722 LogicalPlan::Union(_) => Ok(None),
1723 LogicalPlan::EmptyRelation(_) => Ok(None),
1724 LogicalPlan::Subquery(_) => Ok(None),
1725 LogicalPlan::SubqueryAlias(_) => Ok(None),
1726 LogicalPlan::Statement(_) => Ok(None),
1727 LogicalPlan::Values(_) => Ok(None),
1728 LogicalPlan::Explain(_) => Ok(None),
1729 LogicalPlan::Analyze(_) => Ok(None),
1730 LogicalPlan::Extension(_) => Ok(None),
1731 LogicalPlan::MaterializedCte(_) => Ok(None),
1732 LogicalPlan::Distinct(_) => Ok(None),
1733 LogicalPlan::Dml(_) => Ok(None),
1734 LogicalPlan::Ddl(_) => Ok(None),
1735 LogicalPlan::Copy(_) => Ok(None),
1736 LogicalPlan::Show(_) => Ok(None),
1737 LogicalPlan::Unnest(_) => Ok(None),
1738 LogicalPlan::RecursiveQuery(_) => Ok(None),
1739 }
1740 }
1741
1742 pub fn fetch(&self) -> Result<Option<usize>> {
1748 match self {
1749 LogicalPlan::Sort(Sort { fetch, .. }) => Ok(*fetch),
1750 LogicalPlan::TableScan(TableScan { fetch, .. }) => Ok(*fetch),
1751 LogicalPlan::Limit(limit) => match limit.get_fetch_type()? {
1752 FetchType::Literal(s) => Ok(s),
1753 FetchType::UnsupportedExpr => Ok(None),
1754 },
1755 LogicalPlan::Projection(_) => Ok(None),
1756 LogicalPlan::Filter(_) => Ok(None),
1757 LogicalPlan::Window(_) => Ok(None),
1758 LogicalPlan::Aggregate(_) => Ok(None),
1759 LogicalPlan::Join(_) => Ok(None),
1760 LogicalPlan::AsOfJoin(_) => Ok(None),
1761 LogicalPlan::Repartition(_) => Ok(None),
1762 LogicalPlan::Union(_) => Ok(None),
1763 LogicalPlan::EmptyRelation(_) => Ok(None),
1764 LogicalPlan::Subquery(_) => Ok(None),
1765 LogicalPlan::SubqueryAlias(_) => Ok(None),
1766 LogicalPlan::Statement(_) => Ok(None),
1767 LogicalPlan::Values(_) => Ok(None),
1768 LogicalPlan::Explain(_) => Ok(None),
1769 LogicalPlan::Analyze(_) => Ok(None),
1770 LogicalPlan::Extension(_) => Ok(None),
1771 LogicalPlan::MaterializedCte(_) => Ok(None),
1772 LogicalPlan::Distinct(_) => Ok(None),
1773 LogicalPlan::Dml(_) => Ok(None),
1774 LogicalPlan::Ddl(_) => Ok(None),
1775 LogicalPlan::Copy(_) => Ok(None),
1776 LogicalPlan::Show(_) => Ok(None),
1777 LogicalPlan::Unnest(_) => Ok(None),
1778 LogicalPlan::RecursiveQuery(_) => Ok(None),
1779 }
1780 }
1781
1782 pub fn contains_outer_reference(&self) -> bool {
1784 let mut contains = false;
1785 self.apply_expressions(|expr| {
1786 Ok(if expr.contains_outer() {
1787 contains = true;
1788 TreeNodeRecursion::Stop
1789 } else {
1790 TreeNodeRecursion::Continue
1791 })
1792 })
1793 .unwrap();
1794 contains
1795 }
1796
1797 pub fn columnized_output_exprs(&self) -> Result<Vec<(&Expr, Column)>> {
1805 match self {
1806 LogicalPlan::Aggregate(aggregate) => Ok(aggregate
1807 .output_expressions()?
1808 .into_iter()
1809 .zip(self.schema().columns())
1810 .collect()),
1811 LogicalPlan::Window(Window {
1812 window_expr,
1813 input,
1814 schema,
1815 }) => {
1816 let mut output_exprs = input.columnized_output_exprs()?;
1824 let input_len = input.schema().fields().len();
1825 output_exprs.extend(
1826 window_expr
1827 .iter()
1828 .zip(schema.columns().into_iter().skip(input_len)),
1829 );
1830 Ok(output_exprs)
1831 }
1832 _ => Ok(vec![]),
1833 }
1834 }
1835}
1836
1837impl LogicalPlan {
1838 pub fn replace_params_with_values(
1845 self,
1846 param_values: &ParamValues,
1847 ) -> Result<LogicalPlan> {
1848 self.transform_up_with_subqueries(|plan| {
1849 let schema = Arc::clone(plan.schema());
1850 let name_preserver = NamePreserver::new(&plan);
1851 plan.map_expressions(|e| {
1852 let (e, has_placeholder) = e.infer_placeholder_types(&schema)?;
1853 if !has_placeholder {
1854 Ok(Transformed::no(e))
1858 } else {
1859 let original_name = name_preserver.save(&e);
1860 let transformed_expr = e.transform_up(|e| {
1861 if let Expr::Placeholder(Placeholder { id, .. }) = e {
1862 let (value, metadata) = param_values
1863 .get_placeholders_with_values(&id)?
1864 .into_inner();
1865 Ok(Transformed::yes(Expr::Literal(value, metadata)))
1866 } else {
1867 Ok(Transformed::no(e))
1868 }
1869 })?;
1870 Ok(transformed_expr.update_data(|expr| original_name.restore(expr)))
1872 }
1873 })?
1874 .map_data(|plan| plan.update_schema_data_type())
1875 })
1876 .map(|res| res.data)
1877 }
1878
1879 fn update_schema_data_type(self) -> Result<LogicalPlan> {
1885 match self {
1886 LogicalPlan::Values(Values { values, schema: _ }) => {
1890 LogicalPlanBuilder::values(values)?.build()
1891 }
1892 plan => plan.recompute_schema(),
1894 }
1895 }
1896
1897 pub fn get_parameter_names(&self) -> Result<HashSet<String>> {
1899 let mut param_names = HashSet::new();
1900 self.apply_with_subqueries(|plan| {
1901 plan.apply_expressions(|expr| {
1902 expr.apply(|expr| {
1903 if let Expr::Placeholder(Placeholder { id, .. }) = expr {
1904 param_names.insert(id.clone());
1905 }
1906 Ok(TreeNodeRecursion::Continue)
1907 })
1908 })
1909 })
1910 .map(|_| param_names)
1911 }
1912
1913 pub fn get_parameter_types(
1918 &self,
1919 ) -> Result<HashMap<String, Option<DataType>>, DataFusionError> {
1920 let mut parameter_fields = self.get_parameter_fields()?;
1921 Ok(parameter_fields
1922 .drain()
1923 .map(|(name, maybe_field)| {
1924 (name, maybe_field.map(|field| field.data_type().clone()))
1925 })
1926 .collect())
1927 }
1928
1929 pub fn get_parameter_fields(
1932 &self,
1933 ) -> Result<HashMap<String, Option<FieldRef>>, DataFusionError> {
1934 let mut param_types: HashMap<String, Option<FieldRef>> = HashMap::new();
1935 let mut row_count_parameters: HashSet<String> = HashSet::new();
1936
1937 self.apply_with_subqueries(|plan| {
1938 plan.apply_expressions(|expr| {
1939 if matches!(plan, LogicalPlan::Limit(_))
1940 && let Expr::Placeholder(Placeholder { id, field: None }) = expr
1941 {
1942 row_count_parameters.insert(id.clone());
1943 }
1944 expr.apply(|expr| {
1945 if let Expr::Placeholder(Placeholder { id, field }) = expr {
1946 let prev = param_types.get(id);
1947 match (prev, field) {
1948 (Some(Some(prev)), Some(field)) => {
1949 check_metadata_with_storage_equal(
1950 (field.data_type(), Some(field.metadata())),
1951 (prev.data_type(), Some(prev.metadata())),
1952 "parameter",
1953 &format!(": Conflicting types for id {id}"),
1954 )?;
1955 }
1956 (_, Some(field)) => {
1957 param_types.insert(id.clone(), Some(Arc::clone(field)));
1958 }
1959 _ => {
1960 param_types.entry(id.clone()).or_insert(None);
1961 }
1962 }
1963 }
1964 Ok(TreeNodeRecursion::Continue)
1965 })
1966 })
1967 })?;
1968
1969 for id in row_count_parameters {
1970 param_types
1971 .entry(id)
1972 .or_default()
1973 .get_or_insert_with(|| Arc::new(Field::new("", DataType::Int64, true)));
1974 }
1975 Ok(param_types)
1976 }
1977
1978 pub fn display_indent(&self) -> impl Display + '_ {
2010 struct Wrapper<'a>(&'a LogicalPlan);
2013 impl Display for Wrapper<'_> {
2014 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2015 let with_schema = false;
2016 let mut visitor = IndentVisitor::new(f, with_schema);
2017 match self.0.visit_with_subqueries(&mut visitor) {
2018 Ok(_) => Ok(()),
2019 Err(_) => Err(fmt::Error),
2020 }
2021 }
2022 }
2023 Wrapper(self)
2024 }
2025
2026 pub fn display_indent_schema(&self) -> impl Display + '_ {
2056 struct Wrapper<'a>(&'a LogicalPlan);
2059 impl Display for Wrapper<'_> {
2060 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2061 let with_schema = true;
2062 let mut visitor = IndentVisitor::new(f, with_schema);
2063 match self.0.visit_with_subqueries(&mut visitor) {
2064 Ok(_) => Ok(()),
2065 Err(_) => Err(fmt::Error),
2066 }
2067 }
2068 }
2069 Wrapper(self)
2070 }
2071
2072 pub fn display_pg_json(&self) -> impl Display + '_ {
2076 struct Wrapper<'a>(&'a LogicalPlan);
2079 impl Display for Wrapper<'_> {
2080 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2081 let mut visitor = PgJsonVisitor::new(f);
2082 visitor.with_schema(true);
2083 match self.0.visit_with_subqueries(&mut visitor) {
2084 Ok(_) => Ok(()),
2085 Err(_) => Err(fmt::Error),
2086 }
2087 }
2088 }
2089 Wrapper(self)
2090 }
2091
2092 pub fn display_graphviz(&self) -> impl Display + '_ {
2122 struct Wrapper<'a>(&'a LogicalPlan);
2125 impl Display for Wrapper<'_> {
2126 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2127 let mut visitor = GraphvizVisitor::new(f);
2128
2129 visitor.start_graph()?;
2130
2131 visitor.pre_visit_plan("LogicalPlan")?;
2132 self.0
2133 .visit_with_subqueries(&mut visitor)
2134 .map_err(|_| fmt::Error)?;
2135 visitor.post_visit_plan()?;
2136
2137 visitor.set_with_schema(true);
2138 visitor.pre_visit_plan("Detailed LogicalPlan")?;
2139 self.0
2140 .visit_with_subqueries(&mut visitor)
2141 .map_err(|_| fmt::Error)?;
2142 visitor.post_visit_plan()?;
2143
2144 visitor.end_graph()?;
2145 Ok(())
2146 }
2147 }
2148 Wrapper(self)
2149 }
2150
2151 pub fn display(&self) -> impl Display + '_ {
2173 struct Wrapper<'a>(&'a LogicalPlan);
2176 impl Display for Wrapper<'_> {
2177 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2178 match self.0 {
2179 LogicalPlan::EmptyRelation(EmptyRelation {
2180 produce_one_row,
2181 schema: _,
2182 }) => {
2183 let rows = i32::from(*produce_one_row);
2184 write!(f, "EmptyRelation: rows={rows}")
2185 }
2186 LogicalPlan::RecursiveQuery(RecursiveQuery {
2187 is_distinct, ..
2188 }) => {
2189 write!(f, "RecursiveQuery: is_distinct={is_distinct}")
2190 }
2191 LogicalPlan::Values(Values { values, .. }) => {
2192 let str_values: Vec<_> = values
2193 .iter()
2194 .take(5)
2196 .map(|row| {
2197 let item = row
2198 .iter()
2199 .map(|expr| expr.to_string())
2200 .collect::<Vec<_>>()
2201 .join(", ");
2202 format!("({item})")
2203 })
2204 .collect();
2205
2206 let eclipse = if values.len() > 5 { "..." } else { "" };
2207 write!(f, "Values: {}{}", str_values.join(", "), eclipse)
2208 }
2209
2210 LogicalPlan::TableScan(TableScan {
2211 source,
2212 table_name,
2213 projection,
2214 filters,
2215 fetch,
2216 skip,
2217 ..
2218 }) => {
2219 let projected_fields = match projection {
2220 Some(indices) => {
2221 let schema = source.schema();
2222 let names: Vec<&str> = indices
2223 .iter()
2224 .map(|i| schema.field(*i).name().as_str())
2225 .collect();
2226 format!(" projection=[{}]", names.join(", "))
2227 }
2228 _ => "".to_string(),
2229 };
2230
2231 write!(f, "TableScan: {table_name}{projected_fields}")?;
2232
2233 if !filters.is_empty() {
2234 let mut full_filter = vec![];
2235 let mut partial_filter = vec![];
2236 let mut unsupported_filters = vec![];
2237 let filters: Vec<&Expr> = filters.iter().collect();
2238
2239 if let Ok(results) =
2240 source.supports_filters_pushdown(&filters)
2241 {
2242 filters.iter().zip(results.iter()).for_each(
2243 |(x, res)| match res {
2244 TableProviderFilterPushDown::Exact => {
2245 full_filter.push(x)
2246 }
2247 TableProviderFilterPushDown::Inexact => {
2248 partial_filter.push(x)
2249 }
2250 TableProviderFilterPushDown::Unsupported => {
2251 unsupported_filters.push(x)
2252 }
2253 },
2254 );
2255 }
2256
2257 if !full_filter.is_empty() {
2258 write!(
2259 f,
2260 ", full_filters=[{}]",
2261 expr_vec_fmt!(full_filter)
2262 )?;
2263 }
2264 if !partial_filter.is_empty() {
2265 write!(
2266 f,
2267 ", partial_filters=[{}]",
2268 expr_vec_fmt!(partial_filter)
2269 )?;
2270 }
2271 if !unsupported_filters.is_empty() {
2272 write!(
2273 f,
2274 ", unsupported_filters=[{}]",
2275 expr_vec_fmt!(unsupported_filters)
2276 )?;
2277 }
2278 }
2279
2280 if let Some(n) = fetch {
2281 write!(f, ", fetch={n}")?;
2282 }
2283
2284 if let Some(n) = skip {
2285 write!(f, ", skip={n}")?;
2286 }
2287
2288 Ok(())
2289 }
2290 LogicalPlan::Projection(Projection { expr, .. }) => {
2291 write!(f, "Projection:")?;
2292 for (i, expr_item) in expr.iter().enumerate() {
2293 if i > 0 {
2294 write!(f, ",")?;
2295 }
2296 write!(f, " {expr_item}")?;
2297 }
2298 Ok(())
2299 }
2300 LogicalPlan::Dml(DmlStatement { table_name, op, .. }) => {
2301 write!(f, "Dml: op=[{op}] table=[{table_name}]")?;
2302 if let WriteOp::MergeInto(merge_op) = op {
2303 write!(f, " {merge_op}")?;
2304 }
2305 Ok(())
2306 }
2307 LogicalPlan::Copy(CopyTo {
2308 input: _,
2309 output_url,
2310 file_type,
2311 options,
2312 ..
2313 }) => {
2314 let op_str = options
2315 .iter()
2316 .map(|(k, v)| format!("{k} {v}"))
2317 .collect::<Vec<String>>()
2318 .join(", ");
2319
2320 write!(
2321 f,
2322 "CopyTo: format={} output_url={output_url} options: ({op_str})",
2323 file_type.get_ext()
2324 )
2325 }
2326 LogicalPlan::Ddl(ddl) => {
2327 write!(f, "{}", ddl.display())
2328 }
2329 LogicalPlan::Filter(Filter {
2330 predicate: expr, ..
2331 }) => write!(f, "Filter: {expr}"),
2332 LogicalPlan::Window(Window { window_expr, .. }) => {
2333 write!(
2334 f,
2335 "WindowAggr: windowExpr=[[{}]]",
2336 expr_vec_fmt!(window_expr)
2337 )
2338 }
2339 LogicalPlan::Aggregate(Aggregate {
2340 group_expr,
2341 aggr_expr,
2342 ..
2343 }) => write!(
2344 f,
2345 "Aggregate: groupBy=[[{}]], aggr=[[{}]]",
2346 expr_vec_fmt!(group_expr),
2347 expr_vec_fmt!(aggr_expr)
2348 ),
2349 LogicalPlan::Sort(Sort { expr, fetch, .. }) => {
2350 write!(f, "Sort: ")?;
2351 for (i, expr_item) in expr.iter().enumerate() {
2352 if i > 0 {
2353 write!(f, ", ")?;
2354 }
2355 write!(f, "{expr_item}")?;
2356 }
2357 if let Some(a) = fetch {
2358 write!(f, ", fetch={a}")?;
2359 }
2360
2361 Ok(())
2362 }
2363 LogicalPlan::Join(Join {
2364 on: keys,
2365 filter,
2366 join_constraint,
2367 join_type,
2368 null_aware,
2369 null_aware_value_keys,
2370 ..
2371 }) => {
2372 let join_expr: Vec<String> =
2373 keys.iter().map(|(l, r)| format!("{l} = {r}")).collect();
2374 let filter_expr = filter
2375 .as_ref()
2376 .map(|expr| format!(" Filter: {expr}"))
2377 .unwrap_or_else(|| "".to_string());
2378 let null_aware_expr = match (*null_aware, *null_aware_value_keys)
2379 {
2380 (false, _) => "".to_string(),
2381 (true, 0 | 1) => " null_aware".to_string(),
2382 (true, n) => format!(" null_aware(value_keys={n})"),
2383 };
2384 let join_type = if filter.is_none()
2385 && keys.is_empty()
2386 && *join_type == JoinType::Inner
2387 {
2388 "Cross".to_string()
2389 } else {
2390 join_type.to_string()
2391 };
2392 match join_constraint {
2393 JoinConstraint::On => {
2394 write!(f, "{join_type} Join:")?;
2395 if !join_expr.is_empty() || !filter_expr.is_empty() {
2396 write!(
2397 f,
2398 " {}{}",
2399 join_expr.join(", "),
2400 filter_expr
2401 )?;
2402 }
2403 write!(f, "{null_aware_expr}")?;
2404 Ok(())
2405 }
2406 JoinConstraint::Using => {
2407 write!(
2408 f,
2409 "{} Join: Using {}{}{}",
2410 join_type,
2411 join_expr.join(", "),
2412 filter_expr,
2413 null_aware_expr,
2414 )
2415 }
2416 }
2417 }
2418 LogicalPlan::AsOfJoin(AsOfJoin {
2419 on,
2420 match_condition,
2421 join_constraint,
2422 ..
2423 }) => {
2424 let equality = on
2425 .iter()
2426 .map(|(left, right)| format!("{left} = {right}"))
2427 .join(", ");
2428 write!(
2429 f,
2430 "AsOf Join: match=[{match_condition}], constraint={join_constraint:?}"
2431 )?;
2432 if !equality.is_empty() {
2433 write!(f, ", on=[{equality}]")?;
2434 }
2435 Ok(())
2436 }
2437 LogicalPlan::Repartition(Repartition {
2438 partitioning_scheme,
2439 ..
2440 }) => match partitioning_scheme {
2441 Partitioning::RoundRobinBatch(n) => {
2442 write!(f, "Repartition: RoundRobinBatch partition_count={n}")
2443 }
2444 Partitioning::Hash(expr, n) => {
2445 let hash_expr: Vec<String> =
2446 expr.iter().map(|e| format!("{e}")).collect();
2447 write!(
2448 f,
2449 "Repartition: Hash({}) partition_count={}",
2450 hash_expr.join(", "),
2451 n
2452 )
2453 }
2454 Partitioning::Range(range) => {
2455 write!(f, "Repartition: {range}")
2456 }
2457 Partitioning::DistributeBy(expr) => {
2458 let dist_by_expr: Vec<String> =
2459 expr.iter().map(|e| format!("{e}")).collect();
2460 write!(
2461 f,
2462 "Repartition: DistributeBy({})",
2463 dist_by_expr.join(", "),
2464 )
2465 }
2466 },
2467 LogicalPlan::Limit(limit) => {
2468 let skip_str = match limit.get_skip_type() {
2470 Ok(SkipType::Literal(n)) => n.to_string(),
2471 _ => limit
2472 .skip
2473 .as_ref()
2474 .map_or_else(|| "None".to_string(), |x| x.to_string()),
2475 };
2476 let fetch_str = match limit.get_fetch_type() {
2477 Ok(FetchType::Literal(Some(n))) => n.to_string(),
2478 Ok(FetchType::Literal(None)) => "None".to_string(),
2479 _ => limit
2480 .fetch
2481 .as_ref()
2482 .map_or_else(|| "None".to_string(), |x| x.to_string()),
2483 };
2484 write!(f, "Limit: skip={skip_str}, fetch={fetch_str}")
2485 }
2486 LogicalPlan::Subquery(Subquery { .. }) => {
2487 write!(f, "Subquery:")
2488 }
2489 LogicalPlan::SubqueryAlias(SubqueryAlias { alias, .. }) => {
2490 write!(f, "SubqueryAlias: {alias}")
2491 }
2492 LogicalPlan::Statement(statement) => {
2493 write!(f, "{}", statement.display())
2494 }
2495 LogicalPlan::Distinct(distinct) => match distinct {
2496 Distinct::All(_) => write!(f, "Distinct:"),
2497 Distinct::On(DistinctOn {
2498 on_expr,
2499 select_expr,
2500 sort_expr,
2501 ..
2502 }) => write!(
2503 f,
2504 "DistinctOn: on_expr=[[{}]], select_expr=[[{}]], sort_expr=[[{}]]",
2505 expr_vec_fmt!(on_expr),
2506 expr_vec_fmt!(select_expr),
2507 if let Some(sort_expr) = sort_expr {
2508 expr_vec_fmt!(sort_expr)
2509 } else {
2510 "".to_string()
2511 },
2512 ),
2513 },
2514 LogicalPlan::Explain { .. } => write!(f, "Explain"),
2515 LogicalPlan::Analyze { .. } => write!(f, "Analyze"),
2516 LogicalPlan::Union(_) => write!(f, "Union"),
2517 LogicalPlan::Extension(e) => e.node.fmt_for_explain(f),
2518 LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
2519 MaterializedCte { name, .. },
2520 )) => {
2521 write!(f, "MaterializedCte: name={name}")
2522 }
2523 LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(
2524 MaterializedCteScan { name, .. },
2525 )) => {
2526 write!(f, "MaterializedCteScan: name={name}")
2527 }
2528 LogicalPlan::Show(Show { kind, .. }) => match kind {
2529 ShowKind::Describe { .. }
2530 | ShowKind::Columns {
2531 detail: ColumnsDetail::Describe,
2532 ..
2533 } => write!(f, "DescribeTable"),
2534 ShowKind::Tables => write!(f, "ShowTables"),
2535 ShowKind::Columns { .. } => write!(f, "ShowColumns"),
2536 ShowKind::CreateTable { .. } => write!(f, "ShowCreateTable"),
2537 ShowKind::Variables { .. } => write!(f, "ShowVariables"),
2538 ShowKind::Functions { .. } => write!(f, "ShowFunctions"),
2539 },
2540 LogicalPlan::Unnest(Unnest {
2541 input: plan,
2542 list_type_columns: list_col_indices,
2543 struct_type_columns: struct_col_indices,
2544 ..
2545 }) => {
2546 let input_columns = plan.schema().columns();
2547 let list_type_columns = list_col_indices
2548 .iter()
2549 .map(|(i, unnest_info)| {
2550 format!(
2551 "{}|depth={}",
2552 input_columns[*i], unnest_info.depth
2553 )
2554 })
2555 .collect::<Vec<String>>();
2556 let struct_type_columns = struct_col_indices
2557 .iter()
2558 .map(|i| &input_columns[*i])
2559 .collect::<Vec<&Column>>();
2560 write!(
2562 f,
2563 "Unnest: lists[{}] structs[{}]",
2564 expr_vec_fmt!(list_type_columns),
2565 expr_vec_fmt!(struct_type_columns)
2566 )
2567 }
2568 }
2569 }
2570 }
2571 Wrapper(self)
2572 }
2573
2574 pub fn resolve_lambda_variables(self) -> Result<Transformed<LogicalPlan>> {
2578 self.transform_with_subqueries(|plan| {
2579 let schema = merge_schema(&plan.inputs());
2580
2581 plan.map_expressions(|expr| expr.resolve_lambda_variables(&schema))
2582 })
2583 }
2584}
2585
2586impl Display for LogicalPlan {
2587 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2588 self.display_indent().fmt(f)
2589 }
2590}
2591
2592impl ToStringifiedPlan for LogicalPlan {
2593 fn to_stringified(&self, plan_type: PlanType) -> StringifiedPlan {
2594 StringifiedPlan::new(plan_type, self.display_indent().to_string())
2595 }
2596}
2597
2598#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2602pub struct EmptyRelation {
2603 pub produce_one_row: bool,
2605 pub schema: DFSchemaRef,
2607}
2608
2609impl PartialOrd for EmptyRelation {
2611 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2612 self.produce_one_row
2613 .partial_cmp(&other.produce_one_row)
2614 .filter(|cmp| *cmp != Ordering::Equal || self == other)
2616 }
2617}
2618
2619#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2642pub struct RecursiveQuery {
2643 pub name: String,
2645 pub static_term: Arc<LogicalPlan>,
2647 pub recursive_term: Arc<LogicalPlan>,
2650 pub is_distinct: bool,
2653 pub schema: DFSchemaRef,
2655}
2656
2657impl PartialOrd for RecursiveQuery {
2658 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2659 match self.name.partial_cmp(&other.name) {
2660 Some(Ordering::Equal) => {
2661 match self.static_term.partial_cmp(&other.static_term) {
2662 Some(Ordering::Equal) => {
2663 match self.recursive_term.partial_cmp(&other.recursive_term) {
2664 Some(Ordering::Equal) => {
2665 self.is_distinct.partial_cmp(&other.is_distinct)
2666 }
2667 cmp => cmp,
2668 }
2669 }
2670 cmp => cmp,
2671 }
2672 }
2673 cmp => cmp,
2674 }
2675 .filter(|cmp| *cmp != Ordering::Equal || self == other)
2679 }
2680}
2681
2682impl RecursiveQuery {
2683 pub fn try_new(
2684 name: String,
2685 static_term: Arc<LogicalPlan>,
2686 recursive_term: Arc<LogicalPlan>,
2687 is_distinct: bool,
2688 ) -> Result<Self> {
2689 let schema =
2690 recursive_query_output_schema(static_term.schema(), recursive_term.schema())?;
2691 Ok(Self {
2692 name,
2693 static_term,
2694 recursive_term,
2695 is_distinct,
2696 schema,
2697 })
2698 }
2699}
2700
2701fn recursive_query_output_schema(
2712 static_schema: &DFSchemaRef,
2713 recursive_schema: &DFSchemaRef,
2714) -> Result<DFSchemaRef> {
2715 if static_schema.fields().len() != recursive_schema.fields().len() {
2716 return Err(DataFusionError::Plan(format!(
2717 "Non-recursive term and recursive term must have the same number of columns ({} != {})",
2718 static_schema.fields().len(),
2719 recursive_schema.fields().len()
2720 )));
2721 }
2722
2723 let fields = static_schema
2724 .iter()
2725 .zip(recursive_schema.fields())
2726 .map(|((qualifier, static_field), recursive_field)| {
2727 let nullable = static_field.is_nullable() || recursive_field.is_nullable();
2728 (
2729 qualifier.cloned(),
2730 static_field.as_ref().clone().with_nullable(nullable).into(),
2731 )
2732 })
2733 .collect::<Vec<_>>();
2734
2735 DFSchema::new_with_metadata(fields, static_schema.metadata().clone())
2736 .map(DFSchemaRef::new)
2737}
2738
2739#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2743pub struct Values {
2744 pub schema: DFSchemaRef,
2746 pub values: Vec<Vec<Expr>>,
2748}
2749
2750impl PartialOrd for Values {
2752 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2753 self.values
2754 .partial_cmp(&other.values)
2755 .filter(|cmp| *cmp != Ordering::Equal || self == other)
2757 }
2758}
2759
2760#[derive(Clone, PartialEq, Eq, Hash, Debug)]
2763#[non_exhaustive]
2765pub struct Projection {
2766 pub expr: Vec<Expr>,
2768 pub input: Arc<LogicalPlan>,
2770 pub schema: DFSchemaRef,
2772}
2773
2774impl PartialOrd for Projection {
2776 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2777 match self.expr.partial_cmp(&other.expr) {
2778 Some(Ordering::Equal) => self.input.partial_cmp(&other.input),
2779 cmp => cmp,
2780 }
2781 .filter(|cmp| *cmp != Ordering::Equal || self == other)
2783 }
2784}
2785
2786impl Projection {
2787 pub fn try_new(expr: Vec<Expr>, input: Arc<LogicalPlan>) -> Result<Self> {
2789 let projection_schema = projection_schema(&input, &expr)?;
2790 Self::try_new_with_schema(expr, input, projection_schema)
2791 }
2792
2793 pub fn try_new_with_schema(
2795 expr: Vec<Expr>,
2796 input: Arc<LogicalPlan>,
2797 schema: DFSchemaRef,
2798 ) -> Result<Self> {
2799 #[expect(deprecated)]
2800 if !expr.iter().any(|e| matches!(e, Expr::Wildcard { .. }))
2801 && expr.len() != schema.fields().len()
2802 {
2803 return plan_err!(
2804 "Projection has mismatch between number of expressions ({}) and number of fields in schema ({})",
2805 expr.len(),
2806 schema.fields().len()
2807 );
2808 }
2809 Ok(Self {
2810 expr,
2811 input,
2812 schema,
2813 })
2814 }
2815
2816 pub fn new_from_schema(input: Arc<LogicalPlan>, schema: DFSchemaRef) -> Self {
2818 let expr: Vec<Expr> = schema.columns().into_iter().map(Expr::Column).collect();
2819 Self {
2820 expr,
2821 input,
2822 schema,
2823 }
2824 }
2825}
2826
2827pub fn projection_schema(input: &LogicalPlan, exprs: &[Expr]) -> Result<Arc<DFSchema>> {
2847 let metadata = input.schema().metadata().clone();
2849
2850 let schema =
2852 DFSchema::new_with_metadata(exprlist_to_fields(exprs, input)?, metadata)?
2853 .with_functional_dependencies(calc_func_dependencies_for_project(
2854 exprs, input,
2855 )?)?;
2856
2857 Ok(Arc::new(schema))
2858}
2859
2860#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2862#[non_exhaustive]
2864pub struct SubqueryAlias {
2865 pub input: Arc<LogicalPlan>,
2867 pub alias: TableReference,
2869 pub schema: DFSchemaRef,
2871}
2872
2873impl SubqueryAlias {
2874 pub fn try_new(
2875 plan: Arc<LogicalPlan>,
2876 alias: impl Into<TableReference>,
2877 ) -> Result<Self> {
2878 let alias = alias.into();
2879
2880 let aliases = unique_field_aliases(plan.schema().fields());
2886 let is_projection_needed = aliases.iter().any(Option::is_some);
2887
2888 let plan = if is_projection_needed {
2890 let projection_expressions = aliases
2891 .iter()
2892 .zip(plan.schema().iter())
2893 .map(|(alias, (qualifier, field))| {
2894 let column =
2895 Expr::Column(Column::new(qualifier.cloned(), field.name()));
2896 match alias {
2897 None => column,
2898 Some(alias) => {
2899 Expr::Alias(Alias::new(column, qualifier.cloned(), alias))
2900 }
2901 }
2902 })
2903 .collect();
2904 let projection = Projection::try_new(projection_expressions, plan)?;
2905 Arc::new(LogicalPlan::Projection(projection))
2906 } else {
2907 plan
2908 };
2909
2910 let fields = plan.schema().fields().clone();
2912 let meta_data = plan.schema().metadata().clone();
2913 let func_dependencies = plan.schema().functional_dependencies().clone();
2914
2915 let schema = DFSchema::from_unqualified_fields(fields, meta_data)?;
2916 let schema = schema.as_arrow();
2917
2918 let schema = DFSchemaRef::new(
2919 DFSchema::try_from_qualified_schema(alias.clone(), schema)?
2920 .with_functional_dependencies(func_dependencies)?,
2921 );
2922 Ok(SubqueryAlias {
2923 input: plan,
2924 alias,
2925 schema,
2926 })
2927 }
2928}
2929
2930impl PartialOrd for SubqueryAlias {
2932 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2933 match self.input.partial_cmp(&other.input) {
2934 Some(Ordering::Equal) => self.alias.partial_cmp(&other.alias),
2935 cmp => cmp,
2936 }
2937 .filter(|cmp| *cmp != Ordering::Equal || self == other)
2939 }
2940}
2941
2942#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
2954#[non_exhaustive]
2955pub struct Filter {
2956 pub predicate: Expr,
2958 pub input: Arc<LogicalPlan>,
2960}
2961
2962impl Filter {
2963 #[doc(hidden)]
2979 pub fn new(predicate: Expr, input: Arc<LogicalPlan>) -> Self {
2980 Self { predicate, input }
2981 }
2982
2983 pub fn try_new(predicate: Expr, input: Arc<LogicalPlan>) -> Result<Self> {
2992 Self::try_new_internal(predicate, input)
2993 }
2994
2995 fn is_allowed_filter_type(data_type: &DataType) -> bool {
2996 match data_type {
2997 DataType::Boolean | DataType::Null => true,
2999 DataType::Dictionary(_, value_type) => {
3000 Filter::is_allowed_filter_type(value_type.as_ref())
3001 }
3002 _ => false,
3003 }
3004 }
3005
3006 fn try_new_internal(predicate: Expr, input: Arc<LogicalPlan>) -> Result<Self> {
3007 check_no_window_functions(&predicate, "filter predicates")?;
3011
3012 if let Ok(predicate_type) = predicate.get_type(input.schema())
3017 && !Filter::is_allowed_filter_type(&predicate_type)
3018 {
3019 return plan_err!(
3020 "Cannot create filter with non-boolean predicate '{predicate}' returning {predicate_type}"
3021 );
3022 }
3023
3024 Ok(Self {
3025 predicate: predicate.unalias_nested().data,
3026 input,
3027 })
3028 }
3029
3030 fn is_scalar(&self) -> bool {
3046 let schema = self.input.schema();
3047
3048 let functional_dependencies = self.input.schema().functional_dependencies();
3049 let unique_keys = functional_dependencies.iter().filter(|dep| {
3050 let nullable = dep.nullable
3051 && dep
3052 .source_indices
3053 .iter()
3054 .any(|&source| schema.field(source).is_nullable());
3055 !nullable
3056 && dep.mode == Dependency::Single
3057 && dep.target_indices.len() == schema.fields().len()
3058 });
3059
3060 let exprs = split_conjunction(&self.predicate);
3061 let eq_pred_cols: HashSet<_> = exprs
3062 .iter()
3063 .filter_map(|expr| {
3064 let Expr::BinaryExpr(BinaryExpr {
3065 left,
3066 op: Operator::Eq,
3067 right,
3068 }) = expr
3069 else {
3070 return None;
3071 };
3072 if left == right {
3074 return None;
3075 }
3076
3077 match (left.as_ref(), right.as_ref()) {
3078 (Expr::Column(_), Expr::Column(_)) => None,
3079 (Expr::Column(c), _) | (_, Expr::Column(c)) => {
3080 Some(schema.index_of_column(c).unwrap())
3081 }
3082 _ => None,
3083 }
3084 })
3085 .collect();
3086
3087 for key in unique_keys {
3090 if key.source_indices.iter().all(|c| eq_pred_cols.contains(c)) {
3091 return true;
3092 }
3093 }
3094 false
3095 }
3096}
3097
3098#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3113pub struct Window {
3114 pub input: Arc<LogicalPlan>,
3116 pub window_expr: Vec<Expr>,
3118 pub schema: DFSchemaRef,
3120}
3121
3122impl Window {
3123 pub fn try_new(window_expr: Vec<Expr>, input: Arc<LogicalPlan>) -> Result<Self> {
3125 check_aggregate_and_window_nesting(window_expr.iter())?;
3129
3130 let fields: Vec<(Option<TableReference>, Arc<Field>)> = input
3131 .schema()
3132 .iter()
3133 .map(|(q, f)| (q.cloned(), Arc::clone(f)))
3134 .collect();
3135 let input_len = fields.len();
3136 let mut window_fields = fields;
3137 let expr_fields = exprlist_to_fields(window_expr.as_slice(), &input)?;
3138 window_fields.extend_from_slice(expr_fields.as_slice());
3139 let metadata = input.schema().metadata().clone();
3140
3141 let mut window_func_dependencies =
3143 input.schema().functional_dependencies().clone();
3144 window_func_dependencies.extend_target_indices(window_fields.len());
3145
3146 let mut new_dependencies = window_expr
3150 .iter()
3151 .enumerate()
3152 .filter_map(|(idx, expr)| {
3153 let Expr::WindowFunction(window_fun) = expr else {
3154 return None;
3155 };
3156 let WindowFunction {
3157 fun: WindowFunctionDefinition::WindowUDF(udwf),
3158 params: WindowFunctionParams { partition_by, .. },
3159 } = window_fun.as_ref()
3160 else {
3161 return None;
3162 };
3163 if udwf.name() == "row_number" && partition_by.is_empty() {
3166 Some(idx + input_len)
3167 } else {
3168 None
3169 }
3170 })
3171 .map(|idx| {
3172 FunctionalDependence::new(vec![idx], vec![], false)
3173 .with_mode(Dependency::Single)
3174 })
3175 .collect::<Vec<_>>();
3176
3177 if !new_dependencies.is_empty() {
3178 for dependence in new_dependencies.iter_mut() {
3179 dependence.target_indices = (0..window_fields.len()).collect();
3180 }
3181 let new_deps = FunctionalDependencies::new(new_dependencies);
3183 window_func_dependencies.extend(new_deps);
3184 }
3185
3186 if let Some(e) = window_expr.iter().find(|e| {
3188 matches!(
3189 e,
3190 Expr::WindowFunction(wf)
3191 if !matches!(wf.fun, WindowFunctionDefinition::AggregateUDF(_))
3192 && wf.params.filter.is_some()
3193 )
3194 }) {
3195 return plan_err!(
3196 "FILTER clause can only be used with aggregate window functions. Found in '{e}'"
3197 );
3198 }
3199
3200 Self::try_new_with_schema(
3201 window_expr,
3202 input,
3203 Arc::new(
3204 DFSchema::new_with_metadata(window_fields, metadata)?
3205 .with_functional_dependencies(window_func_dependencies)?,
3206 ),
3207 )
3208 }
3209
3210 pub fn try_new_with_schema(
3216 window_expr: Vec<Expr>,
3217 input: Arc<LogicalPlan>,
3218 schema: DFSchemaRef,
3219 ) -> Result<Self> {
3220 let input_fields_count = input.schema().fields().len();
3221 if schema.fields().len() != input_fields_count + window_expr.len() {
3222 return plan_err!(
3223 "Window schema has wrong number of fields. Expected {} got {}",
3224 input_fields_count + window_expr.len(),
3225 schema.fields().len()
3226 );
3227 }
3228
3229 Ok(Window {
3230 input,
3231 window_expr,
3232 schema,
3233 })
3234 }
3235}
3236
3237impl PartialOrd for Window {
3239 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3240 match self.input.partial_cmp(&other.input)? {
3241 Ordering::Equal => {} not_equal => return Some(not_equal),
3243 }
3244
3245 match self.window_expr.partial_cmp(&other.window_expr)? {
3246 Ordering::Equal => {} not_equal => return Some(not_equal),
3248 }
3249
3250 if self == other {
3253 Some(Ordering::Equal)
3254 } else {
3255 None
3256 }
3257 }
3258}
3259
3260#[derive(Clone)]
3262pub struct TableScan {
3263 pub table_name: TableReference,
3265 pub source: Arc<dyn TableSource>,
3267 pub projection: Option<Vec<usize>>,
3269 pub projected_schema: DFSchemaRef,
3271 pub filters: Vec<Expr>,
3273 pub fetch: Option<usize>,
3275 pub skip: Option<usize>,
3277 pub statistics_requests: Box<BTreeSet<StatisticsRequest>>,
3287}
3288
3289impl Debug for TableScan {
3290 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
3291 f.debug_struct("TableScan")
3292 .field("table_name", &self.table_name)
3293 .field("source", &"...")
3294 .field("projection", &self.projection)
3295 .field("projected_schema", &self.projected_schema)
3296 .field("filters", &self.filters)
3297 .field("fetch", &self.fetch)
3298 .field("skip", &self.skip)
3299 .finish_non_exhaustive()
3300 }
3301}
3302
3303impl PartialEq for TableScan {
3304 fn eq(&self, other: &Self) -> bool {
3305 self.table_name == other.table_name
3306 && self.projection == other.projection
3307 && self.projected_schema == other.projected_schema
3308 && self.filters == other.filters
3309 && self.fetch == other.fetch
3310 }
3311}
3312
3313impl Eq for TableScan {}
3314
3315impl PartialOrd for TableScan {
3318 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3319 #[derive(PartialEq, PartialOrd)]
3320 struct ComparableTableScan<'a> {
3321 pub table_name: &'a TableReference,
3323 pub projection: &'a Option<Vec<usize>>,
3325 pub filters: &'a Vec<Expr>,
3327 pub fetch: &'a Option<usize>,
3329 }
3330 let comparable_self = ComparableTableScan {
3331 table_name: &self.table_name,
3332 projection: &self.projection,
3333 filters: &self.filters,
3334 fetch: &self.fetch,
3335 };
3336 let comparable_other = ComparableTableScan {
3337 table_name: &other.table_name,
3338 projection: &other.projection,
3339 filters: &other.filters,
3340 fetch: &other.fetch,
3341 };
3342 comparable_self
3343 .partial_cmp(&comparable_other)
3344 .filter(|cmp| *cmp != Ordering::Equal || self == other)
3346 }
3347}
3348
3349impl Hash for TableScan {
3350 fn hash<H: Hasher>(&self, state: &mut H) {
3351 self.table_name.hash(state);
3352 self.projection.hash(state);
3353 self.projected_schema.hash(state);
3354 self.filters.hash(state);
3355 self.fetch.hash(state);
3356 }
3357}
3358
3359impl TableScan {
3360 #[deprecated(since = "54.0.0", note = "use `TableScanBuilder` instead")]
3363 pub fn try_new(
3364 table_name: impl Into<TableReference>,
3365 table_source: Arc<dyn TableSource>,
3366 projection: Option<Vec<usize>>,
3367 filters: Vec<Expr>,
3368 fetch: Option<usize>,
3369 ) -> Result<Self> {
3370 TableScanBuilder::new(table_name, table_source)
3371 .with_projection(projection)
3372 .with_filters(filters)
3373 .with_fetch(fetch)
3374 .build()
3375 }
3376}
3377
3378pub struct TableScanBuilder {
3386 table_name: TableReference,
3387 source: Arc<dyn TableSource>,
3388 projection: Option<Vec<usize>>,
3389 filters: Vec<Expr>,
3390 fetch: Option<usize>,
3391 skip: Option<usize>,
3392 #[expect(clippy::box_collection)] statistics_requests: Box<BTreeSet<StatisticsRequest>>,
3394}
3395
3396impl TableScanBuilder {
3397 pub fn new(
3399 table_name: impl Into<TableReference>,
3400 source: Arc<dyn TableSource>,
3401 ) -> Self {
3402 Self {
3403 table_name: table_name.into(),
3404 source,
3405 projection: None,
3406 filters: vec![],
3407 fetch: None,
3408 skip: None,
3409 statistics_requests: Box::default(),
3410 }
3411 }
3412
3413 pub fn with_projection(mut self, projection: Option<Vec<usize>>) -> Self {
3415 self.projection = projection;
3416 self
3417 }
3418
3419 pub fn with_filters(mut self, filters: Vec<Expr>) -> Self {
3421 self.filters = filters;
3422 self
3423 }
3424
3425 pub fn with_fetch(mut self, fetch: Option<usize>) -> Self {
3427 self.fetch = fetch;
3428 self
3429 }
3430
3431 pub fn with_skip(mut self, skip: Option<usize>) -> Self {
3433 self.skip = skip;
3434 self
3435 }
3436
3437 pub fn with_statistics_requests(
3440 mut self,
3441 statistics_requests: BTreeSet<StatisticsRequest>,
3442 ) -> Self {
3443 self.statistics_requests = Box::new(statistics_requests);
3444 self
3445 }
3446
3447 pub fn build(self) -> Result<TableScan> {
3450 let TableScanBuilder {
3451 table_name,
3452 source,
3453 projection,
3454 filters,
3455 fetch,
3456 skip,
3457 statistics_requests,
3458 } = self;
3459
3460 if table_name.table().is_empty() {
3461 return plan_err!("table_name cannot be empty");
3462 }
3463 let schema = source.schema();
3464 let func_dependencies = FunctionalDependencies::new_from_constraints(
3465 source.constraints(),
3466 schema.fields.len(),
3467 );
3468 let projected_schema = projection
3469 .as_ref()
3470 .map(|p| {
3471 let projected_func_dependencies =
3472 func_dependencies.project_functional_dependencies(p, p.len());
3473
3474 let df_schema = DFSchema::new_with_metadata(
3475 p.iter()
3476 .map(|i| {
3477 (Some(table_name.clone()), Arc::clone(&schema.fields()[*i]))
3478 })
3479 .collect(),
3480 schema.metadata.clone(),
3481 )?;
3482 df_schema.with_functional_dependencies(projected_func_dependencies)
3483 })
3484 .unwrap_or_else(|| {
3485 let df_schema =
3486 DFSchema::try_from_qualified_schema(table_name.clone(), &schema)?;
3487 df_schema.with_functional_dependencies(func_dependencies)
3488 })?;
3489 let projected_schema = Arc::new(projected_schema);
3490
3491 Ok(TableScan {
3492 table_name,
3493 source,
3494 projection,
3495 projected_schema,
3496 filters,
3497 fetch,
3498 skip,
3499 statistics_requests,
3500 })
3501 }
3502}
3503
3504impl From<TableScan> for TableScanBuilder {
3505 fn from(scan: TableScan) -> Self {
3506 Self {
3507 table_name: scan.table_name,
3508 source: scan.source,
3509 projection: scan.projection,
3510 filters: scan.filters,
3511 fetch: scan.fetch,
3512 skip: scan.skip,
3513 statistics_requests: scan.statistics_requests,
3514 }
3515 }
3516}
3517
3518#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
3520pub struct Repartition {
3521 pub input: Arc<LogicalPlan>,
3523 pub partitioning_scheme: Partitioning,
3525}
3526
3527#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3529pub struct Union {
3530 pub inputs: Vec<Arc<LogicalPlan>>,
3532 pub schema: DFSchemaRef,
3534}
3535
3536impl Union {
3537 pub fn try_new(inputs: Vec<Arc<LogicalPlan>>) -> Result<Self> {
3540 let schema = Self::derive_schema_from_inputs(&inputs, false, false)?;
3541 Ok(Union { inputs, schema })
3542 }
3543
3544 pub fn try_new_with_loose_types(inputs: Vec<Arc<LogicalPlan>>) -> Result<Self> {
3551 let schema = Self::derive_schema_from_inputs(&inputs, true, false)?;
3552 Ok(Union { inputs, schema })
3553 }
3554
3555 pub fn try_new_by_name(inputs: Vec<Arc<LogicalPlan>>) -> Result<Self> {
3564 let schema = Self::derive_schema_from_inputs(&inputs, true, true)?;
3565 let inputs = Self::rewrite_inputs_from_schema(&schema, inputs)?;
3566
3567 Ok(Union { inputs, schema })
3568 }
3569
3570 fn rewrite_inputs_from_schema(
3574 schema: &Arc<DFSchema>,
3575 inputs: Vec<Arc<LogicalPlan>>,
3576 ) -> Result<Vec<Arc<LogicalPlan>>> {
3577 let schema_width = schema.iter().count();
3578 let mut wrapped_inputs = Vec::with_capacity(inputs.len());
3579 for input in inputs {
3580 let mut expr = Vec::with_capacity(schema_width);
3584 for column in schema.columns() {
3585 if input
3586 .schema()
3587 .has_column_with_unqualified_name(column.name())
3588 {
3589 expr.push(Expr::Column(column));
3590 } else {
3591 expr.push(
3592 Expr::Literal(ScalarValue::Null, None).alias(column.name()),
3593 );
3594 }
3595 }
3596 wrapped_inputs.push(Arc::new(LogicalPlan::Projection(
3597 Projection::try_new_with_schema(expr, input, Arc::clone(schema))?,
3598 )));
3599 }
3600
3601 Ok(wrapped_inputs)
3602 }
3603
3604 fn derive_schema_from_inputs(
3612 inputs: &[Arc<LogicalPlan>],
3613 loose_types: bool,
3614 by_name: bool,
3615 ) -> Result<DFSchemaRef> {
3616 if inputs.len() < 2 {
3617 return plan_err!("UNION requires at least two inputs");
3618 }
3619
3620 if by_name {
3621 Self::derive_schema_from_inputs_by_name(inputs, loose_types)
3622 } else {
3623 Self::derive_schema_from_inputs_by_position(inputs, loose_types)
3624 }
3625 }
3626
3627 fn derive_schema_from_inputs_by_name(
3628 inputs: &[Arc<LogicalPlan>],
3629 loose_types: bool,
3630 ) -> Result<DFSchemaRef> {
3631 let mut cols: Vec<(&str, Vec<Option<&Field>>)> = Vec::new();
3632 for (input_index, input) in inputs.iter().enumerate() {
3633 for field in input.schema().fields() {
3634 if let Some((_, fields)) =
3635 cols.iter_mut().find(|(name, _)| name == field.name())
3636 {
3637 fields[input_index] = Some(field.as_ref());
3638 } else {
3639 let mut fields = vec![None; inputs.len()];
3640 fields[input_index] = Some(field.as_ref());
3641 cols.push((field.name(), fields));
3642 }
3643 }
3644 }
3645
3646 let null_field = Field::new("", DataType::Null, true);
3649 let union_fields = cols
3650 .into_iter()
3651 .map(|(name, fields)| {
3652 let first_type = fields
3653 .iter()
3654 .flatten()
3655 .next()
3656 .expect("column has at least one input field")
3657 .data_type();
3658 let data_type = if loose_types {
3659 coerce_union_type(
3660 fields.iter().map(|field| field.unwrap_or(&null_field)),
3661 )
3662 .unwrap_or_else(|_| first_type.clone())
3663 } else {
3664 if fields
3665 .iter()
3666 .flatten()
3667 .any(|field| field.data_type() != first_type)
3668 {
3669 return plan_err!("Found different types for field {name}");
3670 }
3671 first_type.clone()
3672 };
3673 let nullable = fields
3674 .iter()
3675 .any(|field| field.is_none_or(|field| field.is_nullable()));
3676 let metadata = merge_metadata_for_union(
3677 fields.iter().flatten().map(|field| field.metadata()),
3678 );
3679 Ok((
3680 None,
3681 Arc::new(
3682 Field::new(name, data_type, nullable).with_metadata(metadata),
3683 ),
3684 ))
3685 })
3686 .collect::<Result<Vec<(Option<TableReference>, _)>>>()?;
3687
3688 let union_schema_metadata = merge_metadata_for_union(
3689 inputs.iter().map(|input| input.schema().metadata()),
3690 );
3691
3692 let schema = DFSchema::new_with_metadata(union_fields, union_schema_metadata)?;
3694 let schema = Arc::new(schema);
3695
3696 Ok(schema)
3697 }
3698
3699 fn derive_schema_from_inputs_by_position(
3700 inputs: &[Arc<LogicalPlan>],
3701 loose_types: bool,
3702 ) -> Result<DFSchemaRef> {
3703 let first_schema = inputs[0].schema();
3704 let fields_count = first_schema.fields().len();
3705 for input in inputs.iter().skip(1) {
3706 if fields_count != input.schema().fields().len() {
3707 return plan_err!(
3708 "UNION queries have different number of columns: \
3709 left has {} columns whereas right has {} columns",
3710 fields_count,
3711 input.schema().fields().len()
3712 );
3713 }
3714 }
3715
3716 let mut name_counts: HashMap<String, usize> =
3717 HashMap::with_capacity(fields_count);
3718 let mut fields: Vec<&FieldRef> = Vec::with_capacity(inputs.len());
3719 let union_fields = (0..fields_count)
3720 .map(|i| {
3721 fields.clear();
3722 fields.extend(inputs.iter().map(|input| input.schema().field(i)));
3723 let first_field = fields[0];
3724 let base_name = first_field.name().to_string();
3725
3726 let data_type = if loose_types {
3727 coerce_union_type(fields.iter().map(|field| field.as_ref()))
3728 .unwrap_or_else(|_| first_field.data_type().clone())
3729 } else {
3730 fields
3731 .iter()
3732 .skip(1)
3733 .try_fold(first_field.data_type(), |acc, field| {
3734 if acc != field.data_type() {
3735 return plan_err!(
3736 "UNION field {i} have different type in inputs: \
3737 left has {} whereas right has {}",
3738 first_field.data_type(),
3739 field.data_type()
3740 );
3741 }
3742 Ok(acc)
3743 })?
3744 .clone()
3745 };
3746 let nullable = fields.iter().any(|field| field.is_nullable());
3747
3748 let name = if let Some(count) = name_counts.get_mut(&base_name) {
3750 *count += 1;
3751 format!("{base_name}_{count}")
3752 } else {
3753 name_counts.insert(base_name.clone(), 0);
3754 base_name
3755 };
3756
3757 let mut field = Field::new(&name, data_type, nullable);
3758 let field_metadata =
3759 merge_metadata_for_union(fields.iter().map(|field| field.metadata()));
3760 field.set_metadata(field_metadata);
3761 Ok((None, Arc::new(field)))
3762 })
3763 .collect::<Result<_>>()?;
3764 let union_schema_metadata = merge_metadata_for_union(
3765 inputs.iter().map(|input| input.schema().metadata()),
3766 );
3767
3768 let schema = DFSchema::new_with_metadata(union_fields, union_schema_metadata)?;
3770 let schema = Arc::new(schema);
3771
3772 Ok(schema)
3773 }
3774}
3775
3776impl PartialOrd for Union {
3778 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3779 self.inputs
3780 .partial_cmp(&other.inputs)
3781 .filter(|cmp| *cmp != Ordering::Equal || self == other)
3783 }
3784}
3785
3786#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3810pub struct Show {
3811 pub kind: ShowKind,
3813 pub output_schema: DFSchemaRef,
3815}
3816
3817#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3819pub enum ShowKind {
3820 Describe {
3822 schema: Arc<Schema>,
3824 },
3825 Tables,
3827 Columns {
3829 table_ref: TableReference,
3831 detail: ColumnsDetail,
3833 },
3834 CreateTable {
3836 table_ref: TableReference,
3838 },
3839 Variables {
3841 name: Option<String>,
3843 verbose: bool,
3845 },
3846 Functions {
3848 filter: Option<String>,
3850 },
3851}
3852
3853impl PartialOrd for Show {
3856 fn partial_cmp(&self, _other: &Self) -> Option<Ordering> {
3857 None
3859 }
3860}
3861
3862#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3864pub struct ExplainOption {
3865 pub verbose: bool,
3867 pub analyze: bool,
3869 pub format: ExplainFormat,
3871 pub show_statistics: Option<bool>,
3874 pub analyze_level: Option<MetricType>,
3877 pub analyze_categories: Option<ExplainAnalyzeCategories>,
3880}
3881
3882impl Default for ExplainOption {
3883 fn default() -> Self {
3884 ExplainOption {
3885 verbose: false,
3886 analyze: false,
3887 format: ExplainFormat::Indent,
3888 show_statistics: None,
3889 analyze_level: None,
3890 analyze_categories: None,
3891 }
3892 }
3893}
3894
3895impl ExplainOption {
3896 pub fn with_verbose(mut self, verbose: bool) -> Self {
3898 self.verbose = verbose;
3899 self
3900 }
3901
3902 pub fn with_analyze(mut self, analyze: bool) -> Self {
3904 self.analyze = analyze;
3905 self
3906 }
3907
3908 pub fn with_format(mut self, format: ExplainFormat) -> Self {
3910 self.format = format;
3911 self
3912 }
3913
3914 pub fn with_show_statistics(mut self, show_statistics: Option<bool>) -> Self {
3917 self.show_statistics = show_statistics;
3918 self
3919 }
3920
3921 pub fn with_analyze_level(mut self, analyze_level: Option<MetricType>) -> Self {
3924 self.analyze_level = analyze_level;
3925 self
3926 }
3927
3928 pub fn with_analyze_categories(
3931 mut self,
3932 analyze_categories: Option<ExplainAnalyzeCategories>,
3933 ) -> Self {
3934 self.analyze_categories = analyze_categories;
3935 self
3936 }
3937}
3938
3939#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3946pub struct Explain {
3947 pub verbose: bool,
3949 pub explain_format: ExplainFormat,
3952 pub plan: Arc<LogicalPlan>,
3954 pub stringified_plans: Vec<StringifiedPlan>,
3956 pub schema: DFSchemaRef,
3958 pub logical_optimization_succeeded: bool,
3960 pub show_statistics: Option<bool>,
3963}
3964
3965impl PartialOrd for Explain {
3967 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3968 #[derive(PartialEq, PartialOrd)]
3969 struct ComparableExplain<'a> {
3970 pub verbose: &'a bool,
3972 pub plan: &'a Arc<LogicalPlan>,
3974 pub stringified_plans: &'a Vec<StringifiedPlan>,
3976 pub logical_optimization_succeeded: &'a bool,
3978 pub show_statistics: &'a Option<bool>,
3980 }
3981 let comparable_self = ComparableExplain {
3982 verbose: &self.verbose,
3983 plan: &self.plan,
3984 stringified_plans: &self.stringified_plans,
3985 logical_optimization_succeeded: &self.logical_optimization_succeeded,
3986 show_statistics: &self.show_statistics,
3987 };
3988 let comparable_other = ComparableExplain {
3989 verbose: &other.verbose,
3990 plan: &other.plan,
3991 stringified_plans: &other.stringified_plans,
3992 logical_optimization_succeeded: &other.logical_optimization_succeeded,
3993 show_statistics: &other.show_statistics,
3994 };
3995 comparable_self
3996 .partial_cmp(&comparable_other)
3997 .filter(|cmp| *cmp != Ordering::Equal || self == other)
3999 }
4000}
4001
4002#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4005pub struct Analyze {
4006 pub verbose: bool,
4008 pub format: ExplainFormat,
4010 pub input: Arc<LogicalPlan>,
4012 pub schema: DFSchemaRef,
4014 pub analyze_level: Option<MetricType>,
4017 pub analyze_categories: Option<ExplainAnalyzeCategories>,
4020}
4021
4022impl PartialOrd for Analyze {
4027 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4028 match self.verbose.partial_cmp(&other.verbose) {
4029 Some(Ordering::Equal) => self.input.partial_cmp(&other.input),
4030 cmp => cmp,
4031 }
4032 .filter(|cmp| *cmp != Ordering::Equal || self == other)
4034 }
4035}
4036
4037#[allow(clippy::allow_attributes)]
4042#[allow(clippy::derived_hash_with_manual_eq)]
4043#[derive(Debug, Clone, Eq, Hash)]
4044pub struct Extension {
4045 pub node: Arc<dyn UserDefinedLogicalNode>,
4047}
4048
4049impl PartialEq for Extension {
4053 fn eq(&self, other: &Self) -> bool {
4054 self.node.eq(&other.node)
4055 }
4056}
4057
4058impl PartialOrd for Extension {
4059 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4060 self.node.partial_cmp(&other.node)
4061 }
4062}
4063
4064#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
4066pub struct Limit {
4067 pub skip: Option<Box<Expr>>,
4069 pub fetch: Option<Box<Expr>>,
4072 pub input: Arc<LogicalPlan>,
4074}
4075
4076pub enum SkipType {
4078 Literal(usize),
4080 UnsupportedExpr,
4082}
4083
4084pub enum FetchType {
4086 Literal(Option<usize>),
4089 UnsupportedExpr,
4091}
4092
4093impl Limit {
4094 pub fn get_skip_type(&self) -> Result<SkipType> {
4096 match self.skip.as_deref() {
4097 Some(expr) => match *expr {
4098 Expr::Literal(ScalarValue::Int64(s), _) => {
4099 let s = s.unwrap_or(0);
4101 if s >= 0 {
4102 let s = usize::try_from(s).map_err(|_| {
4103 plan_datafusion_err!(
4104 "OFFSET value {s} cannot be represented as usize"
4105 )
4106 })?;
4107 Ok(SkipType::Literal(s))
4108 } else {
4109 plan_err!("OFFSET must be >=0, '{}' was provided", s)
4110 }
4111 }
4112 _ => Ok(SkipType::UnsupportedExpr),
4113 },
4114 None => Ok(SkipType::Literal(0)),
4116 }
4117 }
4118
4119 pub fn get_fetch_type(&self) -> Result<FetchType> {
4121 match self.fetch.as_deref() {
4122 Some(expr) => match *expr {
4123 Expr::Literal(ScalarValue::Int64(Some(s)), _) => {
4124 if s >= 0 {
4125 let s = usize::try_from(s).map_err(|_| {
4126 plan_datafusion_err!(
4127 "LIMIT value {s} cannot be represented as usize"
4128 )
4129 })?;
4130 Ok(FetchType::Literal(Some(s)))
4131 } else {
4132 plan_err!("LIMIT must be >= 0, '{}' was provided", s)
4133 }
4134 }
4135 Expr::Literal(ScalarValue::Int64(None), _) => {
4136 Ok(FetchType::Literal(None))
4137 }
4138 _ => Ok(FetchType::UnsupportedExpr),
4139 },
4140 None => Ok(FetchType::Literal(None)),
4141 }
4142 }
4143}
4144
4145#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
4147pub enum Distinct {
4148 All(Arc<LogicalPlan>),
4150 On(DistinctOn),
4152}
4153
4154impl Distinct {
4155 pub fn input(&self) -> &Arc<LogicalPlan> {
4157 match self {
4158 Distinct::All(input) => input,
4159 Distinct::On(DistinctOn { input, .. }) => input,
4160 }
4161 }
4162}
4163
4164#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4166pub struct DistinctOn {
4167 pub on_expr: Vec<Expr>,
4169 pub select_expr: Vec<Expr>,
4171 pub sort_expr: Option<Vec<SortExpr>>,
4175 pub input: Arc<LogicalPlan>,
4177 pub schema: DFSchemaRef,
4179}
4180
4181impl DistinctOn {
4182 pub fn try_new(
4184 on_expr: Vec<Expr>,
4185 select_expr: Vec<Expr>,
4186 sort_expr: Option<Vec<SortExpr>>,
4187 input: Arc<LogicalPlan>,
4188 ) -> Result<Self> {
4189 if on_expr.is_empty() {
4190 return plan_err!("No `ON` expressions provided");
4191 }
4192
4193 let on_expr = normalize_cols(on_expr, input.as_ref())?;
4194 let qualified_fields = exprlist_to_fields(select_expr.as_slice(), &input)?
4195 .into_iter()
4196 .collect();
4197
4198 let dfschema = DFSchema::new_with_metadata(
4199 qualified_fields,
4200 input.schema().metadata().clone(),
4201 )?;
4202
4203 let mut distinct_on = DistinctOn {
4204 on_expr,
4205 select_expr,
4206 sort_expr: None,
4207 input,
4208 schema: Arc::new(dfschema),
4209 };
4210
4211 if let Some(sort_expr) = sort_expr {
4212 distinct_on = distinct_on.with_sort_expr(sort_expr)?;
4213 }
4214
4215 Ok(distinct_on)
4216 }
4217
4218 pub fn with_sort_expr(mut self, sort_expr: Vec<SortExpr>) -> Result<Self> {
4222 let sort_expr = normalize_sorts(sort_expr, self.input.as_ref())?;
4223
4224 let mut matched = true;
4226 for (on, sort) in self.on_expr.iter().zip(sort_expr.iter()) {
4227 if on != &sort.expr {
4228 matched = false;
4229 break;
4230 }
4231 }
4232
4233 if self.on_expr.len() > sort_expr.len() || !matched {
4234 return plan_err!(
4235 "SELECT DISTINCT ON expressions must match initial ORDER BY expressions"
4236 );
4237 }
4238
4239 self.sort_expr = Some(sort_expr);
4240 Ok(self)
4241 }
4242}
4243
4244impl PartialOrd for DistinctOn {
4246 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4247 #[derive(PartialEq, PartialOrd)]
4248 struct ComparableDistinctOn<'a> {
4249 pub on_expr: &'a Vec<Expr>,
4251 pub select_expr: &'a Vec<Expr>,
4253 pub sort_expr: &'a Option<Vec<SortExpr>>,
4257 pub input: &'a Arc<LogicalPlan>,
4259 }
4260 let comparable_self = ComparableDistinctOn {
4261 on_expr: &self.on_expr,
4262 select_expr: &self.select_expr,
4263 sort_expr: &self.sort_expr,
4264 input: &self.input,
4265 };
4266 let comparable_other = ComparableDistinctOn {
4267 on_expr: &other.on_expr,
4268 select_expr: &other.select_expr,
4269 sort_expr: &other.sort_expr,
4270 input: &other.input,
4271 };
4272 comparable_self
4273 .partial_cmp(&comparable_other)
4274 .filter(|cmp| *cmp != Ordering::Equal || self == other)
4276 }
4277}
4278
4279#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4292#[non_exhaustive]
4294pub struct Aggregate {
4295 pub input: Arc<LogicalPlan>,
4297 pub group_expr: Vec<Expr>,
4299 pub aggr_expr: Vec<Expr>,
4303 pub schema: DFSchemaRef,
4305}
4306
4307impl Aggregate {
4308 pub fn try_new(
4310 input: Arc<LogicalPlan>,
4311 group_expr: Vec<Expr>,
4312 aggr_expr: Vec<Expr>,
4313 ) -> Result<Self> {
4314 check_aggregate_and_window_nesting(group_expr.iter().chain(aggr_expr.iter()))?;
4317
4318 let group_expr = enumerate_grouping_sets(group_expr)?;
4319
4320 let is_grouping_set = matches!(group_expr.as_slice(), [Expr::GroupingSet(_)]);
4321
4322 let grouping_expr: Vec<&Expr> = grouping_set_to_exprlist(group_expr.as_slice())?;
4323
4324 let mut qualified_fields = exprlist_to_fields(grouping_expr, &input)?;
4325
4326 if is_grouping_set {
4328 qualified_fields = qualified_fields
4329 .into_iter()
4330 .map(|(q, f)| (q, f.as_ref().clone().with_nullable(true).into()))
4331 .collect::<Vec<_>>();
4332 let max_ordinal = max_grouping_set_duplicate_ordinal(&group_expr);
4333 qualified_fields.push((
4334 None,
4335 Field::new(
4336 Self::INTERNAL_GROUPING_ID,
4337 Self::grouping_id_type(qualified_fields.len(), max_ordinal),
4338 false,
4339 )
4340 .into(),
4341 ));
4342 }
4343
4344 qualified_fields.extend(exprlist_to_fields(aggr_expr.as_slice(), &input)?);
4345
4346 let schema = DFSchema::new_with_metadata(
4347 qualified_fields,
4348 input.schema().metadata().clone(),
4349 )?;
4350
4351 Self::try_new_with_schema(input, group_expr, aggr_expr, Arc::new(schema))
4352 }
4353
4354 pub fn try_new_with_schema(
4360 input: Arc<LogicalPlan>,
4361 group_expr: Vec<Expr>,
4362 aggr_expr: Vec<Expr>,
4363 schema: DFSchemaRef,
4364 ) -> Result<Self> {
4365 if group_expr.is_empty() && aggr_expr.is_empty() {
4366 return plan_err!(
4367 "Aggregate requires at least one grouping or aggregate expression. \
4368 Aggregate without grouping expressions nor aggregate expressions is \
4369 logically equivalent to, but less efficient than, VALUES producing \
4370 single row. Please use VALUES instead."
4371 );
4372 }
4373 let group_expr_count = grouping_set_expr_count(&group_expr)?;
4374 if schema.fields().len() != group_expr_count + aggr_expr.len() {
4375 return plan_err!(
4376 "Aggregate schema has wrong number of fields. Expected {} got {}",
4377 group_expr_count + aggr_expr.len(),
4378 schema.fields().len()
4379 );
4380 }
4381
4382 let aggregate_func_dependencies =
4383 calc_func_dependencies_for_aggregate(&group_expr, &input, &schema)?;
4384 let new_schema = Arc::unwrap_or_clone(schema);
4385 let schema = Arc::new(
4386 new_schema.with_functional_dependencies(aggregate_func_dependencies)?,
4387 );
4388 Ok(Self {
4389 input,
4390 group_expr,
4391 aggr_expr,
4392 schema,
4393 })
4394 }
4395
4396 fn is_grouping_set(&self) -> bool {
4397 matches!(self.group_expr.as_slice(), [Expr::GroupingSet(_)])
4398 }
4399
4400 fn output_expressions(&self) -> Result<Vec<&Expr>> {
4402 static INTERNAL_ID_EXPR: LazyLock<Expr> = LazyLock::new(|| {
4403 Expr::Column(Column::from_name(Aggregate::INTERNAL_GROUPING_ID))
4404 });
4405 let mut exprs = grouping_set_to_exprlist(self.group_expr.as_slice())?;
4406 if self.is_grouping_set() {
4407 exprs.push(&INTERNAL_ID_EXPR);
4408 }
4409 exprs.extend(self.aggr_expr.iter());
4410 debug_assert_eq!(exprs.len(), self.schema.fields().len());
4411 Ok(exprs)
4412 }
4413
4414 pub fn group_expr_len(&self) -> Result<usize> {
4418 grouping_set_expr_count(&self.group_expr)
4419 }
4420
4421 pub fn grouping_id_type(group_exprs: usize, max_ordinal: usize) -> DataType {
4433 let ordinal_bits = usize::BITS as usize - max_ordinal.leading_zeros() as usize;
4434 let total_bits = group_exprs + ordinal_bits;
4435 if total_bits <= 8 {
4436 DataType::UInt8
4437 } else if total_bits <= 16 {
4438 DataType::UInt16
4439 } else if total_bits <= 32 {
4440 DataType::UInt32
4441 } else {
4442 DataType::UInt64
4443 }
4444 }
4445
4446 pub const INTERNAL_GROUPING_ID: &'static str = "__grouping_id";
4479}
4480
4481impl PartialOrd for Aggregate {
4483 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4484 match self.input.partial_cmp(&other.input) {
4485 Some(Ordering::Equal) => {
4486 match self.group_expr.partial_cmp(&other.group_expr) {
4487 Some(Ordering::Equal) => self.aggr_expr.partial_cmp(&other.aggr_expr),
4488 cmp => cmp,
4489 }
4490 }
4491 cmp => cmp,
4492 }
4493 .filter(|cmp| *cmp != Ordering::Equal || self == other)
4495 }
4496}
4497
4498#[allow(clippy::allow_attributes, clippy::mutable_key_type)] fn max_grouping_set_duplicate_ordinal(group_expr: &[Expr]) -> usize {
4506 if let Some(Expr::GroupingSet(GroupingSet::GroupingSets(sets))) = group_expr.first() {
4507 let mut counts: HashMap<&[Expr], usize> = HashMap::with_capacity(sets.len());
4508 for set in sets {
4509 *counts.entry(set).or_insert(0) += 1;
4510 }
4511 counts.into_values().max().unwrap_or(0).saturating_sub(1)
4512 } else {
4513 0
4514 }
4515}
4516
4517fn contains_grouping_set(group_expr: &[Expr]) -> bool {
4519 group_expr
4520 .iter()
4521 .any(|expr| matches!(expr, Expr::GroupingSet(_)))
4522}
4523
4524fn calc_func_dependencies_for_aggregate(
4526 group_expr: &[Expr],
4528 input: &LogicalPlan,
4530 aggr_schema: &DFSchema,
4532) -> Result<FunctionalDependencies> {
4533 if !contains_grouping_set(group_expr) {
4539 let group_by_input_indices = grouping_set_to_exprlist(group_expr)?
4541 .into_iter()
4542 .map(|item| passthrough_field_index(item, input.schema()))
4543 .collect::<Vec<_>>();
4544 let aggregate_func_dependencies = aggregate_functional_dependencies(
4545 input.schema(),
4546 &group_by_input_indices,
4547 aggr_schema,
4548 );
4549 Ok(aggregate_func_dependencies)
4550 } else {
4551 Ok(FunctionalDependencies::empty())
4552 }
4553}
4554
4555fn calc_func_dependencies_for_project(
4558 exprs: &[Expr],
4559 input: &LogicalPlan,
4560) -> Result<FunctionalDependencies> {
4561 const COMPUTED_EXPR_INDEX: usize = usize::MAX;
4563
4564 let input_func_dependencies = input.schema().functional_dependencies();
4565 if input_func_dependencies.is_empty() {
4569 return Ok(FunctionalDependencies::empty());
4570 }
4571
4572 let input_schema = input.schema();
4573 let input_index = |expr: &Expr| {
4574 passthrough_field_index(expr, input_schema).unwrap_or(COMPUTED_EXPR_INDEX)
4575 };
4576
4577 let proj_indices = exprs
4580 .iter()
4581 .map(|expr| match expr {
4582 #[expect(deprecated)]
4583 Expr::Wildcard { qualifier, options } => {
4584 let wildcard_fields = exprlist_to_fields(
4585 vec![&Expr::Wildcard {
4586 qualifier: qualifier.clone(),
4587 options: options.clone(),
4588 }],
4589 input,
4590 )?;
4591 Ok::<_, DataFusionError>(
4592 wildcard_fields
4593 .into_iter()
4594 .map(|(qualifier, f)| {
4595 input_schema
4596 .index_of_column_by_name(qualifier.as_ref(), f.name())
4597 .unwrap_or(COMPUTED_EXPR_INDEX)
4598 })
4599 .collect::<Vec<_>>(),
4600 )
4601 }
4602 _ => Ok(vec![input_index(expr)]),
4603 })
4604 .collect::<Result<Vec<_>>>()?
4605 .into_iter()
4606 .flatten()
4607 .collect::<Vec<_>>();
4608
4609 Ok(input_func_dependencies
4610 .project_functional_dependencies(&proj_indices, exprs.len()))
4611}
4612
4613#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
4615pub struct Sort {
4616 pub expr: Vec<SortExpr>,
4618 pub input: Arc<LogicalPlan>,
4620 pub fetch: Option<usize>,
4622}
4623
4624#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4626pub struct Join {
4627 pub left: Arc<LogicalPlan>,
4629 pub right: Arc<LogicalPlan>,
4631 pub on: Vec<(Expr, Expr)>,
4633 pub filter: Option<Expr>,
4635 pub join_type: JoinType,
4637 pub join_constraint: JoinConstraint,
4639 pub schema: DFSchemaRef,
4641 pub null_equality: NullEquality,
4643 pub null_aware: bool,
4651 pub null_aware_value_keys: usize,
4667}
4668
4669#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
4671pub struct AsOfMatch {
4672 pub left: Expr,
4674 pub op: Operator,
4677 pub right: Expr,
4679}
4680
4681impl AsOfMatch {
4682 pub fn new(left: Expr, op: Operator, right: Expr) -> Self {
4684 Self { left, op, right }
4685 }
4686}
4687
4688impl TryFrom<Expr> for AsOfMatch {
4689 type Error = DataFusionError;
4690
4691 fn try_from(condition: Expr) -> Result<Self> {
4692 let Expr::BinaryExpr(BinaryExpr { left, op, right }) = condition else {
4693 return plan_err!("ASOF MATCH_CONDITION must be a single comparison");
4694 };
4695 if !matches!(
4696 op,
4697 Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq
4698 ) {
4699 return plan_err!(
4700 "ASOF MATCH_CONDITION requires <, <=, >, or >=, found {op}"
4701 );
4702 }
4703 Ok(Self::new(*left, op, *right))
4704 }
4705}
4706
4707impl Display for AsOfMatch {
4708 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
4709 write!(f, "{} {} {}", self.left, self.op, self.right)
4710 }
4711}
4712
4713#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4715pub struct AsOfJoin {
4716 pub left: Arc<LogicalPlan>,
4718 pub right: Arc<LogicalPlan>,
4720 pub on: Vec<(Expr, Expr)>,
4722 pub match_condition: Box<AsOfMatch>,
4724 pub join_constraint: JoinConstraint,
4726 pub schema: DFSchemaRef,
4728}
4729
4730impl AsOfJoin {
4731 pub fn try_new(
4738 left: Arc<LogicalPlan>,
4739 right: Arc<LogicalPlan>,
4740 on: Vec<(Expr, Expr)>,
4741 match_condition: AsOfMatch,
4742 join_constraint: JoinConstraint,
4743 ) -> Result<Self> {
4744 if !matches!(
4745 match_condition.op,
4746 Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq
4747 ) {
4748 return plan_err!(
4749 "ASOF MATCH_CONDITION requires <, <=, >, or >=, found {}",
4750 match_condition.op
4751 );
4752 }
4753
4754 Self::validate_side(&match_condition.left, left.schema(), "left match")?;
4755 Self::validate_side(&match_condition.right, right.schema(), "right match")?;
4756 if match_condition.left.is_volatile() || match_condition.right.is_volatile() {
4757 return plan_err!("ASOF MATCH_CONDITION must be deterministic");
4758 }
4759
4760 let left_type = match_condition.left.get_type(left.schema())?;
4761 let right_type = match_condition.right.get_type(right.schema())?;
4762 if crate::type_coercion::binary::comparison_coercion(&left_type, &right_type)
4763 .is_none()
4764 {
4765 return plan_err!(
4766 "ASOF match expressions have incompatible types {left_type} and {right_type}"
4767 );
4768 }
4769
4770 for (left_expr, right_expr) in &on {
4771 Self::validate_side(left_expr, left.schema(), "left equality")?;
4772 Self::validate_side(right_expr, right.schema(), "right equality")?;
4773 if left_expr.is_volatile() || right_expr.is_volatile() {
4774 return plan_err!("ASOF equality expressions must be deterministic");
4775 }
4776 let left_type = left_expr.get_type(left.schema())?;
4777 let right_type = right_expr.get_type(right.schema())?;
4778 let Some(common_type) = crate::type_coercion::binary::comparison_coercion(
4779 &left_type,
4780 &right_type,
4781 ) else {
4782 return plan_err!(
4783 "ASOF equality expressions have incompatible types {left_type} and {right_type}"
4784 );
4785 };
4786 if !crate::utils::can_hash(&common_type) {
4787 return plan_err!(
4788 "ASOF equality expressions have unsupported hash type {common_type}"
4789 );
4790 }
4791 }
4792
4793 if join_constraint == JoinConstraint::Using
4794 && on.iter().any(|(left, right)| {
4795 left.get_as_join_column().is_none()
4796 || right.get_as_join_column().is_none()
4797 })
4798 {
4799 return plan_err!("ASOF USING keys must be columns");
4800 }
4801
4802 let schema = build_asof_join_schema(left.schema(), right.schema())?;
4803 Ok(Self {
4804 left,
4805 right,
4806 on,
4807 match_condition: Box::new(match_condition),
4808 join_constraint,
4809 schema: Arc::new(schema),
4810 })
4811 }
4812
4813 fn validate_side(expr: &Expr, schema: &DFSchema, name: &str) -> Result<()> {
4814 let mut columns = HashSet::new();
4815 expr_to_columns(expr, &mut columns)?;
4816 if columns.is_empty() {
4817 return plan_err!("ASOF {name} expression must reference its input");
4818 }
4819 if let Some(column) = columns
4820 .iter()
4821 .find(|column| !schema.is_column_from_schema(column))
4822 {
4823 return plan_err!(
4824 "ASOF {name} expression references column {column} outside its input"
4825 );
4826 }
4827 Ok(())
4828 }
4829}
4830
4831impl PartialOrd for AsOfJoin {
4832 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4833 (
4834 &self.left,
4835 &self.right,
4836 &self.on,
4837 &self.match_condition,
4838 &self.join_constraint,
4839 )
4840 .partial_cmp(&(
4841 &other.left,
4842 &other.right,
4843 &other.on,
4844 &other.match_condition,
4845 &other.join_constraint,
4846 ))
4847 .filter(|cmp| *cmp != Ordering::Equal || self == other)
4848 }
4849}
4850
4851impl Join {
4852 #[expect(clippy::too_many_arguments)]
4872 pub fn try_new(
4873 left: Arc<LogicalPlan>,
4874 right: Arc<LogicalPlan>,
4875 on: Vec<(Expr, Expr)>,
4876 filter: Option<Expr>,
4877 join_type: JoinType,
4878 join_constraint: JoinConstraint,
4879 null_equality: NullEquality,
4880 null_aware: bool,
4881 ) -> Result<Self> {
4882 let join_schema = build_join_schema(left.schema(), right.schema(), &join_type)?;
4883
4884 Ok(Join {
4885 left,
4886 right,
4887 on,
4888 filter,
4889 join_type,
4890 join_constraint,
4891 schema: Arc::new(join_schema),
4892 null_equality,
4893 null_aware,
4894 null_aware_value_keys: 0,
4895 })
4896 }
4897
4898 pub fn with_null_aware_value_keys(mut self, null_aware_value_keys: usize) -> Self {
4901 self.null_aware_value_keys = null_aware_value_keys;
4902 self
4903 }
4904
4905 pub fn try_new_with_project_input(
4908 original: &LogicalPlan,
4909 left: Arc<LogicalPlan>,
4910 right: Arc<LogicalPlan>,
4911 column_on: (Vec<Column>, Vec<Column>),
4912 ) -> Result<(Self, bool)> {
4913 let LogicalPlan::Join(original_join) = original else {
4914 return plan_err!("Could not create join with project input");
4915 };
4916
4917 let mut left_sch = LogicalPlanBuilder::from(Arc::clone(&left));
4918 let mut right_sch = LogicalPlanBuilder::from(Arc::clone(&right));
4919
4920 let mut requalified = false;
4921
4922 if original_join.join_type == JoinType::Inner
4925 || original_join.join_type == JoinType::Left
4926 || original_join.join_type == JoinType::Right
4927 || original_join.join_type == JoinType::Full
4928 {
4929 (left_sch, right_sch, requalified) =
4930 requalify_sides_if_needed(left_sch.clone(), right_sch.clone())?;
4931 }
4932
4933 let on: Vec<(Expr, Expr)> = column_on
4934 .0
4935 .into_iter()
4936 .zip(column_on.1)
4937 .map(|(l, r)| (Expr::Column(l), Expr::Column(r)))
4938 .collect();
4939
4940 let join_schema = build_join_schema(
4941 left_sch.schema(),
4942 right_sch.schema(),
4943 &original_join.join_type,
4944 )?;
4945
4946 Ok((
4947 Join {
4948 left,
4949 right,
4950 on,
4951 filter: original_join.filter.clone(),
4952 join_type: original_join.join_type,
4953 join_constraint: original_join.join_constraint,
4954 schema: Arc::new(join_schema),
4955 null_equality: original_join.null_equality,
4956 null_aware: original_join.null_aware,
4957 null_aware_value_keys: original_join.null_aware_value_keys,
4958 },
4959 requalified,
4960 ))
4961 }
4962}
4963
4964impl PartialOrd for Join {
4966 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4967 #[derive(PartialEq, PartialOrd)]
4968 struct ComparableJoin<'a> {
4969 pub left: &'a Arc<LogicalPlan>,
4971 pub right: &'a Arc<LogicalPlan>,
4973 pub on: &'a Vec<(Expr, Expr)>,
4975 pub filter: &'a Option<Expr>,
4977 pub join_type: &'a JoinType,
4979 pub join_constraint: &'a JoinConstraint,
4981 pub null_equality: &'a NullEquality,
4983 }
4984 let comparable_self = ComparableJoin {
4985 left: &self.left,
4986 right: &self.right,
4987 on: &self.on,
4988 filter: &self.filter,
4989 join_type: &self.join_type,
4990 join_constraint: &self.join_constraint,
4991 null_equality: &self.null_equality,
4992 };
4993 let comparable_other = ComparableJoin {
4994 left: &other.left,
4995 right: &other.right,
4996 on: &other.on,
4997 filter: &other.filter,
4998 join_type: &other.join_type,
4999 join_constraint: &other.join_constraint,
5000 null_equality: &other.null_equality,
5001 };
5002 comparable_self
5003 .partial_cmp(&comparable_other)
5004 .filter(|cmp| *cmp != Ordering::Equal || self == other)
5006 }
5007}
5008
5009#[derive(Clone, PartialEq, Eq, PartialOrd, Hash)]
5011pub struct Subquery {
5012 pub subquery: Arc<LogicalPlan>,
5014 pub outer_ref_columns: Vec<Expr>,
5016 pub spans: Spans,
5018}
5019
5020impl Normalizeable for Subquery {
5021 fn can_normalize(&self) -> bool {
5022 false
5023 }
5024}
5025
5026impl NormalizeEq for Subquery {
5027 fn normalize_eq(&self, other: &Self) -> bool {
5028 *self.subquery == *other.subquery
5030 && self.outer_ref_columns.len() == other.outer_ref_columns.len()
5031 && self
5032 .outer_ref_columns
5033 .iter()
5034 .zip(other.outer_ref_columns.iter())
5035 .all(|(a, b)| a.normalize_eq(b))
5036 }
5037}
5038
5039impl Subquery {
5040 pub fn try_from_expr(plan: &Expr) -> Result<&Subquery> {
5041 match plan {
5042 Expr::ScalarSubquery(it) => Ok(it),
5043 Expr::Cast(cast) => Subquery::try_from_expr(cast.expr.as_ref()),
5044 _ => plan_err!("Could not coerce into ScalarSubquery!"),
5045 }
5046 }
5047
5048 pub fn with_plan(&self, plan: Arc<LogicalPlan>) -> Subquery {
5049 Subquery {
5050 subquery: plan,
5051 outer_ref_columns: self.outer_ref_columns.clone(),
5052 spans: Spans::new(),
5053 }
5054 }
5055}
5056
5057impl Debug for Subquery {
5058 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
5059 write!(f, "<subquery>")
5060 }
5061}
5062
5063#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
5074pub enum Partitioning {
5075 RoundRobinBatch(usize),
5077 Hash(Vec<Expr>, usize),
5080 Range(RangePartitioning),
5083 DistributeBy(Vec<Expr>),
5085}
5086
5087impl Partitioning {
5088 pub fn partition_count(&self) -> Option<usize> {
5090 match self {
5091 Self::RoundRobinBatch(partition_count) | Self::Hash(_, partition_count) => {
5092 Some(*partition_count)
5093 }
5094 Self::Range(range) => Some(range.partition_count()),
5095 Self::DistributeBy(_) => None,
5096 }
5097 }
5098}
5099
5100#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
5124pub struct RangePartitioning {
5125 ordering: Vec<SortExpr>,
5127 split_points: Vec<SplitPoint>,
5129}
5130
5131impl RangePartitioning {
5132 pub fn try_new(
5135 ordering: Vec<SortExpr>,
5136 split_points: Vec<SplitPoint>,
5137 ) -> Result<Self> {
5138 if ordering.is_empty() {
5139 return plan_err!("Range partitioning requires non-empty ordering");
5140 }
5141
5142 validate_range_split_points(&split_points, &logical_sort_options(&ordering))?;
5143
5144 Ok(Self {
5145 ordering,
5146 split_points,
5147 })
5148 }
5149
5150 pub fn partition_count(&self) -> usize {
5152 self.split_points.len() + 1
5153 }
5154
5155 pub fn ordering(&self) -> &[SortExpr] {
5157 &self.ordering
5158 }
5159
5160 pub fn split_points(&self) -> &[SplitPoint] {
5162 &self.split_points
5163 }
5164}
5165
5166fn logical_sort_options(ordering: &[SortExpr]) -> Vec<SortOptions> {
5167 ordering
5168 .iter()
5169 .map(|sort_expr| SortOptions {
5170 descending: !sort_expr.asc,
5171 nulls_first: sort_expr.nulls_first,
5172 })
5173 .collect()
5174}
5175
5176impl Display for RangePartitioning {
5177 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
5178 let ordering = self.ordering().iter().map(ToString::to_string).join(", ");
5179 let split_points = self
5180 .split_points()
5181 .iter()
5182 .map(ToString::to_string)
5183 .join(", ");
5184 write!(
5185 f,
5186 "Range([{ordering}], [{split_points}], {})",
5187 self.partition_count()
5188 )
5189 }
5190}
5191
5192#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd)]
5212pub struct ColumnUnnestList {
5213 pub output_column: Column,
5214 pub depth: usize,
5215}
5216
5217impl Display for ColumnUnnestList {
5218 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
5219 write!(f, "{}|depth={}", self.output_column, self.depth)
5220 }
5221}
5222
5223#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5226pub struct Unnest {
5227 pub input: Arc<LogicalPlan>,
5229 pub exec_columns: Vec<Column>,
5231 pub list_type_columns: Vec<(usize, ColumnUnnestList)>,
5234 pub struct_type_columns: Vec<usize>,
5237 pub dependency_indices: Vec<usize>,
5240 pub schema: DFSchemaRef,
5242 pub options: UnnestOptions,
5244}
5245
5246impl PartialOrd for Unnest {
5248 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
5249 #[derive(PartialEq, PartialOrd)]
5250 struct ComparableUnnest<'a> {
5251 pub input: &'a Arc<LogicalPlan>,
5253 pub exec_columns: &'a Vec<Column>,
5255 pub list_type_columns: &'a Vec<(usize, ColumnUnnestList)>,
5258 pub struct_type_columns: &'a Vec<usize>,
5261 pub dependency_indices: &'a Vec<usize>,
5264 pub options: &'a UnnestOptions,
5266 }
5267 let comparable_self = ComparableUnnest {
5268 input: &self.input,
5269 exec_columns: &self.exec_columns,
5270 list_type_columns: &self.list_type_columns,
5271 struct_type_columns: &self.struct_type_columns,
5272 dependency_indices: &self.dependency_indices,
5273 options: &self.options,
5274 };
5275 let comparable_other = ComparableUnnest {
5276 input: &other.input,
5277 exec_columns: &other.exec_columns,
5278 list_type_columns: &other.list_type_columns,
5279 struct_type_columns: &other.struct_type_columns,
5280 dependency_indices: &other.dependency_indices,
5281 options: &other.options,
5282 };
5283 comparable_self
5284 .partial_cmp(&comparable_other)
5285 .filter(|cmp| *cmp != Ordering::Equal || self == other)
5287 }
5288}
5289
5290impl Unnest {
5291 pub fn try_new(
5292 input: Arc<LogicalPlan>,
5293 exec_columns: Vec<Column>,
5294 options: UnnestOptions,
5295 ) -> Result<Self> {
5296 if exec_columns.is_empty() {
5297 return plan_err!("unnest plan requires at least 1 column to unnest");
5298 }
5299
5300 let mut list_columns: Vec<(usize, ColumnUnnestList)> = vec![];
5301 let mut struct_columns = vec![];
5302 let indices_to_unnest = exec_columns
5303 .iter()
5304 .map(|c| Ok((input.schema().index_of_column(c)?, c)))
5305 .collect::<Result<HashMap<usize, &Column>>>()?;
5306
5307 let input_schema = input.schema();
5308
5309 let mut dependency_indices = Vec::with_capacity(input_schema.fields().len());
5310 let fields = input_schema
5326 .iter()
5327 .enumerate()
5328 .map(|(index, (original_qualifier, original_field))| {
5329 match indices_to_unnest.get(&index) {
5330 Some(column_to_unnest) => {
5331 let recursions_on_column = options
5332 .recursions
5333 .iter()
5334 .filter(|p| -> bool { &p.input_column == *column_to_unnest })
5335 .collect::<Vec<_>>();
5336 let mut transformed_columns = recursions_on_column
5337 .iter()
5338 .map(|r| {
5339 list_columns.push((
5340 index,
5341 ColumnUnnestList {
5342 output_column: r.output_column.clone(),
5343 depth: r.depth,
5344 },
5345 ));
5346 Ok(get_unnested_columns(
5347 &r.output_column.name,
5348 original_field,
5349 r.depth,
5350 )?
5351 .into_iter()
5352 .next()
5353 .unwrap()) })
5355 .collect::<Result<Vec<(Column, Arc<Field>)>>>()?;
5356 if transformed_columns.is_empty() {
5357 transformed_columns = get_unnested_columns(
5358 &column_to_unnest.name,
5359 original_field,
5360 1,
5361 )?;
5362 match original_field.data_type() {
5363 DataType::Struct(_) => {
5364 struct_columns.push(index);
5365 }
5366 DataType::List(_)
5367 | DataType::FixedSizeList(_, _)
5368 | DataType::LargeList(_)
5369 | DataType::ListView(_)
5370 | DataType::LargeListView(_) => {
5371 list_columns.push((
5372 index,
5373 ColumnUnnestList {
5374 output_column: Column::from_name(
5375 &column_to_unnest.name,
5376 ),
5377 depth: 1,
5378 },
5379 ));
5380 }
5381 _ => {}
5382 }
5383 }
5384
5385 dependency_indices.extend(std::iter::repeat_n(
5387 index,
5388 transformed_columns.len(),
5389 ));
5390 Ok(transformed_columns
5391 .iter()
5392 .map(|(col, field)| {
5393 (col.relation.to_owned(), field.to_owned())
5394 })
5395 .collect())
5396 }
5397 None => {
5398 dependency_indices.push(index);
5399 Ok(vec![(
5400 original_qualifier.cloned(),
5401 Arc::clone(original_field),
5402 )])
5403 }
5404 }
5405 })
5406 .collect::<Result<Vec<_>>>()?
5407 .into_iter()
5408 .flatten()
5409 .collect::<Vec<_>>();
5410
5411 let metadata = input_schema.metadata().clone();
5412 let df_schema = DFSchema::new_with_metadata(fields, metadata)?;
5413 let list_indices: HashSet<_> =
5414 list_columns.iter().map(|(index, _)| *index).collect();
5415 let remap_indices = |indices: &[usize], exclude_lists: bool| {
5418 dependency_indices
5419 .iter()
5420 .enumerate()
5421 .filter_map(|(output_index, input_index)| {
5422 (indices.contains(input_index)
5423 && (!exclude_lists || !list_indices.contains(input_index)))
5424 .then_some(output_index)
5425 })
5426 .collect()
5427 };
5428 let deps = FunctionalDependencies::new(
5429 input_schema
5430 .functional_dependencies()
5431 .iter()
5432 .filter(|dep| {
5436 dep.source_indices.iter().all(|index| {
5437 !list_indices.contains(index) && !struct_columns.contains(index)
5438 })
5439 })
5440 .map(|dep| FunctionalDependence {
5441 source_indices: remap_indices(&dep.source_indices, false),
5442 target_indices: remap_indices(&dep.target_indices, true),
5444 mode: if list_indices.is_empty() {
5446 dep.mode
5447 } else {
5448 Dependency::Multi
5449 },
5450 ..dep.clone()
5451 })
5452 .collect(),
5453 );
5454 let schema = Arc::new(df_schema.with_functional_dependencies(deps)?);
5455
5456 Ok(Unnest {
5457 input,
5458 exec_columns,
5459 list_type_columns: list_columns,
5460 struct_type_columns: struct_columns,
5461 dependency_indices,
5462 schema,
5463 options,
5464 })
5465 }
5466}
5467
5468fn get_unnested_columns(
5477 col_name: &String,
5478 field: &Field,
5479 depth: usize,
5480) -> Result<Vec<(Column, Arc<Field>)>> {
5481 let data_type = field.data_type();
5482 let mut qualified_columns = Vec::with_capacity(1);
5483
5484 match data_type {
5485 DataType::List(_)
5486 | DataType::FixedSizeList(_, _)
5487 | DataType::LargeList(_)
5488 | DataType::ListView(_)
5489 | DataType::LargeListView(_) => {
5490 let field = get_unnested_list_field(data_type, depth)?;
5491 let new_field = Arc::new(
5492 field
5493 .clone()
5494 .with_name(col_name)
5495 .with_nullable(true),
5498 );
5499 let column = Column::from_name(col_name);
5500 qualified_columns.push((column, new_field));
5502 }
5503 DataType::Struct(fields) => {
5504 qualified_columns.extend(fields.iter().map(|f| {
5505 let new_name = format!("{}.{}", col_name, f.name());
5506 let column = Column::from_name(&new_name);
5507 let new_field = f
5508 .as_ref()
5509 .clone()
5510 .with_name(new_name)
5511 .with_nullable(field.is_nullable() || f.is_nullable());
5512 (column, Arc::new(new_field))
5514 }))
5515 }
5516 _ => {
5517 return internal_err!("trying to unnest on invalid data type {data_type}");
5518 }
5519 }
5520 Ok(qualified_columns)
5521}
5522
5523#[cfg(test)]
5524mod tests {
5525 use super::*;
5526 use crate::builder::LogicalTableSource;
5527 use crate::logical_plan::table_scan;
5528 use crate::select_expr::SelectExpr;
5529 use crate::test::function_stub::{count, count_udaf};
5530 use crate::{
5531 GroupingSet, binary_expr, col, exists, in_subquery, lit, placeholder,
5532 scalar_subquery,
5533 };
5534 use arrow::datatypes::Metadata;
5535 use datafusion_common::metadata::ScalarAndMetadata;
5536 use datafusion_common::tree_node::{
5537 TransformedResult, TreeNodeRewriter, TreeNodeVisitor,
5538 };
5539 use datafusion_common::{Constraint, RecursionUnnestOption, not_impl_err};
5540 use insta::{assert_debug_snapshot, assert_snapshot};
5541 use std::hash::DefaultHasher;
5542
5543 #[test]
5553 fn test_size_of_logical_plan() {
5554 assert_eq!(size_of::<LogicalPlan>(), 176);
5559 assert!(
5562 size_of::<DdlStatement>() < size_of::<Join>(),
5563 "DdlStatement ({} bytes) should stay smaller than Join ({} bytes); \
5564 box the new large variant rather than letting it dominate `LogicalPlan`.",
5565 size_of::<DdlStatement>(),
5566 size_of::<Join>(),
5567 );
5568 assert_eq!(
5571 size_of::<Box<crate::CreateExternalTable>>(),
5572 8,
5573 "CreateExternalTable should be Box'd inside DdlStatement"
5574 );
5575 assert_eq!(
5576 size_of::<Box<crate::CreateFunction>>(),
5577 8,
5578 "CreateFunction should be Box'd inside DdlStatement"
5579 );
5580 }
5581
5582 #[test]
5583 fn limit_literals_use_checked_usize_conversion() -> Result<()> {
5584 let value = i64::from(u32::MAX) + 1;
5585 let input = Arc::new(LogicalPlanBuilder::empty(false).build()?);
5586 let limit = Limit {
5587 skip: Some(Box::new(lit(value))),
5588 fetch: Some(Box::new(lit(value))),
5589 input,
5590 };
5591
5592 if usize::BITS < 64 {
5593 assert!(limit.get_skip_type().is_err());
5594 assert!(limit.get_fetch_type().is_err());
5595 } else {
5596 let expected = usize::try_from(value).unwrap();
5597 let SkipType::Literal(skip) = limit.get_skip_type()? else {
5598 panic!("expected literal skip")
5599 };
5600 let FetchType::Literal(Some(fetch)) = limit.get_fetch_type()? else {
5601 panic!("expected literal fetch")
5602 };
5603 assert_eq!(skip, expected);
5604 assert_eq!(fetch, expected);
5605 }
5606 Ok(())
5607 }
5608
5609 fn employee_schema() -> Schema {
5610 Schema::new(vec![
5611 Field::new("id", DataType::Int32, false),
5612 Field::new("first_name", DataType::Utf8, false),
5613 Field::new("last_name", DataType::Utf8, false),
5614 Field::new("state", DataType::Utf8, false),
5615 Field::new("salary", DataType::Int32, false),
5616 ])
5617 }
5618
5619 #[test]
5620 fn unnest_remaps_functional_dependencies() -> Result<()> {
5621 let schema = Arc::new(Schema::new(vec![
5622 Field::new_struct(
5623 "s",
5624 vec![
5625 Field::new("a", DataType::Int32, true),
5626 Field::new("b", DataType::Int32, true),
5627 ],
5628 true,
5629 ),
5630 Field::new("k", DataType::Int32, false),
5631 Field::new_list(
5632 "xs",
5633 Field::new_list(
5634 "item",
5635 Field::new_list_field(DataType::Int32, true),
5636 true,
5637 ),
5638 true,
5639 ),
5640 Field::new("payload", DataType::Utf8, true),
5641 ]));
5642 let constraints = Constraints::new_unverified(vec![
5643 Constraint::PrimaryKey(vec![1]),
5644 Constraint::Unique(vec![0]),
5645 Constraint::Unique(vec![2]),
5646 ]);
5647 let source: Arc<dyn TableSource> =
5648 Arc::new(LogicalTableSource::new(schema).with_constraints(constraints));
5649
5650 let struct_only = LogicalPlanBuilder::scan("t", Arc::clone(&source), None)?
5653 .unnest_column("s")?
5654 .build()?;
5655 assert_eq!(
5656 struct_only.schema().functional_dependencies(),
5657 &FunctionalDependencies::new(vec![
5658 FunctionalDependence::new(vec![2], vec![0, 1, 2, 3, 4], false)
5659 .with_mode(Dependency::Single),
5660 FunctionalDependence::new(vec![3], vec![0, 1, 2, 3, 4], true)
5661 .with_mode(Dependency::Single),
5662 ])
5663 );
5664
5665 let options = UnnestOptions::default()
5668 .with_recursions(RecursionUnnestOption {
5669 input_column: "xs".into(),
5670 output_column: "xs_depth_1".into(),
5671 depth: 1,
5672 })
5673 .with_recursions(RecursionUnnestOption {
5674 input_column: "xs".into(),
5675 output_column: "xs_depth_2".into(),
5676 depth: 2,
5677 });
5678 let plan = LogicalPlanBuilder::scan("t", source, None)?
5679 .unnest_columns_with_options(vec!["s".into(), "xs".into()], options)?
5680 .build()?;
5681 assert_eq!(plan.schema().fields().len(), 6);
5682 assert_eq!(
5683 plan.schema().functional_dependencies(),
5684 &FunctionalDependencies::new(vec![
5685 FunctionalDependence::new(vec![2], vec![0, 1, 2, 5], false,)
5686 .with_mode(Dependency::Multi)
5687 ])
5688 );
5689
5690 Ok(())
5691 }
5692
5693 #[test]
5694 fn projection_with_leading_computed_column_preserves_pk() -> Result<()> {
5695 let constraints =
5696 Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5697 let source = Arc::new(
5698 LogicalTableSource::new(Arc::new(employee_schema()))
5699 .with_constraints(constraints),
5700 );
5701 let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5702 .project(vec![
5703 lit(1i32).alias("__common_expr_1"),
5704 col("id"),
5705 col("first_name"),
5706 col("salary"),
5707 ])?
5708 .build()?;
5709
5710 let deps = plan.schema().functional_dependencies();
5711 assert_eq!(deps.len(), 1);
5712 assert_eq!(deps[0].source_indices, vec![1]);
5713
5714 Ok(())
5715 }
5716
5717 #[test]
5718 fn projection_with_leading_computed_column_and_wildcard_preserves_pk() -> Result<()> {
5719 let constraints =
5720 Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5721 let source = Arc::new(
5722 LogicalTableSource::new(Arc::new(employee_schema()))
5723 .with_constraints(constraints),
5724 );
5725 let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5726 .project(vec![
5727 SelectExpr::Expression(lit(1i32).alias("__common_expr_1")),
5728 SelectExpr::Wildcard(Default::default()),
5729 ])?
5730 .build()?;
5731
5732 let deps = plan.schema().functional_dependencies();
5733 assert_eq!(plan.schema().fields().len(), 6);
5734 assert_eq!(deps.len(), 1);
5735 assert_eq!(deps[0].source_indices, vec![1]);
5736 assert_eq!(deps[0].target_indices, vec![0, 1, 2, 3, 4, 5]);
5737
5738 Ok(())
5739 }
5740
5741 #[test]
5742 fn projection_with_wildcard_expr_before_pk_preserves_pk() -> Result<()> {
5743 let constraints =
5744 Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5745 let source = Arc::new(
5746 LogicalTableSource::new(Arc::new(employee_schema()))
5747 .with_constraints(constraints),
5748 );
5749 let input = LogicalPlanBuilder::scan("employee_csv", source, None)?.build()?;
5750 #[expect(deprecated)]
5751 let projection = Projection::try_new(
5752 vec![
5753 Expr::Wildcard {
5754 qualifier: None,
5755 options: Box::new(crate::expr::WildcardOptions::default()),
5756 },
5757 col("employee_csv.id"),
5758 ],
5759 Arc::new(input),
5760 )?;
5761
5762 let deps = projection.schema.functional_dependencies();
5763 assert_eq!(deps.len(), 1);
5764 assert_eq!(deps[0].source_indices, vec![1]);
5765
5766 Ok(())
5767 }
5768
5769 #[test]
5770 fn projection_with_alias_preserves_pk() -> Result<()> {
5771 let constraints =
5772 Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5773 let source = Arc::new(
5774 LogicalTableSource::new(Arc::new(employee_schema()))
5775 .with_constraints(constraints),
5776 );
5777 let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5778 .project(vec![col("id").alias("emp_id"), col("first_name")])?
5779 .build()?;
5780
5781 let deps = plan.schema().functional_dependencies();
5782 assert_eq!(deps.len(), 1);
5783 assert_eq!(deps[0].source_indices, vec![0]);
5784 assert_eq!(deps[0].target_indices, vec![0, 1]);
5785
5786 Ok(())
5787 }
5788
5789 #[test]
5790 fn projection_over_unconstrained_table_has_no_dependencies() -> Result<()> {
5791 let source = Arc::new(LogicalTableSource::new(Arc::new(employee_schema())));
5792 let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5793 .project(vec![col("id"), col("first_name")])?
5794 .build()?;
5795
5796 let deps = plan.schema().functional_dependencies();
5797 assert!(deps.is_empty());
5798
5799 Ok(())
5800 }
5801
5802 #[test]
5803 fn aggregate_group_by_repeated_key_keeps_key_dependency() -> Result<()> {
5804 let constraints =
5805 Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5806 let source = Arc::new(
5807 LogicalTableSource::new(Arc::new(employee_schema()))
5808 .with_constraints(constraints),
5809 );
5810 let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5812 .aggregate(
5813 vec![col("id"), col("state"), col("id").alias("k")],
5814 Vec::<Expr>::new(),
5815 )?
5816 .build()?;
5817
5818 let deps = plan.schema().functional_dependencies();
5820 assert_eq!(deps.len(), 1);
5821 assert_eq!(deps[0].source_indices, vec![0]);
5822 assert_eq!(deps[0].target_indices, vec![0, 1, 2]);
5823
5824 Ok(())
5825 }
5826
5827 #[test]
5828 fn projection_resolves_columns_not_flattened_names() -> Result<()> {
5829 let schema = DFSchema::new_with_metadata(
5835 vec![
5836 (
5837 Some(TableReference::bare("orders")),
5838 Arc::new(Field::new("id", DataType::Int32, false)),
5839 ),
5840 (
5841 None,
5842 Arc::new(Field::new("orders.id", DataType::Int32, false)),
5843 ),
5844 ],
5845 Metadata::default(),
5846 )?
5847 .with_functional_dependencies(FunctionalDependencies::new(vec![
5848 FunctionalDependence::new(vec![0], vec![0, 1], false)
5849 .with_mode(Dependency::Single),
5850 ]))?;
5851 let input = LogicalPlan::EmptyRelation(EmptyRelation {
5852 produce_one_row: true,
5853 schema: Arc::new(schema),
5854 });
5855
5856 let exprs = vec![Expr::Column(Column::new_unqualified("orders.id"))];
5858 let deps = calc_func_dependencies_for_project(&exprs, &input)?;
5859 assert!(deps.is_empty());
5860
5861 let exprs = vec![Expr::Column(Column::new(Some("orders"), "id"))];
5863 let deps = calc_func_dependencies_for_project(&exprs, &input)?;
5864 assert_eq!(deps.len(), 1);
5865 assert_eq!(deps[0].source_indices, vec![0]);
5866
5867 Ok(())
5868 }
5869
5870 #[test]
5871 fn aggregate_group_by_on_primary_key_reports_single_dependency() -> Result<()> {
5872 let constraints =
5873 Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]);
5874 let source = Arc::new(
5875 LogicalTableSource::new(Arc::new(employee_schema()))
5876 .with_constraints(constraints),
5877 );
5878 let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5879 .aggregate(vec![col("id")], vec![count(lit(true))])?
5880 .build()?;
5881
5882 let deps = plan.schema().functional_dependencies();
5883 assert_eq!(deps.len(), 1);
5884 assert_eq!(deps[0].source_indices, vec![0]);
5885 assert_eq!(deps[0].mode, Dependency::Single);
5886
5887 Ok(())
5888 }
5889
5890 #[test]
5891 fn aggregate_group_by_without_constraints_still_reports_single_dependency()
5892 -> Result<()> {
5893 let source = Arc::new(LogicalTableSource::new(Arc::new(employee_schema())));
5902 let plan = LogicalPlanBuilder::scan("employee_csv", source, None)?
5903 .aggregate(vec![col("id")], vec![count(lit(true))])?
5904 .build()?;
5905
5906 let deps = plan.schema().functional_dependencies();
5907 assert_eq!(deps.len(), 1);
5908 assert_eq!(deps[0].source_indices, vec![0]);
5909 assert_eq!(deps[0].mode, Dependency::Single);
5910
5911 Ok(())
5912 }
5913
5914 fn i32_split_point(value: i32) -> SplitPoint {
5915 SplitPoint::new(vec![ScalarValue::Int32(Some(value))])
5916 }
5917
5918 fn null_i32_split_point() -> SplitPoint {
5919 SplitPoint::new(vec![ScalarValue::Int32(None)])
5920 }
5921
5922 #[test]
5923 fn logical_range_partitioning_validates_shape() {
5924 let range = RangePartitioning::try_new(
5925 vec![col("id").sort(true, true)],
5926 vec![i32_split_point(10), i32_split_point(20)],
5927 )
5928 .unwrap();
5929 assert_eq!(range.partition_count(), 3);
5930
5931 let range = RangePartitioning::try_new(
5932 vec![col("id").sort(false, true)],
5933 vec![i32_split_point(20), i32_split_point(10)],
5934 )
5935 .unwrap();
5936 assert_eq!(range.partition_count(), 3);
5937
5938 let err = RangePartitioning::try_new(vec![], vec![]).unwrap_err();
5939 assert!(err.to_string().contains("non-empty ordering"));
5940
5941 let err = RangePartitioning::try_new(
5942 vec![col("id").sort(true, true), col("salary").sort(true, true)],
5943 vec![i32_split_point(10)],
5944 )
5945 .unwrap_err();
5946 assert!(
5947 err.to_string()
5948 .contains("split point 0 has width 1, but ordering has width 2")
5949 );
5950
5951 let err = RangePartitioning::try_new(
5952 vec![col("id").sort(true, true)],
5953 vec![i32_split_point(20), i32_split_point(10)],
5954 )
5955 .unwrap_err();
5956 assert!(
5957 err.to_string()
5958 .contains("split points must be strictly ordered")
5959 );
5960
5961 let err = RangePartitioning::try_new(
5962 vec![col("id").sort(true, true)],
5963 vec![i32_split_point(10), i32_split_point(10)],
5964 )
5965 .unwrap_err();
5966 assert!(
5967 err.to_string()
5968 .contains("split points must be strictly ordered")
5969 );
5970
5971 let range = RangePartitioning::try_new(
5972 vec![col("id").sort(true, true)],
5973 vec![null_i32_split_point(), i32_split_point(10)],
5974 )
5975 .unwrap();
5976 assert_eq!(range.partition_count(), 3);
5977 }
5978
5979 #[test]
5980 fn logical_partitioning_reports_known_partition_count() -> Result<()> {
5981 let range = RangePartitioning::try_new(
5982 vec![col("id").sort(true, true)],
5983 vec![i32_split_point(10)],
5984 )?;
5985
5986 assert_eq!(Partitioning::RoundRobinBatch(4).partition_count(), Some(4));
5987 assert_eq!(
5988 Partitioning::Hash(vec![col("id")], 8).partition_count(),
5989 Some(8)
5990 );
5991 assert_eq!(Partitioning::Range(range).partition_count(), Some(2));
5992 assert_eq!(
5993 Partitioning::DistributeBy(vec![col("id")]).partition_count(),
5994 None
5995 );
5996
5997 Ok(())
5998 }
5999
6000 #[test]
6001 fn logical_range_partitioning_participates_in_expression_rewrite() -> Result<()> {
6002 let input =
6003 table_scan(Some("employee_csv"), &employee_schema(), None)?.build()?;
6004 let plan = LogicalPlan::Repartition(Repartition {
6005 input: Arc::new(input),
6006 partitioning_scheme: Partitioning::Range(RangePartitioning::try_new(
6007 vec![col("id").sort(true, true)],
6008 vec![i32_split_point(10)],
6009 )?),
6010 });
6011
6012 let mut visited_exprs = vec![];
6013 plan.apply_expressions(|expr| {
6014 visited_exprs.push(expr.to_string());
6015 Ok(TreeNodeRecursion::Continue)
6016 })?;
6017 assert_eq!(visited_exprs, vec!["id"]);
6018
6019 let plan = plan
6020 .map_expressions(|expr| {
6021 if expr == col("id") {
6022 Ok(Transformed::yes(col("salary")))
6023 } else {
6024 Ok(Transformed::no(expr))
6025 }
6026 })?
6027 .data;
6028
6029 let LogicalPlan::Repartition(Repartition {
6030 partitioning_scheme: Partitioning::Range(range),
6031 ..
6032 }) = plan
6033 else {
6034 unreachable!("expected range repartition");
6035 };
6036 assert_eq!(range.ordering()[0].expr, col("salary"));
6037 assert_eq!(range.partition_count(), 2);
6038
6039 Ok(())
6040 }
6041
6042 fn display_plan() -> Result<LogicalPlan> {
6043 let plan1 = table_scan(Some("employee_csv"), &employee_schema(), Some(vec![3]))?
6044 .build()?;
6045
6046 table_scan(Some("employee_csv"), &employee_schema(), Some(vec![0, 3]))?
6047 .filter(in_subquery(col("state"), Arc::new(plan1)))?
6048 .project(vec![col("id")])?
6049 .build()
6050 }
6051
6052 fn recursive_term_scan(name: &str, fields: Vec<Field>) -> Result<Arc<LogicalPlan>> {
6053 Ok(Arc::new(
6054 table_scan(Some(name), &Schema::new(fields), None)?.build()?,
6055 ))
6056 }
6057
6058 #[test]
6059 fn recursive_query_widens_nullability_per_column() -> Result<()> {
6060 let static_term = recursive_term_scan(
6064 "static",
6065 vec![
6066 Field::new("a", DataType::Int32, false),
6067 Field::new("b", DataType::Int32, false),
6068 ],
6069 )?;
6070 let recursive_term = recursive_term_scan(
6071 "rec",
6072 vec![
6073 Field::new("a", DataType::Int32, false),
6074 Field::new("b", DataType::Int32, true),
6075 ],
6076 )?;
6077
6078 let query =
6079 RecursiveQuery::try_new("t".to_string(), static_term, recursive_term, false)?;
6080
6081 assert_eq!(query.schema.field(0).name(), "a");
6083 assert_eq!(query.schema.field(1).name(), "b");
6084 assert_eq!(query.schema.field(0).data_type(), &DataType::Int32);
6085 assert_eq!(query.schema.field(1).data_type(), &DataType::Int32);
6086 assert!(!query.schema.field(0).is_nullable());
6088 assert!(query.schema.field(1).is_nullable());
6089 assert_eq!(
6091 LogicalPlan::RecursiveQuery(query.clone()).schema(),
6092 &query.schema
6093 );
6094 Ok(())
6095 }
6096
6097 #[test]
6098 fn recursive_query_rejects_column_count_mismatch() -> Result<()> {
6099 let static_term =
6100 recursive_term_scan("static", vec![Field::new("a", DataType::Int32, false)])?;
6101 let recursive_term = recursive_term_scan(
6102 "rec",
6103 vec![
6104 Field::new("a", DataType::Int32, false),
6105 Field::new("b", DataType::Int32, false),
6106 ],
6107 )?;
6108
6109 let err =
6110 RecursiveQuery::try_new("t".to_string(), static_term, recursive_term, false)
6111 .unwrap_err();
6112 assert!(
6113 err.strip_backtrace()
6114 .contains("must have the same number of columns"),
6115 "unexpected error: {err}"
6116 );
6117 Ok(())
6118 }
6119
6120 #[test]
6121 fn test_display_indent() -> Result<()> {
6122 let plan = display_plan()?;
6123
6124 assert_snapshot!(plan.display_indent(), @r"
6125 Projection: employee_csv.id
6126 Filter: employee_csv.state IN (<subquery>)
6127 Subquery:
6128 TableScan: employee_csv projection=[state]
6129 TableScan: employee_csv projection=[id, state]
6130 ");
6131 Ok(())
6132 }
6133
6134 #[test]
6135 fn test_display_indent_schema() -> Result<()> {
6136 let plan = display_plan()?;
6137
6138 assert_snapshot!(plan.display_indent_schema(), @r"
6139 Projection: employee_csv.id [id:Int32]
6140 Filter: employee_csv.state IN (<subquery>) [id:Int32, state:Utf8]
6141 Subquery: [state:Utf8]
6142 TableScan: employee_csv projection=[state] [state:Utf8]
6143 TableScan: employee_csv projection=[id, state] [id:Int32, state:Utf8]
6144 ");
6145 Ok(())
6146 }
6147
6148 #[test]
6149 fn test_display_subquery_alias() -> Result<()> {
6150 let plan1 = table_scan(Some("employee_csv"), &employee_schema(), Some(vec![3]))?
6151 .build()?;
6152 let plan1 = Arc::new(plan1);
6153
6154 let plan =
6155 table_scan(Some("employee_csv"), &employee_schema(), Some(vec![0, 3]))?
6156 .project(vec![col("id"), exists(plan1).alias("exists")])?
6157 .build();
6158
6159 assert_snapshot!(plan?.display_indent(), @r"
6160 Projection: employee_csv.id, EXISTS (<subquery>) AS exists
6161 Subquery:
6162 TableScan: employee_csv projection=[state]
6163 TableScan: employee_csv projection=[id, state]
6164 ");
6165 Ok(())
6166 }
6167
6168 #[test]
6169 fn test_display_graphviz() -> Result<()> {
6170 let plan = display_plan()?;
6171
6172 assert_snapshot!(plan.display_graphviz(), @r#"
6175 // Begin DataFusion GraphViz Plan,
6176 // display it online here: https://dreampuf.github.io/GraphvizOnline
6177
6178 digraph {
6179 subgraph cluster_1
6180 {
6181 graph[label="LogicalPlan"]
6182 2[shape=box label="Projection: employee_csv.id"]
6183 3[shape=box label="Filter: employee_csv.state IN (<subquery>)"]
6184 2 -> 3 [arrowhead=none, arrowtail=normal, dir=back]
6185 4[shape=box label="Subquery:"]
6186 3 -> 4 [arrowhead=none, arrowtail=normal, dir=back]
6187 5[shape=box label="TableScan: employee_csv projection=[state]"]
6188 4 -> 5 [arrowhead=none, arrowtail=normal, dir=back]
6189 6[shape=box label="TableScan: employee_csv projection=[id, state]"]
6190 3 -> 6 [arrowhead=none, arrowtail=normal, dir=back]
6191 }
6192 subgraph cluster_7
6193 {
6194 graph[label="Detailed LogicalPlan"]
6195 8[shape=box label="Projection: employee_csv.id\nSchema: [id:Int32]"]
6196 9[shape=box label="Filter: employee_csv.state IN (<subquery>)\nSchema: [id:Int32, state:Utf8]"]
6197 8 -> 9 [arrowhead=none, arrowtail=normal, dir=back]
6198 10[shape=box label="Subquery:\nSchema: [state:Utf8]"]
6199 9 -> 10 [arrowhead=none, arrowtail=normal, dir=back]
6200 11[shape=box label="TableScan: employee_csv projection=[state]\nSchema: [state:Utf8]"]
6201 10 -> 11 [arrowhead=none, arrowtail=normal, dir=back]
6202 12[shape=box label="TableScan: employee_csv projection=[id, state]\nSchema: [id:Int32, state:Utf8]"]
6203 9 -> 12 [arrowhead=none, arrowtail=normal, dir=back]
6204 }
6205 }
6206 // End DataFusion GraphViz Plan
6207 "#);
6208 Ok(())
6209 }
6210
6211 #[test]
6212 fn test_display_pg_json() -> Result<()> {
6213 let plan = display_plan()?;
6214
6215 assert_snapshot!(plan.display_pg_json(), @r#"
6216 [
6217 {
6218 "Plan": {
6219 "Node Type": "Projection",
6220 "Expressions": [
6221 "employee_csv.id"
6222 ],
6223 "Plans": [
6224 {
6225 "Node Type": "Filter",
6226 "Condition": "employee_csv.state IN (<subquery>)",
6227 "Plans": [
6228 {
6229 "Node Type": "Subquery",
6230 "Plans": [
6231 {
6232 "Node Type": "TableScan",
6233 "Relation Name": "employee_csv",
6234 "Plans": [],
6235 "Output": [
6236 "state"
6237 ]
6238 }
6239 ],
6240 "Output": [
6241 "state"
6242 ]
6243 },
6244 {
6245 "Node Type": "TableScan",
6246 "Relation Name": "employee_csv",
6247 "Plans": [],
6248 "Output": [
6249 "id",
6250 "state"
6251 ]
6252 }
6253 ],
6254 "Output": [
6255 "id",
6256 "state"
6257 ]
6258 }
6259 ],
6260 "Output": [
6261 "id"
6262 ]
6263 }
6264 }
6265 ]
6266 "#);
6267 Ok(())
6268 }
6269
6270 #[derive(Debug, Default)]
6272 struct OkVisitor {
6273 strings: Vec<String>,
6274 }
6275
6276 impl<'n> TreeNodeVisitor<'n> for OkVisitor {
6277 type Node = LogicalPlan;
6278
6279 fn f_down(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6280 let s = match plan {
6281 LogicalPlan::Projection { .. } => "pre_visit Projection",
6282 LogicalPlan::Filter { .. } => "pre_visit Filter",
6283 LogicalPlan::TableScan { .. } => "pre_visit TableScan",
6284 _ => {
6285 return not_impl_err!("unknown plan type");
6286 }
6287 };
6288
6289 self.strings.push(s.into());
6290 Ok(TreeNodeRecursion::Continue)
6291 }
6292
6293 fn f_up(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6294 let s = match plan {
6295 LogicalPlan::Projection { .. } => "post_visit Projection",
6296 LogicalPlan::Filter { .. } => "post_visit Filter",
6297 LogicalPlan::TableScan { .. } => "post_visit TableScan",
6298 _ => {
6299 return not_impl_err!("unknown plan type");
6300 }
6301 };
6302
6303 self.strings.push(s.into());
6304 Ok(TreeNodeRecursion::Continue)
6305 }
6306 }
6307
6308 #[test]
6309 fn visit_order() {
6310 let mut visitor = OkVisitor::default();
6311 let plan = test_plan();
6312 let res = plan.visit_with_subqueries(&mut visitor);
6313 assert!(res.is_ok());
6314
6315 assert_debug_snapshot!(visitor.strings, @r#"
6316 [
6317 "pre_visit Projection",
6318 "pre_visit Filter",
6319 "pre_visit TableScan",
6320 "post_visit TableScan",
6321 "post_visit Filter",
6322 "post_visit Projection",
6323 ]
6324 "#);
6325 }
6326
6327 #[derive(Debug, Default)]
6328 struct OptionalCounter {
6330 val: Option<usize>,
6331 }
6332
6333 impl OptionalCounter {
6334 fn new(val: usize) -> Self {
6335 Self { val: Some(val) }
6336 }
6337 fn dec(&mut self) -> bool {
6339 if Some(0) == self.val {
6340 true
6341 } else {
6342 self.val = self.val.take().map(|i| i - 1);
6343 false
6344 }
6345 }
6346 }
6347
6348 #[derive(Debug, Default)]
6349 struct StoppingVisitor {
6351 inner: OkVisitor,
6352 return_false_from_pre_in: OptionalCounter,
6354 return_false_from_post_in: OptionalCounter,
6356 }
6357
6358 impl<'n> TreeNodeVisitor<'n> for StoppingVisitor {
6359 type Node = LogicalPlan;
6360
6361 fn f_down(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6362 if self.return_false_from_pre_in.dec() {
6363 return Ok(TreeNodeRecursion::Stop);
6364 }
6365 self.inner.f_down(plan)?;
6366
6367 Ok(TreeNodeRecursion::Continue)
6368 }
6369
6370 fn f_up(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6371 if self.return_false_from_post_in.dec() {
6372 return Ok(TreeNodeRecursion::Stop);
6373 }
6374
6375 self.inner.f_up(plan)
6376 }
6377 }
6378
6379 #[test]
6381 fn early_stopping_pre_visit() {
6382 let mut visitor = StoppingVisitor {
6383 return_false_from_pre_in: OptionalCounter::new(2),
6384 ..Default::default()
6385 };
6386 let plan = test_plan();
6387 let res = plan.visit_with_subqueries(&mut visitor);
6388 assert!(res.is_ok());
6389
6390 assert_debug_snapshot!(
6391 visitor.inner.strings,
6392 @r#"
6393 [
6394 "pre_visit Projection",
6395 "pre_visit Filter",
6396 ]
6397 "#
6398 );
6399 }
6400
6401 #[test]
6402 fn early_stopping_post_visit() {
6403 let mut visitor = StoppingVisitor {
6404 return_false_from_post_in: OptionalCounter::new(1),
6405 ..Default::default()
6406 };
6407 let plan = test_plan();
6408 let res = plan.visit_with_subqueries(&mut visitor);
6409 assert!(res.is_ok());
6410
6411 assert_debug_snapshot!(
6412 visitor.inner.strings,
6413 @r#"
6414 [
6415 "pre_visit Projection",
6416 "pre_visit Filter",
6417 "pre_visit TableScan",
6418 "post_visit TableScan",
6419 ]
6420 "#
6421 );
6422 }
6423
6424 #[derive(Debug, Default)]
6425 struct ErrorVisitor {
6427 inner: OkVisitor,
6428 return_error_from_pre_in: OptionalCounter,
6430 return_error_from_post_in: OptionalCounter,
6432 }
6433
6434 impl<'n> TreeNodeVisitor<'n> for ErrorVisitor {
6435 type Node = LogicalPlan;
6436
6437 fn f_down(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6438 if self.return_error_from_pre_in.dec() {
6439 return not_impl_err!("Error in pre_visit");
6440 }
6441
6442 self.inner.f_down(plan)
6443 }
6444
6445 fn f_up(&mut self, plan: &'n LogicalPlan) -> Result<TreeNodeRecursion> {
6446 if self.return_error_from_post_in.dec() {
6447 return not_impl_err!("Error in post_visit");
6448 }
6449
6450 self.inner.f_up(plan)
6451 }
6452 }
6453
6454 #[test]
6455 fn error_pre_visit() {
6456 let mut visitor = ErrorVisitor {
6457 return_error_from_pre_in: OptionalCounter::new(2),
6458 ..Default::default()
6459 };
6460 let plan = test_plan();
6461 let res = plan.visit_with_subqueries(&mut visitor).unwrap_err();
6462 assert_snapshot!(
6463 res.strip_backtrace(),
6464 @"This feature is not implemented: Error in pre_visit"
6465 );
6466 assert_debug_snapshot!(
6467 visitor.inner.strings,
6468 @r#"
6469 [
6470 "pre_visit Projection",
6471 "pre_visit Filter",
6472 ]
6473 "#
6474 );
6475 }
6476
6477 #[test]
6478 fn error_post_visit() {
6479 let mut visitor = ErrorVisitor {
6480 return_error_from_post_in: OptionalCounter::new(1),
6481 ..Default::default()
6482 };
6483 let plan = test_plan();
6484 let res = plan.visit_with_subqueries(&mut visitor).unwrap_err();
6485 assert_snapshot!(
6486 res.strip_backtrace(),
6487 @"This feature is not implemented: Error in post_visit"
6488 );
6489 assert_debug_snapshot!(
6490 visitor.inner.strings,
6491 @r#"
6492 [
6493 "pre_visit Projection",
6494 "pre_visit Filter",
6495 "pre_visit TableScan",
6496 "post_visit TableScan",
6497 ]
6498 "#
6499 );
6500 }
6501
6502 #[test]
6503 fn test_partial_eq_hash_and_partial_ord() {
6504 let empty_values = Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
6505 produce_one_row: true,
6506 schema: Arc::new(DFSchema::empty()),
6507 }));
6508
6509 let count_window_function = |schema| {
6510 Window::try_new_with_schema(
6511 vec![Expr::WindowFunction(Box::new(WindowFunction::new(
6512 WindowFunctionDefinition::AggregateUDF(count_udaf()),
6513 vec![],
6514 )))],
6515 Arc::clone(&empty_values),
6516 Arc::new(schema),
6517 )
6518 .unwrap()
6519 };
6520
6521 let schema_without_metadata = || {
6522 DFSchema::from_unqualified_fields(
6523 vec![Field::new("count", DataType::Int64, false)].into(),
6524 HashMap::new(),
6525 )
6526 .unwrap()
6527 };
6528
6529 let schema_with_metadata = || {
6530 DFSchema::from_unqualified_fields(
6531 vec![Field::new("count", DataType::Int64, false)].into(),
6532 Metadata::new().with("key", "value"),
6533 )
6534 .unwrap()
6535 };
6536
6537 let f = count_window_function(schema_without_metadata());
6539
6540 let f2 = count_window_function(schema_without_metadata());
6542 assert_eq!(f, f2);
6543 assert_eq!(hash(&f), hash(&f2));
6544 assert_eq!(f.partial_cmp(&f2), Some(Ordering::Equal));
6545
6546 let o = count_window_function(schema_with_metadata());
6548 assert_ne!(f, o);
6549 assert_ne!(hash(&f), hash(&o)); assert_eq!(f.partial_cmp(&o), None);
6551 }
6552
6553 fn hash<T: Hash>(value: &T) -> u64 {
6554 let hasher = &mut DefaultHasher::new();
6555 value.hash(hasher);
6556 hasher.finish()
6557 }
6558
6559 #[test]
6560 fn projection_expr_schema_mismatch() -> Result<()> {
6561 let empty_schema = Arc::new(DFSchema::empty());
6562 let p = Projection::try_new_with_schema(
6563 vec![col("a")],
6564 Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
6565 produce_one_row: false,
6566 schema: Arc::clone(&empty_schema),
6567 })),
6568 empty_schema,
6569 );
6570 assert_snapshot!(p.unwrap_err().strip_backtrace(), @"Error during planning: Projection has mismatch between number of expressions (1) and number of fields in schema (0)");
6571 Ok(())
6572 }
6573
6574 fn test_plan() -> LogicalPlan {
6575 let schema = Schema::new(vec![
6576 Field::new("id", DataType::Int32, false),
6577 Field::new("state", DataType::Utf8, false),
6578 ]);
6579
6580 table_scan(TableReference::none(), &schema, Some(vec![0, 1]))
6581 .unwrap()
6582 .filter(col("state").eq(lit("CO")))
6583 .unwrap()
6584 .project(vec![col("id")])
6585 .unwrap()
6586 .build()
6587 .unwrap()
6588 }
6589
6590 #[test]
6591 fn min_rows_is_a_conservative_lower_bound() -> Result<()> {
6592 let no_rows = LogicalPlanBuilder::empty(false).build()?;
6593 let one_row = LogicalPlanBuilder::empty(true).build()?;
6594 assert_eq!(no_rows.min_rows(), 0);
6595 assert_eq!(no_rows.max_rows(), Some(0));
6596 assert_eq!(one_row.min_rows(), 1);
6597 assert_eq!(one_row.max_rows(), Some(1));
6598
6599 let projection = LogicalPlanBuilder::from(one_row.clone())
6600 .project(vec![lit(1)])?
6601 .build()?;
6602 assert_eq!(projection.min_rows(), 1);
6603
6604 let filter = LogicalPlanBuilder::from(projection.clone())
6605 .filter(lit(true))?
6606 .build()?;
6607 assert_eq!(filter.min_rows(), 0);
6608
6609 let aggregate = LogicalPlanBuilder::from(no_rows)
6610 .aggregate(Vec::<Expr>::new(), vec![count(lit(1))])?
6611 .build()?;
6612 assert_eq!(aggregate.min_rows(), 1);
6613
6614 let offset = LogicalPlanBuilder::from(projection.clone())
6615 .limit(1, None)?
6616 .build()?;
6617 assert_eq!(offset.min_rows(), 0);
6618
6619 let union = LogicalPlanBuilder::from(projection.clone())
6620 .union(projection)?
6621 .build()?;
6622 assert_eq!(union.min_rows(), 2);
6623 assert_eq!(
6624 LogicalPlanBuilder::from(union)
6625 .distinct()?
6626 .build()?
6627 .min_rows(),
6628 1
6629 );
6630
6631 let values =
6632 LogicalPlanBuilder::values(vec![vec![lit(1)], vec![lit(2)]])?.build()?;
6633 assert_eq!(values.min_rows(), 2);
6634
6635 let sort_key = col("column1").sort(true, false);
6636 let sort = LogicalPlanBuilder::from(values.clone())
6637 .sort(vec![sort_key.clone()])?
6638 .build()?;
6639 assert_eq!(sort.min_rows(), 2);
6640 let sort_with_fetch = LogicalPlanBuilder::from(values.clone())
6641 .sort_with_limit(vec![sort_key], Some(1))?
6642 .build()?;
6643 assert_eq!(sort_with_fetch.min_rows(), 1);
6644
6645 let limit = LogicalPlanBuilder::from(values.clone())
6646 .limit(1, Some(5))?
6647 .build()?;
6648 assert_eq!(limit.min_rows(), 1);
6649
6650 let grouped = LogicalPlanBuilder::from(values)
6651 .aggregate(vec![col("column1")], vec![count(lit(1))])?
6652 .build()?;
6653 assert_eq!(grouped.min_rows(), 0);
6654
6655 let scan = table_scan(Some("employee"), &employee_schema(), None)?.build()?;
6656 assert_eq!(scan.min_rows(), 0);
6657
6658 Ok(())
6659 }
6660
6661 #[test]
6662 fn min_rows_of_joins() -> Result<()> {
6663 let two_rows = LogicalPlanBuilder::values(vec![vec![lit(1)], vec![lit(2)]])?
6664 .alias("l")?
6665 .build()?;
6666 let one_row = LogicalPlanBuilder::values(vec![vec![lit(1)]])?
6667 .alias("r")?
6668 .build()?;
6669
6670 let cross_join = LogicalPlanBuilder::from(two_rows.clone())
6671 .cross_join(one_row.clone())?
6672 .build()?;
6673 assert_eq!(cross_join.min_rows(), 2);
6674
6675 let asof_join = LogicalPlanBuilder::from(two_rows.clone())
6676 .asof_join_on(
6677 one_row.clone(),
6678 None,
6679 col("l.column1").gt_eq(col("r.column1")),
6680 )?
6681 .build()?;
6682 assert_eq!(asof_join.min_rows(), 2);
6683
6684 for (join_type, expected_min_rows) in [
6685 (JoinType::Inner, 0),
6688 (JoinType::Left, 2),
6689 (JoinType::Right, 1),
6690 (JoinType::Full, 2),
6691 (JoinType::LeftSemi, 0),
6692 ] {
6693 let join = LogicalPlanBuilder::from(two_rows.clone())
6694 .join_on(
6695 one_row.clone(),
6696 join_type,
6697 [col("l.column1").eq(col("r.column1"))],
6698 )?
6699 .build()?;
6700 assert_eq!(join.min_rows(), expected_min_rows, "{join_type} join");
6701 }
6702
6703 Ok(())
6704 }
6705
6706 #[test]
6707 fn test_replace_invalid_placeholder() {
6708 let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
6710
6711 let plan = table_scan(TableReference::none(), &schema, None)
6712 .unwrap()
6713 .filter(col("id").eq(placeholder("")))
6714 .unwrap()
6715 .build()
6716 .unwrap();
6717
6718 let param_values = vec![ScalarValue::Int32(Some(42))];
6719 plan.replace_params_with_values(¶m_values.clone().into())
6720 .expect_err("unexpectedly succeeded to replace an invalid placeholder");
6721
6722 let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
6724
6725 let plan = table_scan(TableReference::none(), &schema, None)
6726 .unwrap()
6727 .filter(col("id").eq(placeholder("$0")))
6728 .unwrap()
6729 .build()
6730 .unwrap();
6731
6732 plan.replace_params_with_values(¶m_values.clone().into())
6733 .expect_err("unexpectedly succeeded to replace an invalid placeholder");
6734
6735 let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
6737
6738 let plan = table_scan(TableReference::none(), &schema, None)
6739 .unwrap()
6740 .filter(col("id").eq(placeholder("$00")))
6741 .unwrap()
6742 .build()
6743 .unwrap();
6744
6745 plan.replace_params_with_values(¶m_values.into())
6746 .expect_err("unexpectedly succeeded to replace an invalid placeholder");
6747 }
6748
6749 #[test]
6750 fn test_replace_placeholder_mismatched_metadata() {
6751 let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
6752
6753 let plan = table_scan(TableReference::none(), &schema, None)
6755 .unwrap()
6756 .filter(col("id").eq(placeholder("$1")))
6757 .unwrap()
6758 .build()
6759 .unwrap();
6760 let prepared_builder = LogicalPlanBuilder::new(plan)
6761 .prepare(
6762 "".to_string(),
6763 vec![Field::new("", DataType::Int32, true).into()],
6764 )
6765 .unwrap();
6766
6767 let mut scalar_meta = HashMap::new();
6769 scalar_meta.insert("some_key".to_string(), "some_value".to_string());
6770 let param_values = ParamValues::List(vec![ScalarAndMetadata::new(
6771 ScalarValue::Int32(Some(42)),
6772 Some(scalar_meta.into()),
6773 )]);
6774 prepared_builder
6775 .plan()
6776 .clone()
6777 .with_param_values(param_values)
6778 .expect_err("prepared field metadata mismatch unexpectedly succeeded");
6779 }
6780
6781 #[test]
6782 fn test_replace_placeholder_empty_relation_valid_schema() {
6783 let plan = LogicalPlanBuilder::empty(false)
6785 .project(vec![
6786 SelectExpr::from(placeholder("$1")),
6787 SelectExpr::from(placeholder("$2")),
6788 ])
6789 .unwrap()
6790 .build()
6791 .unwrap();
6792
6793 assert_snapshot!(plan.display_indent_schema(), @r"
6795 Projection: $1, $2 [$1:Null;N, $2:Null;N]
6796 EmptyRelation: rows=0 []
6797 ");
6798
6799 let plan = plan
6800 .with_param_values(vec![ScalarValue::from(1i32), ScalarValue::from("s")])
6801 .unwrap();
6802
6803 assert_snapshot!(plan.display_indent_schema(), @r#"
6805 Projection: Int32(1) AS $1, Utf8("s") AS $2 [$1:Int32, $2:Utf8]
6806 EmptyRelation: rows=0 []
6807 "#);
6808 }
6809
6810 #[test]
6811 fn test_nullable_schema_after_grouping_set() {
6812 let schema = Schema::new(vec![
6813 Field::new("foo", DataType::Int32, false),
6814 Field::new("bar", DataType::Int32, false),
6815 ]);
6816
6817 let plan = table_scan(TableReference::none(), &schema, None)
6818 .unwrap()
6819 .aggregate(
6820 vec![Expr::GroupingSet(GroupingSet::GroupingSets(vec![
6821 vec![col("foo")],
6822 vec![col("bar")],
6823 ]))],
6824 vec![count(lit(true))],
6825 )
6826 .unwrap()
6827 .build()
6828 .unwrap();
6829
6830 let output_schema = plan.schema();
6831
6832 assert!(
6833 output_schema
6834 .field_with_name(None, "foo")
6835 .unwrap()
6836 .is_nullable(),
6837 );
6838 assert!(
6839 output_schema
6840 .field_with_name(None, "bar")
6841 .unwrap()
6842 .is_nullable()
6843 );
6844 }
6845
6846 #[test]
6847 fn grouping_id_type_accounts_for_duplicate_ordinal_bits() {
6848 assert_eq!(Aggregate::grouping_id_type(8, 0), DataType::UInt8);
6851 assert_eq!(Aggregate::grouping_id_type(8, 1), DataType::UInt16);
6852 }
6853
6854 #[test]
6855 fn test_filter_is_scalar() {
6856 let schema =
6858 Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
6859
6860 let source = Arc::new(LogicalTableSource::new(schema));
6861 let schema = Arc::new(
6862 DFSchema::try_from_qualified_schema(
6863 TableReference::bare("tab"),
6864 &source.schema(),
6865 )
6866 .unwrap(),
6867 );
6868 let scan = Arc::new(LogicalPlan::TableScan(TableScan {
6869 table_name: TableReference::bare("tab"),
6870 source: Arc::clone(&source) as Arc<dyn TableSource>,
6871 projection: None,
6872 projected_schema: Arc::clone(&schema),
6873 filters: vec![],
6874 fetch: None,
6875 skip: None,
6876 statistics_requests: Box::default(),
6877 }));
6878 let col = schema.field_names()[0].clone();
6879
6880 let filter = Filter::try_new(
6881 Expr::Column(col.into()).eq(Expr::Literal(ScalarValue::Int32(Some(1)), None)),
6882 scan,
6883 )
6884 .unwrap();
6885 assert!(!filter.is_scalar());
6886 let unique_schema = Arc::new(
6887 schema
6888 .as_ref()
6889 .clone()
6890 .with_functional_dependencies(
6891 FunctionalDependencies::new_from_constraints(
6892 Some(&Constraints::new_unverified(vec![Constraint::Unique(
6893 vec![0],
6894 )])),
6895 1,
6896 ),
6897 )
6898 .unwrap(),
6899 );
6900 let scan = Arc::new(LogicalPlan::TableScan(TableScan {
6901 table_name: TableReference::bare("tab"),
6902 source,
6903 projection: None,
6904 projected_schema: Arc::clone(&unique_schema),
6905 filters: vec![],
6906 fetch: None,
6907 skip: None,
6908 statistics_requests: Box::default(),
6909 }));
6910 let col = schema.field_names()[0].clone();
6911
6912 let filter =
6913 Filter::try_new(Expr::Column(col.into()).eq(lit(1i32)), scan).unwrap();
6914 assert!(filter.is_scalar());
6915 }
6916
6917 #[test]
6918 fn test_transform_explain() {
6919 let schema = Schema::new(vec![
6920 Field::new("foo", DataType::Int32, false),
6921 Field::new("bar", DataType::Int32, false),
6922 ]);
6923
6924 let plan = table_scan(TableReference::none(), &schema, None)
6925 .unwrap()
6926 .explain(false, false)
6927 .unwrap()
6928 .build()
6929 .unwrap();
6930
6931 let external_filter = col("foo").eq(lit(true));
6932
6933 let plan = plan
6936 .transform(|plan| match plan {
6937 LogicalPlan::TableScan(table) => {
6938 let filter = Filter::try_new(
6939 external_filter.clone(),
6940 Arc::new(LogicalPlan::TableScan(table)),
6941 )
6942 .unwrap();
6943 Ok(Transformed::yes(LogicalPlan::Filter(filter)))
6944 }
6945 x => Ok(Transformed::no(x)),
6946 })
6947 .data()
6948 .unwrap();
6949
6950 let actual = format!("{}", plan.display_indent());
6951 assert_snapshot!(actual, @r"
6952 Explain
6953 Filter: foo = Boolean(true)
6954 TableScan: ?table?
6955 ")
6956 }
6957
6958 #[test]
6959 fn test_plan_partial_ord() {
6960 let empty_relation = LogicalPlan::EmptyRelation(EmptyRelation {
6961 produce_one_row: false,
6962 schema: Arc::new(DFSchema::empty()),
6963 });
6964
6965 let describe_table = LogicalPlan::Show(Show {
6966 kind: ShowKind::Describe {
6967 schema: Arc::new(Schema::new(vec![Field::new(
6968 "foo",
6969 DataType::Int32,
6970 false,
6971 )])),
6972 },
6973 output_schema: DFSchemaRef::new(DFSchema::empty()),
6974 });
6975
6976 let describe_table_clone = LogicalPlan::Show(Show {
6977 kind: ShowKind::Describe {
6978 schema: Arc::new(Schema::new(vec![Field::new(
6979 "foo",
6980 DataType::Int32,
6981 false,
6982 )])),
6983 },
6984 output_schema: DFSchemaRef::new(DFSchema::empty()),
6985 });
6986
6987 assert_eq!(
6988 empty_relation.partial_cmp(&describe_table),
6989 Some(Ordering::Less)
6990 );
6991 assert_eq!(
6992 describe_table.partial_cmp(&empty_relation),
6993 Some(Ordering::Greater)
6994 );
6995 assert_eq!(describe_table.partial_cmp(&describe_table_clone), None);
6996 }
6997
6998 #[test]
6999 fn test_limit_with_new_children() {
7000 let input = Arc::new(LogicalPlan::Values(Values {
7001 schema: Arc::new(DFSchema::empty()),
7002 values: vec![vec![]],
7003 }));
7004 let cases = [
7005 LogicalPlan::Limit(Limit {
7006 skip: None,
7007 fetch: None,
7008 input: Arc::clone(&input),
7009 }),
7010 LogicalPlan::Limit(Limit {
7011 skip: None,
7012 fetch: Some(Box::new(Expr::Literal(
7013 ScalarValue::new_ten(&DataType::UInt32).unwrap(),
7014 None,
7015 ))),
7016 input: Arc::clone(&input),
7017 }),
7018 LogicalPlan::Limit(Limit {
7019 skip: Some(Box::new(Expr::Literal(
7020 ScalarValue::new_ten(&DataType::UInt32).unwrap(),
7021 None,
7022 ))),
7023 fetch: None,
7024 input: Arc::clone(&input),
7025 }),
7026 LogicalPlan::Limit(Limit {
7027 skip: Some(Box::new(Expr::Literal(
7028 ScalarValue::new_one(&DataType::UInt32).unwrap(),
7029 None,
7030 ))),
7031 fetch: Some(Box::new(Expr::Literal(
7032 ScalarValue::new_ten(&DataType::UInt32).unwrap(),
7033 None,
7034 ))),
7035 input,
7036 }),
7037 ];
7038
7039 for limit in cases {
7040 let new_limit = limit
7041 .with_new_exprs(
7042 limit.expressions(),
7043 limit.inputs().into_iter().cloned().collect(),
7044 )
7045 .unwrap();
7046 assert_eq!(limit, new_limit);
7047 }
7048 }
7049
7050 #[test]
7051 fn test_with_subqueries_jump() {
7052 let subquery_schema =
7057 Schema::new(vec![Field::new("sub_id", DataType::Int32, false)]);
7058
7059 let subquery_plan =
7060 table_scan(TableReference::none(), &subquery_schema, Some(vec![0]))
7061 .unwrap()
7062 .filter(col("sub_id").eq(lit(0)))
7063 .unwrap()
7064 .build()
7065 .unwrap();
7066
7067 let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
7068
7069 let plan = table_scan(TableReference::none(), &schema, Some(vec![0]))
7070 .unwrap()
7071 .filter(col("id").eq(lit(0)))
7072 .unwrap()
7073 .project(vec![col("id"), scalar_subquery(Arc::new(subquery_plan))])
7074 .unwrap()
7075 .build()
7076 .unwrap();
7077
7078 let mut filter_found = false;
7079 plan.apply_with_subqueries(|plan| {
7080 match plan {
7081 LogicalPlan::Projection(..) => return Ok(TreeNodeRecursion::Jump),
7082 LogicalPlan::Filter(..) => filter_found = true,
7083 _ => {}
7084 }
7085 Ok(TreeNodeRecursion::Continue)
7086 })
7087 .unwrap();
7088 assert!(!filter_found);
7089
7090 struct ProjectJumpVisitor {
7091 filter_found: bool,
7092 }
7093
7094 impl ProjectJumpVisitor {
7095 fn new() -> Self {
7096 Self {
7097 filter_found: false,
7098 }
7099 }
7100 }
7101
7102 impl<'n> TreeNodeVisitor<'n> for ProjectJumpVisitor {
7103 type Node = LogicalPlan;
7104
7105 fn f_down(&mut self, node: &'n Self::Node) -> Result<TreeNodeRecursion> {
7106 match node {
7107 LogicalPlan::Projection(..) => return Ok(TreeNodeRecursion::Jump),
7108 LogicalPlan::Filter(..) => self.filter_found = true,
7109 _ => {}
7110 }
7111 Ok(TreeNodeRecursion::Continue)
7112 }
7113 }
7114
7115 let mut visitor = ProjectJumpVisitor::new();
7116 plan.visit_with_subqueries(&mut visitor).unwrap();
7117 assert!(!visitor.filter_found);
7118
7119 let mut filter_found = false;
7120 plan.clone()
7121 .transform_down_with_subqueries(|plan| {
7122 match plan {
7123 LogicalPlan::Projection(..) => {
7124 return Ok(Transformed::new(
7125 plan,
7126 false,
7127 TreeNodeRecursion::Jump,
7128 ));
7129 }
7130 LogicalPlan::Filter(..) => filter_found = true,
7131 _ => {}
7132 }
7133 Ok(Transformed::no(plan))
7134 })
7135 .unwrap();
7136 assert!(!filter_found);
7137
7138 let mut filter_found = false;
7139 plan.clone()
7140 .transform_down_up_with_subqueries(
7141 |plan| {
7142 match plan {
7143 LogicalPlan::Projection(..) => {
7144 return Ok(Transformed::new(
7145 plan,
7146 false,
7147 TreeNodeRecursion::Jump,
7148 ));
7149 }
7150 LogicalPlan::Filter(..) => filter_found = true,
7151 _ => {}
7152 }
7153 Ok(Transformed::no(plan))
7154 },
7155 |plan| Ok(Transformed::no(plan)),
7156 )
7157 .unwrap();
7158 assert!(!filter_found);
7159
7160 struct ProjectJumpRewriter {
7161 filter_found: bool,
7162 }
7163
7164 impl ProjectJumpRewriter {
7165 fn new() -> Self {
7166 Self {
7167 filter_found: false,
7168 }
7169 }
7170 }
7171
7172 impl TreeNodeRewriter for ProjectJumpRewriter {
7173 type Node = LogicalPlan;
7174
7175 fn f_down(&mut self, node: Self::Node) -> Result<Transformed<Self::Node>> {
7176 match node {
7177 LogicalPlan::Projection(..) => {
7178 return Ok(Transformed::new(
7179 node,
7180 false,
7181 TreeNodeRecursion::Jump,
7182 ));
7183 }
7184 LogicalPlan::Filter(..) => self.filter_found = true,
7185 _ => {}
7186 }
7187 Ok(Transformed::no(node))
7188 }
7189 }
7190
7191 let mut rewriter = ProjectJumpRewriter::new();
7192 plan.rewrite_with_subqueries(&mut rewriter).unwrap();
7193 assert!(!rewriter.filter_found);
7194 }
7195
7196 #[test]
7197 fn test_with_unresolved_placeholders() {
7198 let field_name = "id";
7199 let placeholder_value = "$1";
7200 let schema = Schema::new(vec![Field::new(field_name, DataType::Int32, false)]);
7201
7202 let plan = table_scan(TableReference::none(), &schema, None)
7203 .unwrap()
7204 .filter(col(field_name).eq(placeholder(placeholder_value)))
7205 .unwrap()
7206 .build()
7207 .unwrap();
7208
7209 let params = plan.get_parameter_fields().unwrap();
7211 assert_eq!(params.len(), 1);
7212
7213 let parameter_type = params.clone().get(placeholder_value).unwrap().clone();
7214 assert_eq!(parameter_type, None);
7215 }
7216
7217 #[test]
7218 fn test_join_with_new_exprs() -> Result<()> {
7219 fn create_test_join(
7220 on: Vec<(Expr, Expr)>,
7221 filter: Option<Expr>,
7222 ) -> Result<LogicalPlan> {
7223 let schema = Schema::new(vec![
7224 Field::new("a", DataType::Int32, false),
7225 Field::new("b", DataType::Int32, false),
7226 ]);
7227
7228 let left_schema = DFSchema::try_from_qualified_schema("t1", &schema)?;
7229 let right_schema = DFSchema::try_from_qualified_schema("t2", &schema)?;
7230
7231 Ok(LogicalPlan::Join(Join {
7232 left: Arc::new(
7233 table_scan(Some("t1"), left_schema.as_arrow(), None)?.build()?,
7234 ),
7235 right: Arc::new(
7236 table_scan(Some("t2"), right_schema.as_arrow(), None)?.build()?,
7237 ),
7238 on,
7239 filter,
7240 join_type: JoinType::Inner,
7241 join_constraint: JoinConstraint::On,
7242 schema: Arc::new(left_schema.join(&right_schema)?),
7243 null_equality: NullEquality::NullEqualsNothing,
7244 null_aware: false,
7245 null_aware_value_keys: 0,
7246 }))
7247 }
7248
7249 {
7250 let join = create_test_join(vec![(col("t1.a"), (col("t2.a")))], None)?;
7251 let LogicalPlan::Join(join) = join.with_new_exprs(
7252 join.expressions(),
7253 join.inputs().into_iter().cloned().collect(),
7254 )?
7255 else {
7256 unreachable!()
7257 };
7258 assert_eq!(join.on, vec![(col("t1.a"), (col("t2.a")))]);
7259 assert_eq!(join.filter, None);
7260 }
7261
7262 {
7263 let join = create_test_join(vec![], Some(col("t1.a").gt(col("t2.a"))))?;
7264 let LogicalPlan::Join(join) = join.with_new_exprs(
7265 join.expressions(),
7266 join.inputs().into_iter().cloned().collect(),
7267 )?
7268 else {
7269 unreachable!()
7270 };
7271 assert_eq!(join.on, vec![]);
7272 assert_eq!(join.filter, Some(col("t1.a").gt(col("t2.a"))));
7273 }
7274
7275 {
7276 let join = create_test_join(
7277 vec![(col("t1.a"), (col("t2.a")))],
7278 Some(col("t1.b").gt(col("t2.b"))),
7279 )?;
7280 let LogicalPlan::Join(join) = join.with_new_exprs(
7281 join.expressions(),
7282 join.inputs().into_iter().cloned().collect(),
7283 )?
7284 else {
7285 unreachable!()
7286 };
7287 assert_eq!(join.on, vec![(col("t1.a"), (col("t2.a")))]);
7288 assert_eq!(join.filter, Some(col("t1.b").gt(col("t2.b"))));
7289 }
7290
7291 {
7292 let join = create_test_join(
7293 vec![(col("t1.a"), (col("t2.a"))), (col("t1.b"), (col("t2.b")))],
7294 None,
7295 )?;
7296 let LogicalPlan::Join(join) = join.with_new_exprs(
7297 vec![
7298 binary_expr(col("t1.a"), Operator::Plus, lit(1)),
7299 binary_expr(col("t2.a"), Operator::Plus, lit(2)),
7300 col("t1.b"),
7301 col("t2.b"),
7302 lit(true),
7303 ],
7304 join.inputs().into_iter().cloned().collect(),
7305 )?
7306 else {
7307 unreachable!()
7308 };
7309 assert_eq!(
7310 join.on,
7311 vec![
7312 (
7313 binary_expr(col("t1.a"), Operator::Plus, lit(1)),
7314 binary_expr(col("t2.a"), Operator::Plus, lit(2))
7315 ),
7316 (col("t1.b"), (col("t2.b")))
7317 ]
7318 );
7319 assert_eq!(join.filter, Some(lit(true)));
7320 }
7321
7322 Ok(())
7323 }
7324
7325 #[test]
7326 fn test_join_try_new() -> Result<()> {
7327 let schema = Schema::new(vec![
7328 Field::new("a", DataType::Int32, false),
7329 Field::new("b", DataType::Int32, false),
7330 ]);
7331
7332 let left_scan = table_scan(Some("t1"), &schema, None)?.build()?;
7333
7334 let right_scan = table_scan(Some("t2"), &schema, None)?.build()?;
7335
7336 let join_types = vec![
7337 JoinType::Inner,
7338 JoinType::Left,
7339 JoinType::Right,
7340 JoinType::Full,
7341 JoinType::LeftSemi,
7342 JoinType::LeftAnti,
7343 JoinType::RightSemi,
7344 JoinType::RightAnti,
7345 JoinType::LeftMark,
7346 ];
7347
7348 for join_type in join_types {
7349 let join = Join::try_new(
7350 Arc::new(left_scan.clone()),
7351 Arc::new(right_scan.clone()),
7352 vec![(col("t1.a"), col("t2.a"))],
7353 Some(col("t1.b").gt(col("t2.b"))),
7354 join_type,
7355 JoinConstraint::On,
7356 NullEquality::NullEqualsNothing,
7357 false,
7358 )?;
7359
7360 match join_type {
7361 JoinType::LeftSemi | JoinType::LeftAnti => {
7362 assert_eq!(join.schema.fields().len(), 2);
7363
7364 let fields = join.schema.fields();
7365 assert_eq!(
7366 fields[0].name(),
7367 "a",
7368 "First field should be 'a' from left table"
7369 );
7370 assert_eq!(
7371 fields[1].name(),
7372 "b",
7373 "Second field should be 'b' from left table"
7374 );
7375 }
7376 JoinType::RightSemi | JoinType::RightAnti => {
7377 assert_eq!(join.schema.fields().len(), 2);
7378
7379 let fields = join.schema.fields();
7380 assert_eq!(
7381 fields[0].name(),
7382 "a",
7383 "First field should be 'a' from right table"
7384 );
7385 assert_eq!(
7386 fields[1].name(),
7387 "b",
7388 "Second field should be 'b' from right table"
7389 );
7390 }
7391 JoinType::LeftMark => {
7392 assert_eq!(join.schema.fields().len(), 3);
7393
7394 let fields = join.schema.fields();
7395 assert_eq!(
7396 fields[0].name(),
7397 "a",
7398 "First field should be 'a' from left table"
7399 );
7400 assert_eq!(
7401 fields[1].name(),
7402 "b",
7403 "Second field should be 'b' from left table"
7404 );
7405 assert_eq!(
7406 fields[2].name(),
7407 "mark",
7408 "Third field should be the mark column"
7409 );
7410
7411 assert!(!fields[0].is_nullable());
7412 assert!(!fields[1].is_nullable());
7413 assert!(fields[2].is_nullable());
7416 }
7417 _ => {
7418 assert_eq!(join.schema.fields().len(), 4);
7419
7420 let fields = join.schema.fields();
7421 assert_eq!(
7422 fields[0].name(),
7423 "a",
7424 "First field should be 'a' from left table"
7425 );
7426 assert_eq!(
7427 fields[1].name(),
7428 "b",
7429 "Second field should be 'b' from left table"
7430 );
7431 assert_eq!(
7432 fields[2].name(),
7433 "a",
7434 "Third field should be 'a' from right table"
7435 );
7436 assert_eq!(
7437 fields[3].name(),
7438 "b",
7439 "Fourth field should be 'b' from right table"
7440 );
7441
7442 if join_type == JoinType::Left {
7443 assert!(!fields[0].is_nullable());
7445 assert!(!fields[1].is_nullable());
7446 assert!(fields[2].is_nullable());
7448 assert!(fields[3].is_nullable());
7449 } else if join_type == JoinType::Right {
7450 assert!(fields[0].is_nullable());
7452 assert!(fields[1].is_nullable());
7453 assert!(!fields[2].is_nullable());
7455 assert!(!fields[3].is_nullable());
7456 } else if join_type == JoinType::Full {
7457 assert!(fields[0].is_nullable());
7458 assert!(fields[1].is_nullable());
7459 assert!(fields[2].is_nullable());
7460 assert!(fields[3].is_nullable());
7461 }
7462 }
7463 }
7464
7465 assert_eq!(join.on, vec![(col("t1.a"), col("t2.a"))]);
7466 assert_eq!(join.filter, Some(col("t1.b").gt(col("t2.b"))));
7467 assert_eq!(join.join_type, join_type);
7468 assert_eq!(join.join_constraint, JoinConstraint::On);
7469 assert_eq!(join.null_equality, NullEquality::NullEqualsNothing);
7470 }
7471
7472 Ok(())
7473 }
7474
7475 #[test]
7476 fn test_join_try_new_with_using_constraint_and_overlapping_columns() -> Result<()> {
7477 let left_schema = Schema::new(vec![
7478 Field::new("id", DataType::Int32, false), Field::new("name", DataType::Utf8, false), Field::new("value", DataType::Int32, false), ]);
7482
7483 let right_schema = Schema::new(vec![
7484 Field::new("id", DataType::Int32, false), Field::new("category", DataType::Utf8, false), Field::new("value", DataType::Float64, true), ]);
7488
7489 let left_plan = table_scan(Some("t1"), &left_schema, None)?.build()?;
7490
7491 let right_plan = table_scan(Some("t2"), &right_schema, None)?.build()?;
7492
7493 {
7495 let join = Join::try_new(
7498 Arc::new(left_plan.clone()),
7499 Arc::new(right_plan.clone()),
7500 vec![(col("t1.id"), col("t2.id"))],
7501 None,
7502 JoinType::Inner,
7503 JoinConstraint::Using,
7504 NullEquality::NullEqualsNothing,
7505 false,
7506 )?;
7507
7508 let fields = join.schema.fields();
7509
7510 assert_eq!(fields.len(), 6);
7511
7512 assert_eq!(
7513 fields[0].name(),
7514 "id",
7515 "First field should be 'id' from left table"
7516 );
7517 assert_eq!(
7518 fields[1].name(),
7519 "name",
7520 "Second field should be 'name' from left table"
7521 );
7522 assert_eq!(
7523 fields[2].name(),
7524 "value",
7525 "Third field should be 'value' from left table"
7526 );
7527 assert_eq!(
7528 fields[3].name(),
7529 "id",
7530 "Fourth field should be 'id' from right table"
7531 );
7532 assert_eq!(
7533 fields[4].name(),
7534 "category",
7535 "Fifth field should be 'category' from right table"
7536 );
7537 assert_eq!(
7538 fields[5].name(),
7539 "value",
7540 "Sixth field should be 'value' from right table"
7541 );
7542
7543 assert_eq!(join.join_constraint, JoinConstraint::Using);
7544 }
7545
7546 {
7548 let join = Join::try_new(
7550 Arc::new(left_plan.clone()),
7551 Arc::new(right_plan.clone()),
7552 vec![(col("t1.id"), col("t2.id"))], Some(col("t1.value").lt(col("t2.value"))), JoinType::Inner,
7555 JoinConstraint::On,
7556 NullEquality::NullEqualsNothing,
7557 false,
7558 )?;
7559
7560 let fields = join.schema.fields();
7561 assert_eq!(fields.len(), 6);
7562
7563 assert_eq!(
7564 fields[0].name(),
7565 "id",
7566 "First field should be 'id' from left table"
7567 );
7568 assert_eq!(
7569 fields[1].name(),
7570 "name",
7571 "Second field should be 'name' from left table"
7572 );
7573 assert_eq!(
7574 fields[2].name(),
7575 "value",
7576 "Third field should be 'value' from left table"
7577 );
7578 assert_eq!(
7579 fields[3].name(),
7580 "id",
7581 "Fourth field should be 'id' from right table"
7582 );
7583 assert_eq!(
7584 fields[4].name(),
7585 "category",
7586 "Fifth field should be 'category' from right table"
7587 );
7588 assert_eq!(
7589 fields[5].name(),
7590 "value",
7591 "Sixth field should be 'value' from right table"
7592 );
7593
7594 assert_eq!(join.filter, Some(col("t1.value").lt(col("t2.value"))));
7595 }
7596
7597 {
7599 let join = Join::try_new(
7600 Arc::new(left_plan.clone()),
7601 Arc::new(right_plan.clone()),
7602 vec![(col("t1.id"), col("t2.id"))],
7603 None,
7604 JoinType::Inner,
7605 JoinConstraint::On,
7606 NullEquality::NullEqualsNull,
7607 false,
7608 )?;
7609
7610 assert_eq!(join.null_equality, NullEquality::NullEqualsNull);
7611 }
7612
7613 Ok(())
7614 }
7615
7616 #[test]
7617 fn test_asof_using_preserves_qualified_keys() -> Result<()> {
7618 let schema = Schema::new(vec![
7619 Field::new("id", DataType::Int32, false),
7620 Field::new("ts", DataType::Int64, false),
7621 ]);
7622 let left = Arc::new(table_scan(Some("t1"), &schema, None)?.build()?);
7623 let right = Arc::new(table_scan(Some("t2"), &schema, None)?.build()?);
7624 let join = AsOfJoin::try_new(
7625 left,
7626 right,
7627 vec![(col("t1.id"), col("t2.id"))],
7628 AsOfMatch::new(col("t1.ts"), Operator::GtEq, col("t2.ts")),
7629 JoinConstraint::Using,
7630 )?;
7631
7632 assert_eq!(join.schema.fields().len(), 4);
7633 assert_eq!(
7634 join.schema
7635 .index_of_column(&Column::from_qualified_name("t2.id"))?,
7636 2
7637 );
7638 assert!(join.schema.field(2).is_nullable());
7639 Ok(())
7640 }
7641
7642 #[test]
7643 fn test_join_try_new_schema_validation() -> Result<()> {
7644 let left_schema = Schema::new(vec![
7645 Field::new("id", DataType::Int32, false),
7646 Field::new("name", DataType::Utf8, false),
7647 Field::new("value", DataType::Float64, true),
7648 ]);
7649
7650 let right_schema = Schema::new(vec![
7651 Field::new("id", DataType::Int32, false),
7652 Field::new("category", DataType::Utf8, true),
7653 Field::new("code", DataType::Int16, false),
7654 ]);
7655
7656 let left_plan = table_scan(Some("t1"), &left_schema, None)?.build()?;
7657
7658 let right_plan = table_scan(Some("t2"), &right_schema, None)?.build()?;
7659
7660 let join_types = vec![
7661 JoinType::Inner,
7662 JoinType::Left,
7663 JoinType::Right,
7664 JoinType::Full,
7665 ];
7666
7667 for join_type in join_types {
7668 let join = Join::try_new(
7669 Arc::new(left_plan.clone()),
7670 Arc::new(right_plan.clone()),
7671 vec![(col("t1.id"), col("t2.id"))],
7672 Some(col("t1.value").gt(lit(5.0))),
7673 join_type,
7674 JoinConstraint::On,
7675 NullEquality::NullEqualsNothing,
7676 false,
7677 )?;
7678
7679 let fields = join.schema.fields();
7680 assert_eq!(fields.len(), 6, "Expected 6 fields for {join_type} join");
7681
7682 for (i, field) in fields.iter().enumerate() {
7683 let expected_nullable = match (i, &join_type) {
7684 (0, JoinType::Right | JoinType::Full) => true, (1, JoinType::Right | JoinType::Full) => true, (2, _) => true, (3, JoinType::Left | JoinType::Full) => true, (4, _) => true, (5, JoinType::Left | JoinType::Full) => true, _ => false,
7695 };
7696
7697 assert_eq!(
7698 field.is_nullable(),
7699 expected_nullable,
7700 "Field {} ({}) nullability incorrect for {:?} join",
7701 i,
7702 field.name(),
7703 join_type
7704 );
7705 }
7706 }
7707
7708 let using_join = Join::try_new(
7709 Arc::new(left_plan.clone()),
7710 Arc::new(right_plan.clone()),
7711 vec![(col("t1.id"), col("t2.id"))],
7712 None,
7713 JoinType::Inner,
7714 JoinConstraint::Using,
7715 NullEquality::NullEqualsNothing,
7716 false,
7717 )?;
7718
7719 assert_eq!(
7720 using_join.schema.fields().len(),
7721 6,
7722 "USING join should have all fields"
7723 );
7724 assert_eq!(using_join.join_constraint, JoinConstraint::Using);
7725
7726 Ok(())
7727 }
7728
7729 #[test]
7730 fn test_unnest_with_new_exprs_accepts_expressions() -> Result<()> {
7731 use crate::LogicalPlanBuilder;
7732 use arrow::datatypes::{DataType, Field, Schema};
7733
7734 let schema = Schema::new(vec![
7735 Field::new("list_col", DataType::new_list(DataType::Int32, true), true),
7736 Field::new("other_col", DataType::Int32, true),
7737 ]);
7738 let plan = table_scan(Some("t"), &schema, None)?.build()?;
7739 let unnest_plan = LogicalPlanBuilder::from(plan)
7740 .unnest_column("list_col")?
7741 .build()?;
7742
7743 let exprs = unnest_plan.expressions();
7744 assert!(!exprs.is_empty(), "Unnest should expose exec_columns");
7745 assert_eq!(exprs.len(), 1);
7746 assert!(matches!(&exprs[0], Expr::Column(c) if c.name == "list_col"));
7747
7748 let inputs: Vec<LogicalPlan> =
7749 unnest_plan.inputs().into_iter().cloned().collect();
7750 let rebuilt = unnest_plan.with_new_exprs(exprs, inputs)?;
7751 assert_eq!(rebuilt.schema(), unnest_plan.schema());
7752
7753 Ok(())
7754 }
7755
7756 #[test]
7757 fn test_unnest_with_new_exprs_empty_preserves_columns() -> Result<()> {
7758 use crate::LogicalPlanBuilder;
7759 use arrow::datatypes::{DataType, Field, Schema};
7760
7761 let schema = Schema::new(vec![
7762 Field::new("list_col", DataType::new_list(DataType::Int32, true), true),
7763 Field::new("other_col", DataType::Int32, true),
7764 ]);
7765 let plan = table_scan(Some("t"), &schema, None)?.build()?;
7766 let unnest_plan = LogicalPlanBuilder::from(plan)
7767 .unnest_column("list_col")?
7768 .build()?;
7769
7770 let inputs: Vec<LogicalPlan> =
7771 unnest_plan.inputs().into_iter().cloned().collect();
7772 let rebuilt = unnest_plan.with_new_exprs(vec![], inputs)?;
7773 assert_eq!(rebuilt.schema(), unnest_plan.schema());
7774
7775 Ok(())
7776 }
7777
7778 #[test]
7779 fn union_infers_types_without_rewriting_inputs() -> Result<()> {
7780 let input = |data_type, nullable, source: &str| {
7781 table_scan(
7782 Some(source),
7783 &Schema::new(vec![
7784 Field::new("x", data_type, nullable)
7785 .with_metadata(Metadata::new().with("source", source)),
7786 ]),
7787 None,
7788 )?
7789 .build()
7790 .map(Arc::new)
7791 };
7792 let left = input(DataType::Int16, false, "left")?;
7793 let right = input(DataType::Int64, true, "right")?;
7794 let inputs = vec![Arc::clone(&left), Arc::clone(&right)];
7795 let union = Union::try_new_with_loose_types(inputs.clone())?;
7796 assert_eq!(union.inputs, inputs);
7797 assert_eq!(union.schema.field(0).name(), "x");
7798 assert_eq!(union.schema.field(0).data_type(), &DataType::Int64);
7799 assert!(union.schema.field(0).is_nullable());
7800 assert_eq!(
7801 union
7802 .schema
7803 .field(0)
7804 .metadata()
7805 .get("source")
7806 .map(String::as_str),
7807 Some("right")
7808 );
7809 assert!(Union::try_new(inputs.clone()).is_err());
7810 assert!(Union::try_new_with_loose_types(vec![Arc::clone(&left)]).is_err());
7811
7812 let incompatible = input(DataType::Boolean, false, "third")?;
7815 let inputs = vec![left, right, incompatible];
7816 for union in [
7817 Union::try_new_with_loose_types(inputs.clone())?,
7818 Union::try_new_by_name(inputs)?,
7819 ] {
7820 assert_eq!(union.schema.field(0).data_type(), &DataType::Int16);
7821 }
7822 Ok(())
7823 }
7824}