Apache DataFusion SQL Query Engine
Move ordering equivalence, and output ordering for joins to util functions (#7167)
Mustafa Akur7af25decf050
diff --git a/datafusion/core/src/physical_optimizer/sort_pushdown.rs b/datafusion/core/src/physical_optimizer/sort_pushdown.rsindex 108f753800..eb7fb49ac9 100644--- a/datafusion/core/src/physical_optimizer/sort_pushdown.rs+++ b/datafusion/core/src/physical_optimizer/sort_pushdown.rs@@ -14,14 +14,18 @@// KIND, either express or implied. See the License for the// specific language governing permissions and limitations// under the License.++use std::sync::Arc;+use crate::physical_optimizer::utils::{add_sort_above, is_limit, is_union, is_window};use crate::physical_plan::filter::FilterExec;-use crate::physical_plan::joins::utils::JoinSide;+use crate::physical_plan::joins::utils::{calculate_join_output_ordering, JoinSide};use crate::physical_plan::joins::{HashJoinExec, SortMergeJoinExec};use crate::physical_plan::projection::ProjectionExec;use crate::physical_plan::repartition::RepartitionExec;use crate::physical_plan::sorts::sort::SortExec;use crate::physical_plan::{with_new_children_if_necessary, ExecutionPlan};+use datafusion_common::tree_node::{Transformed, TreeNode, VisitRecursion};use datafusion_common::{DataFusionError, Result};use datafusion_expr::JoinType;@@ -30,9 +34,8 @@ use datafusion_physical_expr::utils::{ordering_satisfy_requirement, requirements_compatible,};use datafusion_physical_expr::{PhysicalSortExpr, PhysicalSortRequirement};+use itertools::izip;-use std::ops::Deref;-use std::sync::Arc;/// This is a "data class" we use within the [`EnforceSorting`] rule to push/// down [`SortExec`] in the plan. In some cases, we can reduce the total@@ -223,31 +226,24 @@ fn pushdown_requirement_to_children(let expr_source_side =expr_source_sides(&parent_required_expr, smj.join_type, left_columns_len);match expr_source_side {- Some(JoinSide::Left) if maintains_input_order[0] => {+ Some(JoinSide::Left) => try_pushdown_requirements_to_join(+ smj,+ parent_required,+ parent_required_expr,+ JoinSide::Left,+ ),+ Some(JoinSide::Right) => {+ let right_offset =+ smj.schema().fields.len() - smj.right.schema().fields.len();+ let new_right_required =+ shift_right_required(parent_required.ok_or_else(err)?, right_offset)?;+ let new_right_required_expr = PhysicalSortRequirement::to_sort_exprs(+ new_right_required.iter().cloned(),+ );try_pushdown_requirements_to_join(- plan,+ smj,parent_required,- parent_required_expr,- JoinSide::Left,- )- }- Some(JoinSide::Right) if maintains_input_order[1] => {- let new_right_required = match smj.join_type {- JoinType::Inner | JoinType::Right => shift_right_required(- parent_required.ok_or_else(err)?,- left_columns_len,- )?,- JoinType::RightSemi | JoinType::RightAnti => {- parent_required.ok_or_else(err)?.to_vec()- }- _ => Err(DataFusionError::Plan(- "Unexpected SortMergeJoin type here".to_string(),- ))?,- };- try_pushdown_requirements_to_join(- plan,- Some(new_right_required.deref()),- parent_required_expr,+ new_right_required_expr,JoinSide::Right,)}@@ -316,39 +312,45 @@ fn determine_children_requirement(RequirementsCompatibility::NonCompatible}}-fn try_pushdown_requirements_to_join(- plan: &Arc<dyn ExecutionPlan>,+ smj: &SortMergeJoinExec,parent_required: Option<&[PhysicalSortRequirement]>,sort_expr: Vec<PhysicalSortExpr>,push_side: JoinSide,) -> Result<Option<Vec<Option<Vec<PhysicalSortRequirement>>>>> {- let child_idx = match push_side {- JoinSide::Left => 0,- JoinSide::Right => 1,+ let left_ordering = smj.left.output_ordering().unwrap_or(&[]);+ let right_ordering = smj.right.output_ordering().unwrap_or(&[]);+ let (new_left_ordering, new_right_ordering) = match push_side {+ JoinSide::Left => (sort_expr.as_slice(), right_ordering),+ JoinSide::Right => (left_ordering, sort_expr.as_slice()),};- let required_input_ordering = plan.required_input_ordering();- let request_child = required_input_ordering[child_idx].as_deref();- let child_plan = plan.children()[child_idx].clone();- match determine_children_requirement(parent_required, request_child, child_plan) {- RequirementsCompatibility::Satisfy => Ok(None),- RequirementsCompatibility::Compatible(adjusted) => {- let new_adjusted = match push_side {- JoinSide::Left => {- vec![adjusted, required_input_ordering[1].clone()]- }- JoinSide::Right => {- vec![required_input_ordering[0].clone(), adjusted]- }- };- Ok(Some(new_adjusted))- }- RequirementsCompatibility::NonCompatible => {- // Can not push down, add new SortExec- add_sort_above(&mut plan.clone(), sort_expr, None)?;- Ok(None)+ let new_output_ordering = calculate_join_output_ordering(+ new_left_ordering,+ new_right_ordering,+ smj.join_type,+ &smj.on,+ smj.left.schema().fields.len(),+ &smj.maintains_input_order(),+ Some(SortMergeJoinExec::probe_side(&smj.join_type)),+ )?;+ Ok(ordering_satisfy_requirement(+ new_output_ordering.as_deref(),+ parent_required,+ || smj.equivalence_properties(),+ || smj.ordering_equivalence_properties(),+ )+ .then(|| {+ let required_input_ordering = smj.required_input_ordering();+ let new_req = Some(PhysicalSortRequirement::from_sort_exprs(&sort_expr));+ match push_side {+ JoinSide::Left => {+ vec![new_req, required_input_ordering[1].clone()]+ }+ JoinSide::Right => {+ vec![required_input_ordering[0].clone(), new_req]+ }}- }+ }))}fn expr_source_sides(diff --git a/datafusion/core/src/physical_plan/joins/hash_join.rs b/datafusion/core/src/physical_plan/joins/hash_join.rsindex ce1d6dbcc0..6159a64be3 100644--- a/datafusion/core/src/physical_plan/joins/hash_join.rs+++ b/datafusion/core/src/physical_plan/joins/hash_join.rs@@ -25,10 +25,9 @@ use std::task::Poll;use std::{any::Any, usize, vec};use crate::physical_plan::joins::utils::{- add_offset_to_ordering_equivalence_classes, adjust_indices_by_join_type,- apply_join_filter_to_indices, build_batch_from_indices,- calculate_hash_join_output_order, get_final_indices_from_bit_map,- need_produce_result_in_final, JoinSide,+ adjust_indices_by_join_type, apply_join_filter_to_indices, build_batch_from_indices,+ calculate_join_output_ordering, combine_join_ordering_equivalence_properties,+ get_final_indices_from_bit_map, need_produce_result_in_final, JoinSide,};use crate::physical_plan::DisplayAs;use crate::physical_plan::{@@ -151,11 +150,14 @@ impl HashJoinExec {let random_state = RandomState::with_seeds(0, 0, 0, 0);- let output_order = calculate_hash_join_output_order(- join_type,- left.output_ordering(),- right.output_ordering(),- left.schema().fields().len(),+ let output_order = calculate_join_output_ordering(+ left.output_ordering().unwrap_or(&[]),+ right.output_ordering().unwrap_or(&[]),+ *join_type,+ &on,+ left_schema.fields.len(),+ &Self::maintains_input_order(*join_type),+ Some(Self::probe_side()),)?;Ok(HashJoinExec {@@ -209,6 +211,23 @@ impl HashJoinExec {pub fn null_equals_null(&self) -> bool {self.null_equals_null}++ /// Calculate order preservation flags for this hash join.+ fn maintains_input_order(join_type: JoinType) -> Vec<bool> {+ vec![+ false,+ matches!(+ join_type,+ JoinType::Inner | JoinType::RightAnti | JoinType::RightSemi+ ),+ ]+ }++ /// Get probe side information for the hash join.+ pub fn probe_side() -> JoinSide {+ // In current implementation right side is always probe side.+ JoinSide::Right+ }}impl DisplayAs for HashJoinExec {@@ -355,13 +374,7 @@ impl ExecutionPlan for HashJoinExec {// are processed sequentially in the probe phase, and unmatched rows are directly output// as results, these results tend to retain the order of the probe side table.fn maintains_input_order(&self) -> Vec<bool> {- vec![- false,- matches!(- self.join_type,- JoinType::Inner | JoinType::RightAnti | JoinType::RightSemi- ),- ]+ Self::maintains_input_order(self.join_type)}fn equivalence_properties(&self) -> EquivalenceProperties {@@ -377,31 +390,16 @@ impl ExecutionPlan for HashJoinExec {}fn ordering_equivalence_properties(&self) -> OrderingEquivalenceProperties {- let mut new_properties = OrderingEquivalenceProperties::new(self.schema());- let left_columns_len = self.left.schema().fields.len();- let right_oeq_properties = self.right.ordering_equivalence_properties();- match self.join_type {- JoinType::RightAnti | JoinType::RightSemi => {- // For `RightAnti` and `RightSemi` joins, the right table schema remains valid.- // Hence, its ordering equivalence properties can be used as is.- new_properties.extend(right_oeq_properties.classes().iter().cloned());- }- JoinType::Inner => {- // For `Inner` joins, the right table schema is no longer valid.- // Size of the left table is added as an offset to the right table- // columns when constructing the join output schema.- let updated_right_classes = add_offset_to_ordering_equivalence_classes(- right_oeq_properties.classes(),- left_columns_len,- )- .unwrap();- new_properties.extend(updated_right_classes);- }- // In other cases, we cannot propagate ordering equivalences as- // the output ordering is not preserved.- _ => {}- }- new_properties+ combine_join_ordering_equivalence_properties(+ &self.join_type,+ &self.left,+ &self.right,+ self.schema(),+ &self.maintains_input_order(),+ Some(Self::probe_side()),+ self.equivalence_properties(),+ )+ .unwrap()}fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {diff --git a/datafusion/core/src/physical_plan/joins/sort_merge_join.rs b/datafusion/core/src/physical_plan/joins/sort_merge_join.rsindex 9b8e9e85cd..4b34ecbcc2 100644--- a/datafusion/core/src/physical_plan/joins/sort_merge_join.rs+++ b/datafusion/core/src/physical_plan/joins/sort_merge_join.rs@@ -33,9 +33,9 @@ use std::task::{Context, Poll};use crate::physical_plan::expressions::Column;use crate::physical_plan::expressions::PhysicalSortExpr;use crate::physical_plan::joins::utils::{- add_offset_to_lex_ordering, add_offset_to_ordering_equivalence_classes,- build_join_schema, check_join_is_valid, combine_join_equivalence_properties,- estimate_join_statistics, partitioned_join_output_partitioning, JoinOn,+ build_join_schema, calculate_join_output_ordering, check_join_is_valid,+ combine_join_equivalence_properties, combine_join_ordering_equivalence_properties,+ estimate_join_statistics, partitioned_join_output_partitioning, JoinOn, JoinSide,};use crate::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricBuilder, MetricsSet};use crate::physical_plan::{@@ -52,11 +52,9 @@ use arrow::record_batch::RecordBatch;use datafusion_common::{DataFusionError, JoinType, Result};use datafusion_execution::memory_pool::{MemoryConsumer, MemoryReservation};use datafusion_execution::TaskContext;-use datafusion_physical_expr::utils::normalize_sort_exprs;use datafusion_physical_expr::{OrderingEquivalenceProperties, PhysicalSortRequirement};use futures::{Stream, StreamExt};-use itertools::Itertools;/// join execution plan executes partitions in parallel and combines them into a set of/// partitions.@@ -86,38 +84,6 @@ pub struct SortMergeJoinExec {pub(crate) null_equals_null: bool,}-/// Replaces the right column (first index in the `on_column` tuple) with-/// the left column (zeroth index in the tuple) inside `right_ordering`.-fn replace_on_columns_of_right_ordering(- on_columns: &[(Column, Column)],- right_ordering: &mut [PhysicalSortExpr],- left_columns_len: usize,-) {- for (left_col, right_col) in on_columns {- let right_col =- Column::new(right_col.name(), right_col.index() + left_columns_len);- for item in right_ordering.iter_mut() {- if let Some(col) = item.expr.as_any().downcast_ref::<Column>() {- if right_col.eq(col) {- item.expr = Arc::new(left_col.clone()) as _;- }- }- }- }-}--/// Merge left and right sort expressions, checking for duplicates.-fn merge_vectors(- left: &[PhysicalSortExpr],- right: &[PhysicalSortExpr],-) -> Vec<PhysicalSortExpr> {- left.iter()- .cloned()- .chain(right.iter().cloned())- .unique()- .collect()-}-impl SortMergeJoinExec {/// Tries to create a new [SortMergeJoinExec]./// The inputs are sorted using `sort_options` are applied to the columns in the `on`@@ -165,43 +131,15 @@ impl SortMergeJoinExec {}).unzip();- let output_ordering = match join_type {- JoinType::Inner => {- match (left.output_ordering(), right.output_ordering()) {- // If both sides have orderings, ordering of the right hand side- // can be appended to the left side ordering for inner joins.- (Some(left_ordering), Some(right_ordering)) => {- let left_columns_len = left.schema().fields.len();- let mut right_ordering =- add_offset_to_lex_ordering(right_ordering, left_columns_len)?;- replace_on_columns_of_right_ordering(- &on,- &mut right_ordering,- left_columns_len,- );- Some(merge_vectors(left_ordering, &right_ordering))- }- (Some(left_ordering), _) => Some(left_ordering.to_vec()),- _ => None,- }- }- JoinType::Left | JoinType::LeftSemi | JoinType::LeftAnti => {- left.output_ordering().map(|sort_exprs| sort_exprs.to_vec())- }- JoinType::RightSemi | JoinType::RightAnti => right- .output_ordering()- .map(|sort_exprs| sort_exprs.to_vec()),- JoinType::Right => {- let left_columns_len = left.schema().fields.len();- right- .output_ordering()- .map(|sort_exprs| {- add_offset_to_lex_ordering(sort_exprs, left_columns_len)- })- .map_or(Ok(None), |v| v.map(Some))?- }- JoinType::Full => None,- };+ let output_ordering = calculate_join_output_ordering(+ left.output_ordering().unwrap_or(&[]),+ right.output_ordering().unwrap_or(&[]),+ join_type,+ &on,+ left_schema.fields.len(),+ &Self::maintains_input_order(join_type),+ Some(Self::probe_side(&join_type)),+ )?;let schema =Arc::new(build_join_schema(&left_schema, &right_schema, &join_type).0);@@ -221,6 +159,35 @@ impl SortMergeJoinExec {})}+ /// Get probe side (e.g streaming side) information for this sort merge join.+ /// In current implementation, probe side is determined according to join type.+ pub fn probe_side(join_type: &JoinType) -> JoinSide {+ // When output schema contains only the right side, probe side is right.+ // Otherwise probe side is the left side.+ match join_type {+ JoinType::Right | JoinType::RightSemi | JoinType::RightAnti => {+ JoinSide::Right+ }+ JoinType::Inner+ | JoinType::Left+ | JoinType::Full+ | JoinType::LeftAnti+ | JoinType::LeftSemi => JoinSide::Left,+ }+ }++ /// Calculate order preservation flags for this sort merge join.+ fn maintains_input_order(join_type: JoinType) -> Vec<bool> {+ match join_type {+ JoinType::Inner => vec![true, false],+ JoinType::Left | JoinType::LeftSemi | JoinType::LeftAnti => vec![true, false],+ JoinType::Right | JoinType::RightSemi | JoinType::RightAnti => {+ vec![false, true]+ }+ _ => vec![false, false],+ }+ }+/// Set of common columns used to join onpub fn on(&self) -> &[(Column, Column)] {&self.on@@ -299,14 +266,7 @@ impl ExecutionPlan for SortMergeJoinExec {}fn maintains_input_order(&self) -> Vec<bool> {- match self.join_type {- JoinType::Inner => vec![true, true],- JoinType::Left | JoinType::LeftSemi | JoinType::LeftAnti => vec![true, false],- JoinType::Right | JoinType::RightSemi | JoinType::RightAnti => {- vec![false, true]- }- _ => vec![false, false],- }+ Self::maintains_input_order(self.join_type)}fn equivalence_properties(&self) -> EquivalenceProperties {@@ -322,62 +282,16 @@ impl ExecutionPlan for SortMergeJoinExec {}fn ordering_equivalence_properties(&self) -> OrderingEquivalenceProperties {- let mut new_properties = OrderingEquivalenceProperties::new(self.schema());- let left_columns_len = self.left.schema().fields.len();- let left_oeq_properties = self.left.ordering_equivalence_properties();- let right_oeq_properties = self.right.ordering_equivalence_properties();- match self.join_type {- JoinType::Inner => {- // Since left side is the stream side for this `SortMergeJoin` implementation,- // global ordering of the left table is preserved at the output. Hence, left- // side ordering equivalences are still valid.- new_properties.extend(left_oeq_properties.classes().iter().cloned());- if let Some(output_ordering) = &self.output_ordering {- // Update right table ordering equivalence expression indices; i.e.- // add left table size as an offset.- let updated_right_oeq_classes =- add_offset_to_ordering_equivalence_classes(- right_oeq_properties.classes(),- left_columns_len,- )- .unwrap();- let left_output_ordering = self.left.output_ordering().unwrap_or(&[]);- // Right side ordering equivalence properties should be prepended with- // those of the left side while constructing output ordering equivalence- // properties for `SortMergeJoin`. As an example;- //- // If the right table ordering equivalences contain `b ASC`, and the output- // ordering of the left table is `a ASC`, then the ordering equivalence `b ASC`- // for the right table should be converted to `a ASC, b ASC` before it is added- // to the ordering equivalences of `SortMergeJoinExec`.- for oeq_class in updated_right_oeq_classes {- for ordering in oeq_class.others() {- // Entries inside ordering equivalence should be normalized before insertion.- let normalized_ordering = normalize_sort_exprs(- ordering,- self.equivalence_properties().classes(),- &[],- );- let new_oeq_ordering =- merge_vectors(left_output_ordering, &normalized_ordering);- new_properties.add_equal_conditions((- output_ordering,- &new_oeq_ordering,- ));- }- }- }- }- JoinType::Left | JoinType::LeftSemi | JoinType::LeftAnti => {- new_properties.extend(left_oeq_properties.classes().iter().cloned());- }- JoinType::Right | JoinType::RightSemi | JoinType::RightAnti => {- new_properties.extend(right_oeq_properties.classes().iter().cloned());- }- // All ordering equivalences from left and/or right sides are invalidated.- _ => {}- }- new_properties+ combine_join_ordering_equivalence_properties(+ &self.join_type,+ &self.left,+ &self.right,+ self.schema(),+ &self.maintains_input_order(),+ Some(Self::probe_side(&self.join_type)),+ self.equivalence_properties(),+ )+ .unwrap()}fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {@@ -416,25 +330,13 @@ impl ExecutionPlan for SortMergeJoinExec {consider using RepartitionExec",)));}-- let (streamed, buffered, on_streamed, on_buffered) = match self.join_type {- JoinType::Inner- | JoinType::Left- | JoinType::Full- | JoinType::LeftAnti- | JoinType::LeftSemi => (- self.left.clone(),- self.right.clone(),- self.on.iter().map(|on| on.0.clone()).collect(),- self.on.iter().map(|on| on.1.clone()).collect(),- ),- JoinType::Right | JoinType::RightSemi | JoinType::RightAnti => (- self.right.clone(),- self.left.clone(),- self.on.iter().map(|on| on.1.clone()).collect(),- self.on.iter().map(|on| on.0.clone()).collect(),- ),- };+ let (on_left, on_right) = self.on.iter().cloned().unzip();+ let (streamed, buffered, on_streamed, on_buffered) =+ if SortMergeJoinExec::probe_side(&self.join_type) == JoinSide::Left {+ (self.left.clone(), self.right.clone(), on_left, on_right)+ } else {+ (self.right.clone(), self.left.clone(), on_right, on_left)+ };// execute children planslet streamed = streamed.execute(partition, context.clone())?;diff --git a/datafusion/core/src/physical_plan/joins/utils.rs b/datafusion/core/src/physical_plan/joins/utils.rsindex ea9c11a3ed..3366ee8ffa 100644--- a/datafusion/core/src/physical_plan/joins/utils.rs+++ b/datafusion/core/src/physical_plan/joins/utils.rs@@ -43,12 +43,15 @@ use datafusion_common::tree_node::{Transformed, TreeNode};use datafusion_common::{DataFusionError, JoinType, Result, ScalarValue, SharedResult};use datafusion_physical_expr::expressions::Column;use datafusion_physical_expr::{- EquivalentClass, LexOrdering, LexOrderingRef, OrderingEquivalentClass, PhysicalExpr,- PhysicalSortExpr,+ EquivalentClass, LexOrdering, LexOrderingRef, OrderingEquivalenceProperties,+ OrderingEquivalentClass, PhysicalExpr, PhysicalSortExpr,};+use datafusion_physical_expr::utils::normalize_sort_exprs;+use futures::future::{BoxFuture, Shared};use futures::{ready, FutureExt};+use itertools::Itertools;use parking_lot::Mutex;/// The on clause of the join, as vector of (left, right) columns.@@ -147,64 +150,93 @@ pub fn adjust_right_output_partitioning(}}-fn adjust_right_order(- right_order: &[PhysicalSortExpr],+/// Replaces the right column (first index in the `on_column` tuple) with+/// the left column (zeroth index in the tuple) inside `right_ordering`.+fn replace_on_columns_of_right_ordering(+ on_columns: &[(Column, Column)],+ right_ordering: &mut [PhysicalSortExpr],left_columns_len: usize,-) -> Result<Vec<PhysicalSortExpr>> {- right_order- .iter()- .map(|sort_expr| {- let expr = sort_expr.expr.clone();- let adjusted = expr.transform_up(&|expr| {- Ok(- if let Some(column) = expr.as_any().downcast_ref::<Column>() {- let new_col =- Column::new(column.name(), column.index() + left_columns_len);- Transformed::Yes(Arc::new(new_col))- } else {- Transformed::No(expr)- },- )- })?;- Ok(PhysicalSortExpr {- expr: adjusted,- options: sort_expr.options,- })- })- .collect::<Result<Vec<_>>>()-}--/// Calculate the output order for hash join.-pub fn calculate_hash_join_output_order(- join_type: &JoinType,- maybe_left_order: Option<&[PhysicalSortExpr]>,- maybe_right_order: Option<&[PhysicalSortExpr]>,- left_len: usize,-) -> Result<Option<Vec<PhysicalSortExpr>>> {- match maybe_right_order {- Some(right_order) => {- let result = match join_type {- JoinType::Inner => {- // We modify the indices of the right order columns because their- // columns are appended to the right side of the left schema.- let mut adjusted_right_order =- adjust_right_order(right_order, left_len)?;- if let Some(left_order) = maybe_left_order {- adjusted_right_order.extend_from_slice(left_order);- }- Some(adjusted_right_order)+) {+ for (left_col, right_col) in on_columns {+ let right_col =+ Column::new(right_col.name(), right_col.index() + left_columns_len);+ for item in right_ordering.iter_mut() {+ if let Some(col) = item.expr.as_any().downcast_ref::<Column>() {+ if right_col.eq(col) {+ item.expr = Arc::new(left_col.clone()) as _;}- JoinType::RightAnti | JoinType::RightSemi => Some(right_order.to_vec()),- _ => None,- };-- Ok(result)+ }}- None => Ok(None),}}-/// Combine the Equivalence Properties for Join Node+/// Calculate the output ordering of a given join operation.+pub fn calculate_join_output_ordering(+ left_ordering: LexOrderingRef,+ right_ordering: LexOrderingRef,+ join_type: JoinType,+ on_columns: &[(Column, Column)],+ left_columns_len: usize,+ maintains_input_order: &[bool],+ probe_side: Option<JoinSide>,+) -> Result<Option<LexOrdering>> {+ // All joins have 2 children:+ assert_eq!(maintains_input_order.len(), 2);+ let left_maintains = maintains_input_order[0];+ let right_maintains = maintains_input_order[1];+ let (mut right_ordering, on_columns) = match join_type {+ // In the case below, right ordering should be offseted with the left+ // side length, since we append the right table to the left table.+ JoinType::Inner | JoinType::Left | JoinType::Right | JoinType::Full => {+ let updated_on_columns = on_columns+ .iter()+ .map(|(left, right)| {+ (+ left.clone(),+ Column::new(right.name(), right.index() + left_columns_len),+ )+ })+ .collect::<Vec<_>>();+ let updated_right_ordering =+ add_offset_to_lex_ordering(right_ordering, left_columns_len)?;+ (updated_right_ordering, updated_on_columns)+ }+ _ => (right_ordering.to_vec(), on_columns.to_vec()),+ };+ let output_ordering = match (left_maintains, right_maintains) {+ (true, true) => {+ return Err(DataFusionError::Execution(+ "Cannot maintain ordering of both sides".to_string(),+ ))+ }+ (true, false) => {+ // Special case, we can prefix ordering of right side with the ordering of left side.+ if join_type == JoinType::Inner && probe_side == Some(JoinSide::Left) {+ replace_on_columns_of_right_ordering(+ &on_columns,+ &mut right_ordering,+ left_columns_len,+ );+ merge_vectors(left_ordering, &right_ordering)+ } else {+ left_ordering.to_vec()+ }+ }+ (false, true) => {+ // Special case, we can prefix ordering of left side with the ordering of right side.+ if join_type == JoinType::Inner && probe_side == Some(JoinSide::Right) {+ merge_vectors(&right_ordering, left_ordering)+ } else {+ right_ordering+ }+ }+ // Doesn't maintain ordering, output ordering is None.+ (false, false) => return Ok(None),+ };+ Ok((!output_ordering.is_empty()).then_some(output_ordering))+}++/// Combine equivalence properties of the given join inputs.pub fn combine_join_equivalence_properties(join_type: JoinType,left_properties: EquivalenceProperties,@@ -256,7 +288,7 @@ pub fn combine_join_equivalence_properties(new_properties}-/// Calculate the Equivalence Properties for CrossJoin Node+/// Calculate equivalence properties for the given cross join operation.pub fn cross_join_equivalence_properties(left_properties: EquivalenceProperties,right_properties: EquivalenceProperties,@@ -283,6 +315,155 @@ pub fn cross_join_equivalence_properties(new_properties}+/// Update right table ordering equivalences so that they point to valid indices+/// at the output of the join schema. To do so, we increment column indices by left table size+/// when join schema consist of combination of left and right schema (Inner, Left, Full, Right joins).+fn get_updated_right_ordering_equivalence_properties(+ join_type: &JoinType,+ right_oeq_classes: &[OrderingEquivalentClass],+ left_columns_len: usize,+) -> Result<Vec<OrderingEquivalentClass>> {+ match join_type {+ // In these modes, indices of the right schema should be offset by+ // the left table size.+ JoinType::Inner | JoinType::Left | JoinType::Full | JoinType::Right => {+ add_offset_to_ordering_equivalence_classes(+ right_oeq_classes,+ left_columns_len,+ )+ }+ _ => Ok(right_oeq_classes.to_vec()),+ }+}++/// Merge left and right sort expressions, checking for duplicates.+fn merge_vectors(+ left: &[PhysicalSortExpr],+ right: &[PhysicalSortExpr],+) -> Vec<PhysicalSortExpr> {+ left.iter()+ .cloned()+ .chain(right.iter().cloned())+ .unique()+ .collect()+}++/// Prefix with existing ordering.+fn prefix_ordering_equivalence_with_existing_ordering(+ existing_ordering: &[PhysicalSortExpr],+ oeq_classes: &[OrderingEquivalentClass],+ eq_classes: &[EquivalentClass],+) -> Vec<OrderingEquivalentClass> {+ oeq_classes+ .iter()+ .map(|oeq_class| {+ let normalized_head = normalize_sort_exprs(oeq_class.head(), eq_classes, &[]);+ let updated_head = merge_vectors(existing_ordering, &normalized_head);+ let updated_others = oeq_class+ .others()+ .iter()+ .map(|ordering| {+ let normalized_ordering =+ normalize_sort_exprs(ordering, eq_classes, &[]);+ merge_vectors(existing_ordering, &normalized_ordering)+ })+ .collect();+ OrderingEquivalentClass::new(updated_head, updated_others)+ })+ .collect()+}++/// Calculate ordering equivalence properties for the given join operation.+pub fn combine_join_ordering_equivalence_properties(+ join_type: &JoinType,+ left: &Arc<dyn ExecutionPlan>,+ right: &Arc<dyn ExecutionPlan>,+ schema: SchemaRef,+ maintains_input_order: &[bool],+ probe_side: Option<JoinSide>,+ join_eq_properties: EquivalenceProperties,+) -> Result<OrderingEquivalenceProperties> {+ let mut new_properties = OrderingEquivalenceProperties::new(schema);+ let left_columns_len = left.schema().fields.len();+ let left_oeq_properties = left.ordering_equivalence_properties();+ let right_oeq_properties = right.ordering_equivalence_properties();+ // All joins have 2 children+ assert_eq!(maintains_input_order.len(), 2);+ let left_maintains = maintains_input_order[0];+ let right_maintains = maintains_input_order[1];+ match (left_maintains, right_maintains) {+ (true, true) => {+ return Err(DataFusionError::Plan(+ "Cannot maintain ordering of both sides".to_string(),+ ))+ }+ (true, false) => {+ new_properties.extend(left_oeq_properties.classes().iter().cloned());+ // In this special case, right side ordering can be prefixed with left side ordering.+ if probe_side == Some(JoinSide::Left)+ && right.output_ordering().is_some()+ && *join_type == JoinType::Inner+ {+ let right_oeq_classes =+ get_updated_right_ordering_equivalence_properties(+ join_type,+ right_oeq_properties.classes(),+ left_columns_len,+ )?;+ let left_output_ordering = left.output_ordering().unwrap_or(&[]);+ // Right side ordering equivalence properties should be prepended with+ // those of the left side while constructing output ordering equivalence+ // properties since stream side is the left side.+ //+ // If the right table ordering equivalences contain `b ASC`, and the output+ // ordering of the left table is `a ASC`, then the ordering equivalence `b ASC`+ // for the right table should be converted to `a ASC, b ASC` before it is added+ // to the ordering equivalences of the join.+ let updated_right_oeq_classes =+ prefix_ordering_equivalence_with_existing_ordering(+ left_output_ordering,+ &right_oeq_classes,+ join_eq_properties.classes(),+ );+ new_properties.extend(updated_right_oeq_classes);+ }+ }+ (false, true) => {+ let right_oeq_classes = get_updated_right_ordering_equivalence_properties(+ join_type,+ right_oeq_properties.classes(),+ left_columns_len,+ )?;+ new_properties.extend(right_oeq_classes);+ // In this special case, left side ordering can be prefixed with right side ordering.+ if probe_side == Some(JoinSide::Right)+ && left.output_ordering().is_some()+ && *join_type == JoinType::Inner+ {+ let left_oeq_classes = right_oeq_properties.classes();+ let right_output_ordering = right.output_ordering().unwrap_or(&[]);+ // Left side ordering equivalence properties should be prepended with+ // those of the right side while constructing output ordering equivalence+ // properties since stream side is the right side.+ //+ // If the right table ordering equivalences contain `b ASC`, and the output+ // ordering of the left table is `a ASC`, then the ordering equivalence `b ASC`+ // for the right table should be converted to `a ASC, b ASC` before it is added+ // to the ordering equivalences of the join.+ let updated_left_oeq_classes =+ prefix_ordering_equivalence_with_existing_ordering(+ right_output_ordering,+ left_oeq_classes,+ join_eq_properties.classes(),+ );+ new_properties.extend(updated_left_oeq_classes);+ }+ }+ (false, false) => {}+ }+ Ok(new_properties)+}+/// Adds the `offset` value to `Column` indices inside `expr`. This function is/// generally used during the update of the right table schema in join operations.pub(crate) fn add_offset_to_expr(diff --git a/datafusion/optimizer/src/analyzer/count_wildcard_rule.rs b/datafusion/optimizer/src/analyzer/count_wildcard_rule.rsindex ce798781c6..912ac069e0 100644--- a/datafusion/optimizer/src/analyzer/count_wildcard_rule.rs+++ b/datafusion/optimizer/src/analyzer/count_wildcard_rule.rs@@ -75,7 +75,7 @@ fn analyze_internal(plan: LogicalPlan) -> Result<Transformed<LogicalPlan>> {.collect::<Result<Vec<_>>>()?;Ok(Transformed::Yes(LogicalPlan::Aggregate(- Aggregate::try_new(agg.input.clone(), agg.group_expr.clone(), aggr_expr)?,+ Aggregate::try_new(agg.input.clone(), agg.group_expr, aggr_expr)?,)))}LogicalPlan::Sort(Sort { expr, input, fetch }) => {