Apache DataFusion SQL Query Engine
Split equivalence code into smaller modules. (#8649)
tushushu4e4d05085870
diff --git a/datafusion/physical-expr/src/equivalence.rs b/datafusion/physical-expr/src/equivalence.rsdeleted file mode 100644index defd7b5786..0000000000--- a/datafusion/physical-expr/src/equivalence.rs+++ /dev/null@@ -1,5327 +0,0 @@-// Licensed to the Apache Software Foundation (ASF) under one-// or more contributor license agreements. See the NOTICE file-// distributed with this work for additional information-// regarding copyright ownership. The ASF licenses this file-// to you under the Apache License, Version 2.0 (the-// "License"); you may not use this file except in compliance-// with the License. You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing,-// software distributed under the License is distributed on an-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY-// KIND, either express or implied. See the License for the-// specific language governing permissions and limitations-// under the License.--use std::collections::{HashMap, HashSet};-use std::hash::{Hash, Hasher};-use std::sync::Arc;--use crate::expressions::{Column, Literal};-use crate::physical_expr::deduplicate_physical_exprs;-use crate::sort_properties::{ExprOrdering, SortProperties};-use crate::{- physical_exprs_bag_equal, physical_exprs_contains, LexOrdering, LexOrderingRef,- LexRequirement, LexRequirementRef, PhysicalExpr, PhysicalSortExpr,- PhysicalSortRequirement,-};--use arrow::datatypes::SchemaRef;-use arrow_schema::SortOptions;-use datafusion_common::tree_node::{Transformed, TreeNode};-use datafusion_common::{JoinSide, JoinType, Result};--use indexmap::IndexSet;-use itertools::Itertools;--/// An `EquivalenceClass` is a set of [`Arc<dyn PhysicalExpr>`]s that are known-/// to have the same value for all tuples in a relation. These are generated by-/// equality predicates (e.g. `a = b`), typically equi-join conditions and-/// equality conditions in filters.-///-/// Two `EquivalenceClass`es are equal if they contains the same expressions in-/// without any ordering.-#[derive(Debug, Clone)]-pub struct EquivalenceClass {- /// The expressions in this equivalence class. The order doesn't- /// matter for equivalence purposes- ///- /// TODO: use a HashSet for this instead of a Vec- exprs: Vec<Arc<dyn PhysicalExpr>>,-}--impl PartialEq for EquivalenceClass {- /// Returns true if other is equal in the sense- /// of bags (multi-sets), disregarding their orderings.- fn eq(&self, other: &Self) -> bool {- physical_exprs_bag_equal(&self.exprs, &other.exprs)- }-}--impl EquivalenceClass {- /// Create a new empty equivalence class- pub fn new_empty() -> Self {- Self { exprs: vec![] }- }-- // Create a new equivalence class from a pre-existing `Vec`- pub fn new(mut exprs: Vec<Arc<dyn PhysicalExpr>>) -> Self {- deduplicate_physical_exprs(&mut exprs);- Self { exprs }- }-- /// Return the inner vector of expressions- pub fn into_vec(self) -> Vec<Arc<dyn PhysicalExpr>> {- self.exprs- }-- /// Return the "canonical" expression for this class (the first element)- /// if any- fn canonical_expr(&self) -> Option<Arc<dyn PhysicalExpr>> {- self.exprs.first().cloned()- }-- /// Insert the expression into this class, meaning it is known to be equal to- /// all other expressions in this class- pub fn push(&mut self, expr: Arc<dyn PhysicalExpr>) {- if !self.contains(&expr) {- self.exprs.push(expr);- }- }-- /// Inserts all the expressions from other into this class- pub fn extend(&mut self, other: Self) {- for expr in other.exprs {- // use push so entries are deduplicated- self.push(expr);- }- }-- /// Returns true if this equivalence class contains t expression- pub fn contains(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {- physical_exprs_contains(&self.exprs, expr)- }-- /// Returns true if this equivalence class has any entries in common with `other`- pub fn contains_any(&self, other: &Self) -> bool {- self.exprs.iter().any(|e| other.contains(e))- }-- /// return the number of items in this class- pub fn len(&self) -> usize {- self.exprs.len()- }-- /// return true if this class is empty- pub fn is_empty(&self) -> bool {- self.exprs.is_empty()- }-- /// Iterate over all elements in this class, in some arbitrary order- pub fn iter(&self) -> impl Iterator<Item = &Arc<dyn PhysicalExpr>> {- self.exprs.iter()- }-- /// Return a new equivalence class that have the specified offset added to- /// each expression (used when schemas are appended such as in joins)- pub fn with_offset(&self, offset: usize) -> Self {- let new_exprs = self- .exprs- .iter()- .cloned()- .map(|e| add_offset_to_expr(e, offset))- .collect();- Self::new(new_exprs)- }-}--/// Stores the mapping between source expressions and target expressions for a-/// projection.-#[derive(Debug, Clone)]-pub struct ProjectionMapping {- /// Mapping between source expressions and target expressions.- /// Vector indices correspond to the indices after projection.- map: Vec<(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)>,-}--impl ProjectionMapping {- /// Constructs the mapping between a projection's input and output- /// expressions.- ///- /// For example, given the input projection expressions (`a + b`, `c + d`)- /// and an output schema with two columns `"c + d"` and `"a + b"`, the- /// projection mapping would be:- ///- /// ```text- /// [0]: (c + d, col("c + d"))- /// [1]: (a + b, col("a + b"))- /// ```- ///- /// where `col("c + d")` means the column named `"c + d"`.- pub fn try_new(- expr: &[(Arc<dyn PhysicalExpr>, String)],- input_schema: &SchemaRef,- ) -> Result<Self> {- // Construct a map from the input expressions to the output expression of the projection:- expr.iter()- .enumerate()- .map(|(expr_idx, (expression, name))| {- let target_expr = Arc::new(Column::new(name, expr_idx)) as _;- expression- .clone()- .transform_down(&|e| match e.as_any().downcast_ref::<Column>() {- Some(col) => {- // Sometimes, an expression and its name in the input_schema- // doesn't match. This can cause problems, so we make sure- // that the expression name matches with the name in `input_schema`.- // Conceptually, `source_expr` and `expression` should be the same.- let idx = col.index();- let matching_input_field = input_schema.field(idx);- let matching_input_column =- Column::new(matching_input_field.name(), idx);- Ok(Transformed::Yes(Arc::new(matching_input_column)))- }- None => Ok(Transformed::No(e)),- })- .map(|source_expr| (source_expr, target_expr))- })- .collect::<Result<Vec<_>>>()- .map(|map| Self { map })- }-- /// Iterate over pairs of (source, target) expressions- pub fn iter(- &self,- ) -> impl Iterator<Item = &(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)> + '_ {- self.map.iter()- }-- /// This function returns the target expression for a given source expression.- ///- /// # Arguments- ///- /// * `expr` - Source physical expression.- ///- /// # Returns- ///- /// An `Option` containing the target for the given source expression,- /// where a `None` value means that `expr` is not inside the mapping.- pub fn target_expr(- &self,- expr: &Arc<dyn PhysicalExpr>,- ) -> Option<Arc<dyn PhysicalExpr>> {- self.map- .iter()- .find(|(source, _)| source.eq(expr))- .map(|(_, target)| target.clone())- }-}--/// An `EquivalenceGroup` is a collection of `EquivalenceClass`es where each-/// class represents a distinct equivalence class in a relation.-#[derive(Debug, Clone)]-pub struct EquivalenceGroup {- classes: Vec<EquivalenceClass>,-}--impl EquivalenceGroup {- /// Creates an empty equivalence group.- fn empty() -> Self {- Self { classes: vec![] }- }-- /// Creates an equivalence group from the given equivalence classes.- fn new(classes: Vec<EquivalenceClass>) -> Self {- let mut result = Self { classes };- result.remove_redundant_entries();- result- }-- /// Returns how many equivalence classes there are in this group.- fn len(&self) -> usize {- self.classes.len()- }-- /// Checks whether this equivalence group is empty.- pub fn is_empty(&self) -> bool {- self.len() == 0- }-- /// Returns an iterator over the equivalence classes in this group.- pub fn iter(&self) -> impl Iterator<Item = &EquivalenceClass> {- self.classes.iter()- }-- /// Adds the equality `left` = `right` to this equivalence group.- /// New equality conditions often arise after steps like `Filter(a = b)`,- /// `Alias(a, a as b)` etc.- fn add_equal_conditions(- &mut self,- left: &Arc<dyn PhysicalExpr>,- right: &Arc<dyn PhysicalExpr>,- ) {- let mut first_class = None;- let mut second_class = None;- for (idx, cls) in self.classes.iter().enumerate() {- if cls.contains(left) {- first_class = Some(idx);- }- if cls.contains(right) {- second_class = Some(idx);- }- }- match (first_class, second_class) {- (Some(mut first_idx), Some(mut second_idx)) => {- // If the given left and right sides belong to different classes,- // we should unify/bridge these classes.- if first_idx != second_idx {- // By convention, make sure `second_idx` is larger than `first_idx`.- if first_idx > second_idx {- (first_idx, second_idx) = (second_idx, first_idx);- }- // Remove the class at `second_idx` and merge its values with- // the class at `first_idx`. The convention above makes sure- // that `first_idx` is still valid after removing `second_idx`.- let other_class = self.classes.swap_remove(second_idx);- self.classes[first_idx].extend(other_class);- }- }- (Some(group_idx), None) => {- // Right side is new, extend left side's class:- self.classes[group_idx].push(right.clone());- }- (None, Some(group_idx)) => {- // Left side is new, extend right side's class:- self.classes[group_idx].push(left.clone());- }- (None, None) => {- // None of the expressions is among existing classes.- // Create a new equivalence class and extend the group.- self.classes- .push(EquivalenceClass::new(vec![left.clone(), right.clone()]));- }- }- }-- /// Removes redundant entries from this group.- fn remove_redundant_entries(&mut self) {- // Remove duplicate entries from each equivalence class:- self.classes.retain_mut(|cls| {- // Keep groups that have at least two entries as singleton class is- // meaningless (i.e. it contains no non-trivial information):- cls.len() > 1- });- // Unify/bridge groups that have common expressions:- self.bridge_classes()- }-- /// This utility function unifies/bridges classes that have common expressions.- /// For example, assume that we have [`EquivalenceClass`]es `[a, b]` and `[b, c]`.- /// Since both classes contain `b`, columns `a`, `b` and `c` are actually all- /// equal and belong to one class. This utility converts merges such classes.- fn bridge_classes(&mut self) {- let mut idx = 0;- while idx < self.classes.len() {- let mut next_idx = idx + 1;- let start_size = self.classes[idx].len();- while next_idx < self.classes.len() {- if self.classes[idx].contains_any(&self.classes[next_idx]) {- let extension = self.classes.swap_remove(next_idx);- self.classes[idx].extend(extension);- } else {- next_idx += 1;- }- }- if self.classes[idx].len() > start_size {- continue;- }- idx += 1;- }- }-- /// Extends this equivalence group with the `other` equivalence group.- fn extend(&mut self, other: Self) {- self.classes.extend(other.classes);- self.remove_redundant_entries();- }-- /// Normalizes the given physical expression according to this group.- /// The expression is replaced with the first expression in the equivalence- /// class it matches with (if any).- pub fn normalize_expr(&self, expr: Arc<dyn PhysicalExpr>) -> Arc<dyn PhysicalExpr> {- expr.clone()- .transform(&|expr| {- for cls in self.iter() {- if cls.contains(&expr) {- return Ok(Transformed::Yes(cls.canonical_expr().unwrap()));- }- }- Ok(Transformed::No(expr))- })- .unwrap_or(expr)- }-- /// Normalizes the given sort expression according to this group.- /// The underlying physical expression is replaced with the first expression- /// in the equivalence class it matches with (if any). If the underlying- /// expression does not belong to any equivalence class in this group, returns- /// the sort expression as is.- pub fn normalize_sort_expr(- &self,- mut sort_expr: PhysicalSortExpr,- ) -> PhysicalSortExpr {- sort_expr.expr = self.normalize_expr(sort_expr.expr);- sort_expr- }-- /// Normalizes the given sort requirement according to this group.- /// The underlying physical expression is replaced with the first expression- /// in the equivalence class it matches with (if any). If the underlying- /// expression does not belong to any equivalence class in this group, returns- /// the given sort requirement as is.- pub fn normalize_sort_requirement(- &self,- mut sort_requirement: PhysicalSortRequirement,- ) -> PhysicalSortRequirement {- sort_requirement.expr = self.normalize_expr(sort_requirement.expr);- sort_requirement- }-- /// This function applies the `normalize_expr` function for all expressions- /// in `exprs` and returns the corresponding normalized physical expressions.- pub fn normalize_exprs(- &self,- exprs: impl IntoIterator<Item = Arc<dyn PhysicalExpr>>,- ) -> Vec<Arc<dyn PhysicalExpr>> {- exprs- .into_iter()- .map(|expr| self.normalize_expr(expr))- .collect()- }-- /// This function applies the `normalize_sort_expr` function for all sort- /// expressions in `sort_exprs` and returns the corresponding normalized- /// sort expressions.- pub fn normalize_sort_exprs(&self, sort_exprs: LexOrderingRef) -> LexOrdering {- // Convert sort expressions to sort requirements:- let sort_reqs = PhysicalSortRequirement::from_sort_exprs(sort_exprs.iter());- // Normalize the requirements:- let normalized_sort_reqs = self.normalize_sort_requirements(&sort_reqs);- // Convert sort requirements back to sort expressions:- PhysicalSortRequirement::to_sort_exprs(normalized_sort_reqs)- }-- /// This function applies the `normalize_sort_requirement` function for all- /// requirements in `sort_reqs` and returns the corresponding normalized- /// sort requirements.- pub fn normalize_sort_requirements(- &self,- sort_reqs: LexRequirementRef,- ) -> LexRequirement {- collapse_lex_req(- sort_reqs- .iter()- .map(|sort_req| self.normalize_sort_requirement(sort_req.clone()))- .collect(),- )- }-- /// Projects `expr` according to the given projection mapping.- /// If the resulting expression is invalid after projection, returns `None`.- fn project_expr(- &self,- mapping: &ProjectionMapping,- expr: &Arc<dyn PhysicalExpr>,- ) -> Option<Arc<dyn PhysicalExpr>> {- // First, we try to project expressions with an exact match. If we are- // unable to do this, we consult equivalence classes.- if let Some(target) = mapping.target_expr(expr) {- // If we match the source, we can project directly:- return Some(target);- } else {- // If the given expression is not inside the mapping, try to project- // expressions considering the equivalence classes.- for (source, target) in mapping.iter() {- // If we match an equivalent expression to `source`, then we can- // project. For example, if we have the mapping `(a as a1, a + c)`- // and the equivalence class `(a, b)`, expression `b` projects to `a1`.- if self- .get_equivalence_class(source)- .map_or(false, |group| group.contains(expr))- {- return Some(target.clone());- }- }- }- // Project a non-leaf expression by projecting its children.- let children = expr.children();- if children.is_empty() {- // Leaf expression should be inside mapping.- return None;- }- children- .into_iter()- .map(|child| self.project_expr(mapping, &child))- .collect::<Option<Vec<_>>>()- .map(|children| expr.clone().with_new_children(children).unwrap())- }-- /// Projects this equivalence group according to the given projection mapping.- pub fn project(&self, mapping: &ProjectionMapping) -> Self {- let projected_classes = self.iter().filter_map(|cls| {- let new_class = cls- .iter()- .filter_map(|expr| self.project_expr(mapping, expr))- .collect::<Vec<_>>();- (new_class.len() > 1).then_some(EquivalenceClass::new(new_class))- });- // TODO: Convert the algorithm below to a version that uses `HashMap`.- // once `Arc<dyn PhysicalExpr>` can be stored in `HashMap`.- // See issue: https://github.com/apache/arrow-datafusion/issues/8027- let mut new_classes = vec![];- for (source, target) in mapping.iter() {- if new_classes.is_empty() {- new_classes.push((source, vec![target.clone()]));- }- if let Some((_, values)) =- new_classes.iter_mut().find(|(key, _)| key.eq(source))- {- if !physical_exprs_contains(values, target) {- values.push(target.clone());- }- }- }- // Only add equivalence classes with at least two members as singleton- // equivalence classes are meaningless.- let new_classes = new_classes- .into_iter()- .filter_map(|(_, values)| (values.len() > 1).then_some(values))- .map(EquivalenceClass::new);-- let classes = projected_classes.chain(new_classes).collect();- Self::new(classes)- }-- /// Returns the equivalence class containing `expr`. If no equivalence class- /// contains `expr`, returns `None`.- fn get_equivalence_class(- &self,- expr: &Arc<dyn PhysicalExpr>,- ) -> Option<&EquivalenceClass> {- self.iter().find(|cls| cls.contains(expr))- }-- /// Combine equivalence groups of the given join children.- pub fn join(- &self,- right_equivalences: &Self,- join_type: &JoinType,- left_size: usize,- on: &[(Column, Column)],- ) -> Self {- match join_type {- JoinType::Inner | JoinType::Left | JoinType::Full | JoinType::Right => {- let mut result = Self::new(- self.iter()- .cloned()- .chain(- right_equivalences- .iter()- .map(|cls| cls.with_offset(left_size)),- )- .collect(),- );- // In we have an inner join, expressions in the "on" condition- // are equal in the resulting table.- if join_type == &JoinType::Inner {- for (lhs, rhs) in on.iter() {- let index = rhs.index() + left_size;- let new_lhs = Arc::new(lhs.clone()) as _;- let new_rhs = Arc::new(Column::new(rhs.name(), index)) as _;- result.add_equal_conditions(&new_lhs, &new_rhs);- }- }- result- }- JoinType::LeftSemi | JoinType::LeftAnti => self.clone(),- JoinType::RightSemi | JoinType::RightAnti => right_equivalences.clone(),- }- }-}--/// This function constructs a duplicate-free `LexOrderingReq` by filtering out-/// duplicate entries that have same physical expression inside. For example,-/// `vec![a Some(ASC), a Some(DESC)]` collapses to `vec![a Some(ASC)]`.-pub fn collapse_lex_req(input: LexRequirement) -> LexRequirement {- let mut output = Vec::<PhysicalSortRequirement>::new();- for item in input {- if !output.iter().any(|req| req.expr.eq(&item.expr)) {- output.push(item);- }- }- output-}--/// This function constructs a duplicate-free `LexOrdering` by filtering out-/// duplicate entries that have same physical expression inside. For example,-/// `vec![a ASC, a DESC]` collapses to `vec![a ASC]`.-pub fn collapse_lex_ordering(input: LexOrdering) -> LexOrdering {- let mut output = Vec::<PhysicalSortExpr>::new();- for item in input {- if !output.iter().any(|req| req.expr.eq(&item.expr)) {- output.push(item);- }- }- output-}--/// An `OrderingEquivalenceClass` object keeps track of different alternative-/// orderings than can describe a schema. For example, consider the following table:-///-/// ```text-/// |a|b|c|d|-/// |1|4|3|1|-/// |2|3|3|2|-/// |3|1|2|2|-/// |3|2|1|3|-/// ```-///-/// Here, both `vec![a ASC, b ASC]` and `vec![c DESC, d ASC]` describe the table-/// ordering. In this case, we say that these orderings are equivalent.-#[derive(Debug, Clone, Eq, PartialEq, Hash)]-pub struct OrderingEquivalenceClass {- orderings: Vec<LexOrdering>,-}--impl OrderingEquivalenceClass {- /// Creates new empty ordering equivalence class.- fn empty() -> Self {- Self { orderings: vec![] }- }-- /// Clears (empties) this ordering equivalence class.- pub fn clear(&mut self) {- self.orderings.clear();- }-- /// Creates new ordering equivalence class from the given orderings.- pub fn new(orderings: Vec<LexOrdering>) -> Self {- let mut result = Self { orderings };- result.remove_redundant_entries();- result- }-- /// Checks whether `ordering` is a member of this equivalence class.- pub fn contains(&self, ordering: &LexOrdering) -> bool {- self.orderings.contains(ordering)- }-- /// Adds `ordering` to this equivalence class.- #[allow(dead_code)]- fn push(&mut self, ordering: LexOrdering) {- self.orderings.push(ordering);- // Make sure that there are no redundant orderings:- self.remove_redundant_entries();- }-- /// Checks whether this ordering equivalence class is empty.- pub fn is_empty(&self) -> bool {- self.len() == 0- }-- /// Returns an iterator over the equivalent orderings in this class.- pub fn iter(&self) -> impl Iterator<Item = &LexOrdering> {- self.orderings.iter()- }-- /// Returns how many equivalent orderings there are in this class.- pub fn len(&self) -> usize {- self.orderings.len()- }-- /// Extend this ordering equivalence class with the `other` class.- pub fn extend(&mut self, other: Self) {- self.orderings.extend(other.orderings);- // Make sure that there are no redundant orderings:- self.remove_redundant_entries();- }-- /// Adds new orderings into this ordering equivalence class.- pub fn add_new_orderings(- &mut self,- orderings: impl IntoIterator<Item = LexOrdering>,- ) {- self.orderings.extend(orderings);- // Make sure that there are no redundant orderings:- self.remove_redundant_entries();- }-- /// Removes redundant orderings from this equivalence class. For instance,- /// if we already have the ordering `[a ASC, b ASC, c DESC]`, then there is- /// no need to keep ordering `[a ASC, b ASC]` in the state.- fn remove_redundant_entries(&mut self) {- let mut work = true;- while work {- work = false;- let mut idx = 0;- while idx < self.orderings.len() {- let mut ordering_idx = idx + 1;- let mut removal = self.orderings[idx].is_empty();- while ordering_idx < self.orderings.len() {- work |= resolve_overlap(&mut self.orderings, idx, ordering_idx);- if self.orderings[idx].is_empty() {- removal = true;- break;- }- work |= resolve_overlap(&mut self.orderings, ordering_idx, idx);- if self.orderings[ordering_idx].is_empty() {- self.orderings.swap_remove(ordering_idx);- } else {- ordering_idx += 1;- }- }- if removal {- self.orderings.swap_remove(idx);- } else {- idx += 1;- }- }- }- }-- /// Returns the concatenation of all the orderings. This enables merge- /// operations to preserve all equivalent orderings simultaneously.- pub fn output_ordering(&self) -> Option<LexOrdering> {- let output_ordering = self.orderings.iter().flatten().cloned().collect();- let output_ordering = collapse_lex_ordering(output_ordering);- (!output_ordering.is_empty()).then_some(output_ordering)- }-- // Append orderings in `other` to all existing orderings in this equivalence- // class.- pub fn join_suffix(mut self, other: &Self) -> Self {- let n_ordering = self.orderings.len();- // Replicate entries before cross product- let n_cross = std::cmp::max(n_ordering, other.len() * n_ordering);- self.orderings = self- .orderings- .iter()- .cloned()- .cycle()- .take(n_cross)- .collect();- // Suffix orderings of other to the current orderings.- for (outer_idx, ordering) in other.iter().enumerate() {- for idx in 0..n_ordering {- // Calculate cross product index- let idx = outer_idx * n_ordering + idx;- self.orderings[idx].extend(ordering.iter().cloned());- }- }- self- }-- /// Adds `offset` value to the index of each expression inside this- /// ordering equivalence class.- pub fn add_offset(&mut self, offset: usize) {- for ordering in self.orderings.iter_mut() {- for sort_expr in ordering {- sort_expr.expr = add_offset_to_expr(sort_expr.expr.clone(), offset);- }- }- }-- /// Gets sort options associated with this expression if it is a leading- /// ordering expression. Otherwise, returns `None`.- fn get_options(&self, expr: &Arc<dyn PhysicalExpr>) -> Option<SortOptions> {- for ordering in self.iter() {- let leading_ordering = &ordering[0];- if leading_ordering.expr.eq(expr) {- return Some(leading_ordering.options);- }- }- None- }-}--/// 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 fn add_offset_to_expr(- expr: Arc<dyn PhysicalExpr>,- offset: usize,-) -> Arc<dyn PhysicalExpr> {- expr.transform_down(&|e| match e.as_any().downcast_ref::<Column>() {- Some(col) => Ok(Transformed::Yes(Arc::new(Column::new(- col.name(),- offset + col.index(),- )))),- None => Ok(Transformed::No(e)),- })- .unwrap()- // Note that we can safely unwrap here since our transform always returns- // an `Ok` value.-}--/// Trims `orderings[idx]` if some suffix of it overlaps with a prefix of-/// `orderings[pre_idx]`. Returns `true` if there is any overlap, `false` otherwise.-fn resolve_overlap(orderings: &mut [LexOrdering], idx: usize, pre_idx: usize) -> bool {- let length = orderings[idx].len();- let other_length = orderings[pre_idx].len();- for overlap in 1..=length.min(other_length) {- if orderings[idx][length - overlap..] == orderings[pre_idx][..overlap] {- orderings[idx].truncate(length - overlap);- return true;- }- }- false-}--/// A `EquivalenceProperties` object stores useful information related to a schema.-/// Currently, it keeps track of:-/// - Equivalent expressions, e.g expressions that have same value.-/// - Valid sort expressions (orderings) for the schema.-/// - Constants expressions (e.g expressions that are known to have constant values).-///-/// Consider table below:-///-/// ```text-/// ┌-------┐-/// | a | b |-/// |---|---|-/// | 1 | 9 |-/// | 2 | 8 |-/// | 3 | 7 |-/// | 5 | 5 |-/// └---┴---┘-/// ```-///-/// where both `a ASC` and `b DESC` can describe the table ordering. With-/// `EquivalenceProperties`, we can keep track of these different valid sort-/// expressions and treat `a ASC` and `b DESC` on an equal footing.-///-/// Similarly, consider the table below:-///-/// ```text-/// ┌-------┐-/// | a | b |-/// |---|---|-/// | 1 | 1 |-/// | 2 | 2 |-/// | 3 | 3 |-/// | 5 | 5 |-/// └---┴---┘-/// ```-///-/// where columns `a` and `b` always have the same value. We keep track of such-/// equivalences inside this object. With this information, we can optimize-/// things like partitioning. For example, if the partition requirement is-/// `Hash(a)` and output partitioning is `Hash(b)`, then we can deduce that-/// the existing partitioning satisfies the requirement.-#[derive(Debug, Clone)]-pub struct EquivalenceProperties {- /// Collection of equivalence classes that store expressions with the same- /// value.- eq_group: EquivalenceGroup,- /// Equivalent sort expressions for this table.- oeq_class: OrderingEquivalenceClass,- /// Expressions whose values are constant throughout the table.- /// TODO: We do not need to track constants separately, they can be tracked- /// inside `eq_groups` as `Literal` expressions.- constants: Vec<Arc<dyn PhysicalExpr>>,- /// Schema associated with this object.- schema: SchemaRef,-}--impl EquivalenceProperties {- /// Creates an empty `EquivalenceProperties` object.- pub fn new(schema: SchemaRef) -> Self {- Self {- eq_group: EquivalenceGroup::empty(),- oeq_class: OrderingEquivalenceClass::empty(),- constants: vec![],- schema,- }- }-- /// Creates a new `EquivalenceProperties` object with the given orderings.- pub fn new_with_orderings(schema: SchemaRef, orderings: &[LexOrdering]) -> Self {- Self {- eq_group: EquivalenceGroup::empty(),- oeq_class: OrderingEquivalenceClass::new(orderings.to_vec()),- constants: vec![],- schema,- }- }-- /// Returns the associated schema.- pub fn schema(&self) -> &SchemaRef {- &self.schema- }-- /// Returns a reference to the ordering equivalence class within.- pub fn oeq_class(&self) -> &OrderingEquivalenceClass {- &self.oeq_class- }-- /// Returns a reference to the equivalence group within.- pub fn eq_group(&self) -> &EquivalenceGroup {- &self.eq_group- }-- /// Returns a reference to the constant expressions- pub fn constants(&self) -> &[Arc<dyn PhysicalExpr>] {- &self.constants- }-- /// Returns the normalized version of the ordering equivalence class within.- /// Normalization removes constants and duplicates as well as standardizing- /// expressions according to the equivalence group within.- pub fn normalized_oeq_class(&self) -> OrderingEquivalenceClass {- OrderingEquivalenceClass::new(- self.oeq_class- .iter()- .map(|ordering| self.normalize_sort_exprs(ordering))- .collect(),- )- }-- /// Extends this `EquivalenceProperties` with the `other` object.- pub fn extend(mut self, other: Self) -> Self {- self.eq_group.extend(other.eq_group);- self.oeq_class.extend(other.oeq_class);- self.add_constants(other.constants)- }-- /// Clears (empties) the ordering equivalence class within this object.- /// Call this method when existing orderings are invalidated.- pub fn clear_orderings(&mut self) {- self.oeq_class.clear();- }-- /// Extends this `EquivalenceProperties` by adding the orderings inside the- /// ordering equivalence class `other`.- pub fn add_ordering_equivalence_class(&mut self, other: OrderingEquivalenceClass) {- self.oeq_class.extend(other);- }-- /// Adds new orderings into the existing ordering equivalence class.- pub fn add_new_orderings(- &mut self,- orderings: impl IntoIterator<Item = LexOrdering>,- ) {- self.oeq_class.add_new_orderings(orderings);- }-- /// Incorporates the given equivalence group to into the existing- /// equivalence group within.- pub fn add_equivalence_group(&mut self, other_eq_group: EquivalenceGroup) {- self.eq_group.extend(other_eq_group);- }-- /// Adds a new equality condition into the existing equivalence group.- /// If the given equality defines a new equivalence class, adds this new- /// equivalence class to the equivalence group.- pub fn add_equal_conditions(- &mut self,- left: &Arc<dyn PhysicalExpr>,- right: &Arc<dyn PhysicalExpr>,- ) {- self.eq_group.add_equal_conditions(left, right);- }-- /// Track/register physical expressions with constant values.- pub fn add_constants(- mut self,- constants: impl IntoIterator<Item = Arc<dyn PhysicalExpr>>,- ) -> Self {- for expr in self.eq_group.normalize_exprs(constants) {- if !physical_exprs_contains(&self.constants, &expr) {- self.constants.push(expr);- }- }- self- }-- /// Updates the ordering equivalence group within assuming that the table- /// is re-sorted according to the argument `sort_exprs`. Note that constants- /// and equivalence classes are unchanged as they are unaffected by a re-sort.- pub fn with_reorder(mut self, sort_exprs: Vec<PhysicalSortExpr>) -> Self {- // TODO: In some cases, existing ordering equivalences may still be valid add this analysis.- self.oeq_class = OrderingEquivalenceClass::new(vec![sort_exprs]);- self- }-- /// Normalizes the given sort expressions (i.e. `sort_exprs`) using the- /// equivalence group and the ordering equivalence class within.- ///- /// Assume that `self.eq_group` states column `a` and `b` are aliases.- /// Also assume that `self.oeq_class` states orderings `d ASC` and `a ASC, c ASC`- /// are equivalent (in the sense that both describe the ordering of the table).- /// If the `sort_exprs` argument were `vec![b ASC, c ASC, a ASC]`, then this- /// function would return `vec![a ASC, c ASC]`. Internally, it would first- /// normalize to `vec![a ASC, c ASC, a ASC]` and end up with the final result- /// after deduplication.- fn normalize_sort_exprs(&self, sort_exprs: LexOrderingRef) -> LexOrdering {- // Convert sort expressions to sort requirements:- let sort_reqs = PhysicalSortRequirement::from_sort_exprs(sort_exprs.iter());- // Normalize the requirements:- let normalized_sort_reqs = self.normalize_sort_requirements(&sort_reqs);- // Convert sort requirements back to sort expressions:- PhysicalSortRequirement::to_sort_exprs(normalized_sort_reqs)- }-- /// Normalizes the given sort requirements (i.e. `sort_reqs`) using the- /// equivalence group and the ordering equivalence class within. It works by:- /// - Removing expressions that have a constant value from the given requirement.- /// - Replacing sections that belong to some equivalence class in the equivalence- /// group with the first entry in the matching equivalence class.- ///- /// Assume that `self.eq_group` states column `a` and `b` are aliases.- /// Also assume that `self.oeq_class` states orderings `d ASC` and `a ASC, c ASC`- /// are equivalent (in the sense that both describe the ordering of the table).- /// If the `sort_reqs` argument were `vec![b ASC, c ASC, a ASC]`, then this- /// function would return `vec![a ASC, c ASC]`. Internally, it would first- /// normalize to `vec![a ASC, c ASC, a ASC]` and end up with the final result- /// after deduplication.- fn normalize_sort_requirements(- &self,- sort_reqs: LexRequirementRef,- ) -> LexRequirement {- let normalized_sort_reqs = self.eq_group.normalize_sort_requirements(sort_reqs);- let constants_normalized = self.eq_group.normalize_exprs(self.constants.clone());- // Prune redundant sections in the requirement:- collapse_lex_req(- normalized_sort_reqs- .iter()- .filter(|&order| {- !physical_exprs_contains(&constants_normalized, &order.expr)- })- .cloned()- .collect(),- )- }-- /// Checks whether the given ordering is satisfied by any of the existing- /// orderings.- pub fn ordering_satisfy(&self, given: LexOrderingRef) -> bool {- // Convert the given sort expressions to sort requirements:- let sort_requirements = PhysicalSortRequirement::from_sort_exprs(given.iter());- self.ordering_satisfy_requirement(&sort_requirements)- }-- /// Checks whether the given sort requirements are satisfied by any of the- /// existing orderings.- pub fn ordering_satisfy_requirement(&self, reqs: LexRequirementRef) -> bool {- let mut eq_properties = self.clone();- // First, standardize the given requirement:- let normalized_reqs = eq_properties.normalize_sort_requirements(reqs);- for normalized_req in normalized_reqs {- // Check whether given ordering is satisfied- if !eq_properties.ordering_satisfy_single(&normalized_req) {- return false;- }- // Treat satisfied keys as constants in subsequent iterations. We- // can do this because the "next" key only matters in a lexicographical- // ordering when the keys to its left have the same values.- //- // Note that these expressions are not properly "constants". This is just- // an implementation strategy confined to this function.- //- // For example, assume that the requirement is `[a ASC, (b + c) ASC]`,- // and existing equivalent orderings are `[a ASC, b ASC]` and `[c ASC]`.- // From the analysis above, we know that `[a ASC]` is satisfied. Then,- // we add column `a` as constant to the algorithm state. This enables us- // to deduce that `(b + c) ASC` is satisfied, given `a` is constant.- eq_properties =- eq_properties.add_constants(std::iter::once(normalized_req.expr));- }- true- }-- /// Determines whether the ordering specified by the given sort requirement- /// is satisfied based on the orderings within, equivalence classes, and- /// constant expressions.- ///- /// # Arguments- ///- /// - `req`: A reference to a `PhysicalSortRequirement` for which the ordering- /// satisfaction check will be done.- ///- /// # Returns- ///- /// Returns `true` if the specified ordering is satisfied, `false` otherwise.- fn ordering_satisfy_single(&self, req: &PhysicalSortRequirement) -> bool {- let expr_ordering = self.get_expr_ordering(req.expr.clone());- let ExprOrdering { expr, state, .. } = expr_ordering;- match state {- SortProperties::Ordered(options) => {- let sort_expr = PhysicalSortExpr { expr, options };- sort_expr.satisfy(req, self.schema())- }- // Singleton expressions satisfies any ordering.- SortProperties::Singleton => true,- SortProperties::Unordered => false,- }- }-- /// Checks whether the `given`` sort requirements are equal or more specific- /// than the `reference` sort requirements.- pub fn requirements_compatible(- &self,- given: LexRequirementRef,- reference: LexRequirementRef,- ) -> bool {- let normalized_given = self.normalize_sort_requirements(given);- let normalized_reference = self.normalize_sort_requirements(reference);-- (normalized_reference.len() <= normalized_given.len())- && normalized_reference- .into_iter()- .zip(normalized_given)- .all(|(reference, given)| given.compatible(&reference))- }-- /// Returns the finer ordering among the orderings `lhs` and `rhs`, breaking- /// any ties by choosing `lhs`.- ///- /// The finer ordering is the ordering that satisfies both of the orderings.- /// If the orderings are incomparable, returns `None`.- ///- /// For example, the finer ordering among `[a ASC]` and `[a ASC, b ASC]` is- /// the latter.- pub fn get_finer_ordering(- &self,- lhs: LexOrderingRef,- rhs: LexOrderingRef,- ) -> Option<LexOrdering> {- // Convert the given sort expressions to sort requirements:- let lhs = PhysicalSortRequirement::from_sort_exprs(lhs);- let rhs = PhysicalSortRequirement::from_sort_exprs(rhs);- let finer = self.get_finer_requirement(&lhs, &rhs);- // Convert the chosen sort requirements back to sort expressions:- finer.map(PhysicalSortRequirement::to_sort_exprs)- }-- /// Returns the finer ordering among the requirements `lhs` and `rhs`,- /// breaking any ties by choosing `lhs`.- ///- /// The finer requirements are the ones that satisfy both of the given- /// requirements. If the requirements are incomparable, returns `None`.- ///- /// For example, the finer requirements among `[a ASC]` and `[a ASC, b ASC]`- /// is the latter.- pub fn get_finer_requirement(- &self,- req1: LexRequirementRef,- req2: LexRequirementRef,- ) -> Option<LexRequirement> {- let mut lhs = self.normalize_sort_requirements(req1);- let mut rhs = self.normalize_sort_requirements(req2);- lhs.iter_mut()- .zip(rhs.iter_mut())- .all(|(lhs, rhs)| {- lhs.expr.eq(&rhs.expr)- && match (lhs.options, rhs.options) {- (Some(lhs_opt), Some(rhs_opt)) => lhs_opt == rhs_opt,- (Some(options), None) => {- rhs.options = Some(options);- true- }- (None, Some(options)) => {- lhs.options = Some(options);- true- }- (None, None) => true,- }- })- .then_some(if lhs.len() >= rhs.len() { lhs } else { rhs })- }-- /// Calculates the "meet" of the given orderings (`lhs` and `rhs`).- /// The meet of a set of orderings is the finest ordering that is satisfied- /// by all the orderings in that set. For details, see:- ///- /// <https://en.wikipedia.org/wiki/Join_and_meet>- ///- /// If there is no ordering that satisfies both `lhs` and `rhs`, returns- /// `None`. As an example, the meet of orderings `[a ASC]` and `[a ASC, b ASC]`- /// is `[a ASC]`.- pub fn get_meet_ordering(- &self,- lhs: LexOrderingRef,- rhs: LexOrderingRef,- ) -> Option<LexOrdering> {- let lhs = self.normalize_sort_exprs(lhs);- let rhs = self.normalize_sort_exprs(rhs);- let mut meet = vec![];- for (lhs, rhs) in lhs.into_iter().zip(rhs.into_iter()) {- if lhs.eq(&rhs) {- meet.push(lhs);- } else {- break;- }- }- (!meet.is_empty()).then_some(meet)- }-- /// Projects argument `expr` according to `projection_mapping`, taking- /// equivalences into account.- ///- /// For example, assume that columns `a` and `c` are always equal, and that- /// `projection_mapping` encodes following mapping:- ///- /// ```text- /// a -> a1- /// b -> b1- /// ```- ///- /// Then, this function projects `a + b` to `Some(a1 + b1)`, `c + b` to- /// `Some(a1 + b1)` and `d` to `None`, meaning that it cannot be projected.- pub fn project_expr(- &self,- expr: &Arc<dyn PhysicalExpr>,- projection_mapping: &ProjectionMapping,- ) -> Option<Arc<dyn PhysicalExpr>> {- self.eq_group.project_expr(projection_mapping, expr)- }-- /// Constructs a dependency map based on existing orderings referred to in- /// the projection.- ///- /// This function analyzes the orderings in the normalized order-equivalence- /// class and builds a dependency map. The dependency map captures relationships- /// between expressions within the orderings, helping to identify dependencies- /// and construct valid projected orderings during projection operations.- ///- /// # Parameters- ///- /// - `mapping`: A reference to the `ProjectionMapping` that defines the- /// relationship between source and target expressions.- ///- /// # Returns- ///- /// A [`DependencyMap`] representing the dependency map, where each- /// [`DependencyNode`] contains dependencies for the key [`PhysicalSortExpr`].- ///- /// # Example- ///- /// Assume we have two equivalent orderings: `[a ASC, b ASC]` and `[a ASC, c ASC]`,- /// and the projection mapping is `[a -> a_new, b -> b_new, b + c -> b + c]`.- /// Then, the dependency map will be:- ///- /// ```text- /// a ASC: Node {Some(a_new ASC), HashSet{}}- /// b ASC: Node {Some(b_new ASC), HashSet{a ASC}}- /// c ASC: Node {None, HashSet{a ASC}}- /// ```- fn construct_dependency_map(&self, mapping: &ProjectionMapping) -> DependencyMap {- let mut dependency_map = HashMap::new();- for ordering in self.normalized_oeq_class().iter() {- for (idx, sort_expr) in ordering.iter().enumerate() {- let target_sort_expr =- self.project_expr(&sort_expr.expr, mapping).map(|expr| {- PhysicalSortExpr {- expr,- options: sort_expr.options,- }- });- let is_projected = target_sort_expr.is_some();- if is_projected- || mapping- .iter()- .any(|(source, _)| expr_refers(source, &sort_expr.expr))- {- // Previous ordering is a dependency. Note that there is no,- // dependency for a leading ordering (i.e. the first sort- // expression).- let dependency = idx.checked_sub(1).map(|a| &ordering[a]);- // Add sort expressions that can be projected or referred to- // by any of the projection expressions to the dependency map:- dependency_map- .entry(sort_expr.clone())- .or_insert_with(|| DependencyNode {- target_sort_expr: target_sort_expr.clone(),- dependencies: HashSet::new(),- })- .insert_dependency(dependency);- }- if !is_projected {- // If we can not project, stop constructing the dependency- // map as remaining dependencies will be invalid after projection.- break;- }- }- }- dependency_map- }-- /// Returns a new `ProjectionMapping` where source expressions are normalized.- ///- /// This normalization ensures that source expressions are transformed into a- /// consistent representation. This is beneficial for algorithms that rely on- /// exact equalities, as it allows for more precise and reliable comparisons.- ///- /// # Parameters- ///- /// - `mapping`: A reference to the original `ProjectionMapping` to be normalized.- ///- /// # Returns- ///- /// A new `ProjectionMapping` with normalized source expressions.- fn normalized_mapping(&self, mapping: &ProjectionMapping) -> ProjectionMapping {- // Construct the mapping where source expressions are normalized. In this way- // In the algorithms below we can work on exact equalities- ProjectionMapping {- map: mapping- .iter()- .map(|(source, target)| {- let normalized_source = self.eq_group.normalize_expr(source.clone());- (normalized_source, target.clone())- })- .collect(),- }- }-- /// Computes projected orderings based on a given projection mapping.- ///- /// This function takes a `ProjectionMapping` and computes the possible- /// orderings for the projected expressions. It considers dependencies- /// between expressions and generates valid orderings according to the- /// specified sort properties.- ///- /// # Parameters- ///- /// - `mapping`: A reference to the `ProjectionMapping` that defines the- /// relationship between source and target expressions.- ///- /// # Returns- ///- /// A vector of `LexOrdering` containing all valid orderings after projection.- fn projected_orderings(&self, mapping: &ProjectionMapping) -> Vec<LexOrdering> {- let mapping = self.normalized_mapping(mapping);-- // Get dependency map for existing orderings:- let dependency_map = self.construct_dependency_map(&mapping);-- let orderings = mapping.iter().flat_map(|(source, target)| {- referred_dependencies(&dependency_map, source)- .into_iter()- .filter_map(|relevant_deps| {- if let SortProperties::Ordered(options) =- get_expr_ordering(source, &relevant_deps)- {- Some((options, relevant_deps))- } else {- // Do not consider unordered cases- None- }- })- .flat_map(|(options, relevant_deps)| {- let sort_expr = PhysicalSortExpr {- expr: target.clone(),- options,- };- // Generate dependent orderings (i.e. prefixes for `sort_expr`):- let mut dependency_orderings =- generate_dependency_orderings(&relevant_deps, &dependency_map);- // Append `sort_expr` to the dependent orderings:- for ordering in dependency_orderings.iter_mut() {- ordering.push(sort_expr.clone());- }- dependency_orderings- })- });-- // Add valid projected orderings. For example, if existing ordering is- // `a + b` and projection is `[a -> a_new, b -> b_new]`, we need to- // preserve `a_new + b_new` as ordered. Please note that `a_new` and- // `b_new` themselves need not be ordered. Such dependencies cannot be- // deduced via the pass above.- let projected_orderings = dependency_map.iter().flat_map(|(sort_expr, node)| {- let mut prefixes = construct_prefix_orderings(sort_expr, &dependency_map);- if prefixes.is_empty() {- // If prefix is empty, there is no dependency. Insert- // empty ordering:- prefixes = vec![vec![]];- }- // Append current ordering on top its dependencies:- for ordering in prefixes.iter_mut() {- if let Some(target) = &node.target_sort_expr {- ordering.push(target.clone())- }- }- prefixes- });-- // Simplify each ordering by removing redundant sections:- orderings- .chain(projected_orderings)- .map(collapse_lex_ordering)- .collect()- }-- /// Projects constants based on the provided `ProjectionMapping`.- ///- /// This function takes a `ProjectionMapping` and identifies/projects- /// constants based on the existing constants and the mapping. It ensures- /// that constants are appropriately propagated through the projection.- ///- /// # Arguments- ///- /// - `mapping`: A reference to a `ProjectionMapping` representing the- /// mapping of source expressions to target expressions in the projection.- ///- /// # Returns- ///- /// Returns a `Vec<Arc<dyn PhysicalExpr>>` containing the projected constants.- fn projected_constants(- &self,- mapping: &ProjectionMapping,- ) -> Vec<Arc<dyn PhysicalExpr>> {- // First, project existing constants. For example, assume that `a + b`- // is known to be constant. If the projection were `a as a_new`, `b as b_new`,- // then we would project constant `a + b` as `a_new + b_new`.- let mut projected_constants = self- .constants- .iter()- .flat_map(|expr| self.eq_group.project_expr(mapping, expr))- .collect::<Vec<_>>();- // Add projection expressions that are known to be constant:- for (source, target) in mapping.iter() {- if self.is_expr_constant(source)- && !physical_exprs_contains(&projected_constants, target)- {- projected_constants.push(target.clone());- }- }- projected_constants- }-- /// Projects the equivalences within according to `projection_mapping`- /// and `output_schema`.- pub fn project(- &self,- projection_mapping: &ProjectionMapping,- output_schema: SchemaRef,- ) -> Self {- let projected_constants = self.projected_constants(projection_mapping);- let projected_eq_group = self.eq_group.project(projection_mapping);- let projected_orderings = self.projected_orderings(projection_mapping);- Self {- eq_group: projected_eq_group,- oeq_class: OrderingEquivalenceClass::new(projected_orderings),- constants: projected_constants,- schema: output_schema,- }- }-- /// Returns the longest (potentially partial) permutation satisfying the- /// existing ordering. For example, if we have the equivalent orderings- /// `[a ASC, b ASC]` and `[c DESC]`, with `exprs` containing `[c, b, a, d]`,- /// then this function returns `([a ASC, b ASC, c DESC], [2, 1, 0])`.- /// This means that the specification `[a ASC, b ASC, c DESC]` is satisfied- /// by the existing ordering, and `[a, b, c]` resides at indices: `2, 1, 0`- /// inside the argument `exprs` (respectively). For the mathematical- /// definition of "partial permutation", see:- ///- /// <https://en.wikipedia.org/wiki/Permutation#k-permutations_of_n>- pub fn find_longest_permutation(- &self,- exprs: &[Arc<dyn PhysicalExpr>],- ) -> (LexOrdering, Vec<usize>) {- let mut eq_properties = self.clone();- let mut result = vec![];- // The algorithm is as follows:- // - Iterate over all the expressions and insert ordered expressions- // into the result.- // - Treat inserted expressions as constants (i.e. add them as constants- // to the state).- // - Continue the above procedure until no expression is inserted; i.e.- // the algorithm reaches a fixed point.- // This algorithm should reach a fixed point in at most `exprs.len()`- // iterations.- let mut search_indices = (0..exprs.len()).collect::<IndexSet<_>>();- for _idx in 0..exprs.len() {- // Get ordered expressions with their indices.- let ordered_exprs = search_indices- .iter()- .flat_map(|&idx| {- let ExprOrdering { expr, state, .. } =- eq_properties.get_expr_ordering(exprs[idx].clone());- if let SortProperties::Ordered(options) = state {- Some((PhysicalSortExpr { expr, options }, idx))- } else {- None- }- })- .collect::<Vec<_>>();- // We reached a fixed point, exit.- if ordered_exprs.is_empty() {- break;- }- // Remove indices that have an ordering from `search_indices`, and- // treat ordered expressions as constants in subsequent iterations.- // We can do this because the "next" key only matters in a lexicographical- // ordering when the keys to its left have the same values.- //- // Note that these expressions are not properly "constants". This is just- // an implementation strategy confined to this function.- for (PhysicalSortExpr { expr, .. }, idx) in &ordered_exprs {- eq_properties =- eq_properties.add_constants(std::iter::once(expr.clone()));- search_indices.remove(idx);- }- // Add new ordered section to the state.- result.extend(ordered_exprs);- }- result.into_iter().unzip()- }-- /// This function determines whether the provided expression is constant- /// based on the known constants.- ///- /// # Arguments- ///- /// - `expr`: A reference to a `Arc<dyn PhysicalExpr>` representing the- /// expression to be checked.- ///- /// # Returns- ///- /// Returns `true` if the expression is constant according to equivalence- /// group, `false` otherwise.- fn is_expr_constant(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {- // As an example, assume that we know columns `a` and `b` are constant.- // Then, `a`, `b` and `a + b` will all return `true` whereas `c` will- // return `false`.- let normalized_constants = self.eq_group.normalize_exprs(self.constants.to_vec());- let normalized_expr = self.eq_group.normalize_expr(expr.clone());- is_constant_recurse(&normalized_constants, &normalized_expr)- }-- /// Retrieves the ordering information for a given physical expression.- ///- /// This function constructs an `ExprOrdering` object for the provided- /// expression, which encapsulates information about the expression's- /// ordering, including its [`SortProperties`].- ///- /// # Arguments- ///- /// - `expr`: An `Arc<dyn PhysicalExpr>` representing the physical expression- /// for which ordering information is sought.- ///- /// # Returns- ///- /// Returns an `ExprOrdering` object containing the ordering information for- /// the given expression.- pub fn get_expr_ordering(&self, expr: Arc<dyn PhysicalExpr>) -> ExprOrdering {- ExprOrdering::new(expr.clone())- .transform_up(&|expr| Ok(update_ordering(expr, self)))- // Guaranteed to always return `Ok`.- .unwrap()- }-}--/// This function determines whether the provided expression is constant-/// based on the known constants.-///-/// # Arguments-///-/// - `constants`: A `&[Arc<dyn PhysicalExpr>]` containing expressions known to-/// be a constant.-/// - `expr`: A reference to a `Arc<dyn PhysicalExpr>` representing the expression-/// to check.-///-/// # Returns-///-/// Returns `true` if the expression is constant according to equivalence-/// group, `false` otherwise.-fn is_constant_recurse(- constants: &[Arc<dyn PhysicalExpr>],- expr: &Arc<dyn PhysicalExpr>,-) -> bool {- if physical_exprs_contains(constants, expr) {- return true;- }- let children = expr.children();- !children.is_empty() && children.iter().all(|c| is_constant_recurse(constants, c))-}--/// This function examines whether a referring expression directly refers to a-/// given referred expression or if any of its children in the expression tree-/// refer to the specified expression.-///-/// # Parameters-///-/// - `referring_expr`: A reference to the referring expression (`Arc<dyn PhysicalExpr>`).-/// - `referred_expr`: A reference to the referred expression (`Arc<dyn PhysicalExpr>`)-///-/// # Returns-///-/// A boolean value indicating whether `referring_expr` refers (needs it to evaluate its result)-/// `referred_expr` or not.-fn expr_refers(- referring_expr: &Arc<dyn PhysicalExpr>,- referred_expr: &Arc<dyn PhysicalExpr>,-) -> bool {- referring_expr.eq(referred_expr)- || referring_expr- .children()- .iter()- .any(|child| expr_refers(child, referred_expr))-}--/// Wrapper struct for `Arc<dyn PhysicalExpr>` to use them as keys in a hash map.-#[derive(Debug, Clone)]-struct ExprWrapper(Arc<dyn PhysicalExpr>);--impl PartialEq<Self> for ExprWrapper {- fn eq(&self, other: &Self) -> bool {- self.0.eq(&other.0)- }-}--impl Eq for ExprWrapper {}--impl Hash for ExprWrapper {- fn hash<H: Hasher>(&self, state: &mut H) {- self.0.hash(state);- }-}--/// This function analyzes the dependency map to collect referred dependencies for-/// a given source expression.-///-/// # Parameters-///-/// - `dependency_map`: A reference to the `DependencyMap` where each-/// `PhysicalSortExpr` is associated with a `DependencyNode`.-/// - `source`: A reference to the source expression (`Arc<dyn PhysicalExpr>`)-/// for which relevant dependencies need to be identified.-///-/// # Returns-///-/// A `Vec<Dependencies>` containing the dependencies for the given source-/// expression. These dependencies are expressions that are referred to by-/// the source expression based on the provided dependency map.-fn referred_dependencies(- dependency_map: &DependencyMap,- source: &Arc<dyn PhysicalExpr>,-) -> Vec<Dependencies> {- // Associate `PhysicalExpr`s with `PhysicalSortExpr`s that contain them:- let mut expr_to_sort_exprs = HashMap::<ExprWrapper, Dependencies>::new();- for sort_expr in dependency_map- .keys()- .filter(|sort_expr| expr_refers(source, &sort_expr.expr))- {- let key = ExprWrapper(sort_expr.expr.clone());- expr_to_sort_exprs- .entry(key)- .or_default()- .insert(sort_expr.clone());- }-- // Generate all valid dependencies for the source. For example, if the source- // is `a + b` and the map is `[a -> (a ASC, a DESC), b -> (b ASC)]`, we get- // `vec![HashSet(a ASC, b ASC), HashSet(a DESC, b ASC)]`.- expr_to_sort_exprs- .values()- .multi_cartesian_product()- .map(|referred_deps| referred_deps.into_iter().cloned().collect())- .collect()-}--/// This function recursively analyzes the dependencies of the given sort-/// expression within the given dependency map to construct lexicographical-/// orderings that include the sort expression and its dependencies.-///-/// # Parameters-///-/// - `referred_sort_expr`: A reference to the sort expression (`PhysicalSortExpr`)-/// for which lexicographical orderings satisfying its dependencies are to be-/// constructed.-/// - `dependency_map`: A reference to the `DependencyMap` that contains-/// dependencies for different `PhysicalSortExpr`s.-///-/// # Returns-///-/// A vector of lexicographical orderings (`Vec<LexOrdering>`) based on the given-/// sort expression and its dependencies.-fn construct_orderings(- referred_sort_expr: &PhysicalSortExpr,- dependency_map: &DependencyMap,-) -> Vec<LexOrdering> {- // We are sure that `referred_sort_expr` is inside `dependency_map`.- let node = &dependency_map[referred_sort_expr];- // Since we work on intermediate nodes, we are sure `val.target_sort_expr`- // exists.- let target_sort_expr = node.target_sort_expr.clone().unwrap();- if node.dependencies.is_empty() {- vec![vec![target_sort_expr]]- } else {- node.dependencies- .iter()- .flat_map(|dep| {- let mut orderings = construct_orderings(dep, dependency_map);- for ordering in orderings.iter_mut() {- ordering.push(target_sort_expr.clone())- }- orderings- })- .collect()- }-}--/// This function retrieves the dependencies of the given relevant sort expression-/// from the given dependency map. It then constructs prefix orderings by recursively-/// analyzing the dependencies and include them in the orderings.-///-/// # Parameters-///-/// - `relevant_sort_expr`: A reference to the relevant sort expression-/// (`PhysicalSortExpr`) for which prefix orderings are to be constructed.-/// - `dependency_map`: A reference to the `DependencyMap` containing dependencies.-///-/// # Returns-///-/// A vector of prefix orderings (`Vec<LexOrdering>`) based on the given relevant-/// sort expression and its dependencies.-fn construct_prefix_orderings(- relevant_sort_expr: &PhysicalSortExpr,- dependency_map: &DependencyMap,-) -> Vec<LexOrdering> {- dependency_map[relevant_sort_expr]- .dependencies- .iter()- .flat_map(|dep| construct_orderings(dep, dependency_map))- .collect()-}--/// Given a set of relevant dependencies (`relevant_deps`) and a map of dependencies-/// (`dependency_map`), this function generates all possible prefix orderings-/// based on the given dependencies.-///-/// # Parameters-///-/// * `dependencies` - A reference to the dependencies.-/// * `dependency_map` - A reference to the map of dependencies for expressions.-///-/// # Returns-///-/// A vector of lexical orderings (`Vec<LexOrdering>`) representing all valid orderings-/// based on the given dependencies.-fn generate_dependency_orderings(- dependencies: &Dependencies,- dependency_map: &DependencyMap,-) -> Vec<LexOrdering> {- // Construct all the valid prefix orderings for each expression appearing- // in the projection:- let relevant_prefixes = dependencies- .iter()- .flat_map(|dep| {- let prefixes = construct_prefix_orderings(dep, dependency_map);- (!prefixes.is_empty()).then_some(prefixes)- })- .collect::<Vec<_>>();-- // No dependency, dependent is a leading ordering.- if relevant_prefixes.is_empty() {- // Return an empty ordering:- return vec![vec![]];- }-- // Generate all possible orderings where dependencies are satisfied for the- // current projection expression. For example, if expression is `a + b ASC`,- // and the dependency for `a ASC` is `[c ASC]`, the dependency for `b ASC`- // is `[d DESC]`, then we generate `[c ASC, d DESC, a + b ASC]` and- // `[d DESC, c ASC, a + b ASC]`.- relevant_prefixes- .into_iter()- .multi_cartesian_product()- .flat_map(|prefix_orderings| {- prefix_orderings- .iter()- .permutations(prefix_orderings.len())- .map(|prefixes| prefixes.into_iter().flatten().cloned().collect())- .collect::<Vec<_>>()- })- .collect()-}--/// This function examines the given expression and the sort expressions it-/// refers to determine the ordering properties of the expression.-///-/// # Parameters-///-/// - `expr`: A reference to the source expression (`Arc<dyn PhysicalExpr>`) for-/// which ordering properties need to be determined.-/// - `dependencies`: A reference to `Dependencies`, containing sort expressions-/// referred to by `expr`.-///-/// # Returns-///-/// A `SortProperties` indicating the ordering information of the given expression.-fn get_expr_ordering(- expr: &Arc<dyn PhysicalExpr>,- dependencies: &Dependencies,-) -> SortProperties {- if let Some(column_order) = dependencies.iter().find(|&order| expr.eq(&order.expr)) {- // If exact match is found, return its ordering.- SortProperties::Ordered(column_order.options)- } else {- // Find orderings of its children- let child_states = expr- .children()- .iter()- .map(|child| get_expr_ordering(child, dependencies))- .collect::<Vec<_>>();- // Calculate expression ordering using ordering of its children.- expr.get_ordering(&child_states)- }-}--/// Represents a node in the dependency map used to construct projected orderings.-///-/// A `DependencyNode` contains information about a particular sort expression,-/// including its target sort expression and a set of dependencies on other sort-/// expressions.-///-/// # Fields-///-/// - `target_sort_expr`: An optional `PhysicalSortExpr` representing the target-/// sort expression associated with the node. It is `None` if the sort expression-/// cannot be projected.-/// - `dependencies`: A [`Dependencies`] containing dependencies on other sort-/// expressions that are referred to by the target sort expression.-#[derive(Debug, Clone, PartialEq, Eq)]-struct DependencyNode {- target_sort_expr: Option<PhysicalSortExpr>,- dependencies: Dependencies,-}--impl DependencyNode {- // Insert dependency to the state (if exists).- fn insert_dependency(&mut self, dependency: Option<&PhysicalSortExpr>) {- if let Some(dep) = dependency {- self.dependencies.insert(dep.clone());- }- }-}--type DependencyMap = HashMap<PhysicalSortExpr, DependencyNode>;-type Dependencies = HashSet<PhysicalSortExpr>;--/// Calculate ordering equivalence properties for the given join operation.-pub fn join_equivalence_properties(- left: EquivalenceProperties,- right: EquivalenceProperties,- join_type: &JoinType,- join_schema: SchemaRef,- maintains_input_order: &[bool],- probe_side: Option<JoinSide>,- on: &[(Column, Column)],-) -> EquivalenceProperties {- let left_size = left.schema.fields.len();- let mut result = EquivalenceProperties::new(join_schema);- result.add_equivalence_group(left.eq_group().join(- right.eq_group(),- join_type,- left_size,- on,- ));-- let left_oeq_class = left.oeq_class;- let mut right_oeq_class = right.oeq_class;- match maintains_input_order {- [true, false] => {- // In this special case, right side ordering can be prefixed with- // the left side ordering.- if let (Some(JoinSide::Left), JoinType::Inner) = (probe_side, join_type) {- updated_right_ordering_equivalence_class(- &mut right_oeq_class,- join_type,- left_size,- );-- // 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.- //- // For example, if the right side ordering equivalences contain- // `b ASC`, and the left side ordering equivalences contain `a ASC`,- // then we should add `a ASC, b ASC` to the ordering equivalences- // of the join output.- let out_oeq_class = left_oeq_class.join_suffix(&right_oeq_class);- result.add_ordering_equivalence_class(out_oeq_class);- } else {- result.add_ordering_equivalence_class(left_oeq_class);- }- }- [false, true] => {- updated_right_ordering_equivalence_class(- &mut right_oeq_class,- join_type,- left_size,- );- // In this special case, left side ordering can be prefixed with- // the right side ordering.- if let (Some(JoinSide::Right), JoinType::Inner) = (probe_side, join_type) {- // 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.- //- // For example, if the left side ordering equivalences contain- // `a ASC`, and the right side ordering equivalences contain `b ASC`,- // then we should add `b ASC, a ASC` to the ordering equivalences- // of the join output.- let out_oeq_class = right_oeq_class.join_suffix(&left_oeq_class);- result.add_ordering_equivalence_class(out_oeq_class);- } else {- result.add_ordering_equivalence_class(right_oeq_class);- }- }- [false, false] => {}- [true, true] => unreachable!("Cannot maintain ordering of both sides"),- _ => unreachable!("Join operators can not have more than two children"),- }- result-}--/// In the context of a join, update the right side `OrderingEquivalenceClass`-/// so that they point to valid indices in the join output schema.-///-/// To do so, we increment column indices by the size of the left table when-/// join schema consists of a combination of the left and right schemas. This-/// is the case for `Inner`, `Left`, `Full` and `Right` joins. For other cases,-/// indices do not change.-fn updated_right_ordering_equivalence_class(- right_oeq_class: &mut OrderingEquivalenceClass,- join_type: &JoinType,- left_size: usize,-) {- if matches!(- join_type,- JoinType::Inner | JoinType::Left | JoinType::Full | JoinType::Right- ) {- right_oeq_class.add_offset(left_size);- }-}--/// Calculates the [`SortProperties`] of a given [`ExprOrdering`] node.-/// The node can either be a leaf node, or an intermediate node:-/// - If it is a leaf node, we directly find the order of the node by looking-/// at the given sort expression and equivalence properties if it is a `Column`-/// leaf, or we mark it as unordered. In the case of a `Literal` leaf, we mark-/// it as singleton so that it can cooperate with all ordered columns.-/// - If it is an intermediate node, the children states matter. Each `PhysicalExpr`-/// and operator has its own rules on how to propagate the children orderings.-/// However, before we engage in recursion, we check whether this intermediate-/// node directly matches with the sort expression. If there is a match, the-/// sort expression emerges at that node immediately, discarding the recursive-/// result coming from its children.-fn update_ordering(- mut node: ExprOrdering,- eq_properties: &EquivalenceProperties,-) -> Transformed<ExprOrdering> {- // We have a Column, which is one of the two possible leaf node types:- let normalized_expr = eq_properties.eq_group.normalize_expr(node.expr.clone());- if eq_properties.is_expr_constant(&normalized_expr) {- node.state = SortProperties::Singleton;- } else if let Some(options) = eq_properties- .normalized_oeq_class()- .get_options(&normalized_expr)- {- node.state = SortProperties::Ordered(options);- } else if !node.expr.children().is_empty() {- // We have an intermediate (non-leaf) node, account for its children:- node.state = node.expr.get_ordering(&node.children_state());- } else if node.expr.as_any().is::<Literal>() {- // We have a Literal, which is the other possible leaf node type:- node.state = node.expr.get_ordering(&[]);- } else {- return Transformed::No(node);- }- Transformed::Yes(node)-}--#[cfg(test)]-mod tests {- use std::ops::Not;- use std::sync::Arc;-- use super::*;- use crate::execution_props::ExecutionProps;- use crate::expressions::{col, lit, BinaryExpr, Column, Literal};- use crate::functions::create_physical_expr;-- use arrow::compute::{lexsort_to_indices, SortColumn};- use arrow::datatypes::{DataType, Field, Schema};- use arrow_array::{ArrayRef, Float64Array, RecordBatch, UInt32Array};- use arrow_schema::{Fields, SortOptions, TimeUnit};- use datafusion_common::{plan_datafusion_err, DataFusionError, Result, ScalarValue};- use datafusion_expr::{BuiltinScalarFunction, Operator};-- use itertools::{izip, Itertools};- use rand::rngs::StdRng;- use rand::seq::SliceRandom;- use rand::{Rng, SeedableRng};-- fn output_schema(- mapping: &ProjectionMapping,- input_schema: &Arc<Schema>,- ) -> Result<SchemaRef> {- // Calculate output schema- let fields: Result<Vec<Field>> = mapping- .iter()- .map(|(source, target)| {- let name = target- .as_any()- .downcast_ref::<Column>()- .ok_or_else(|| plan_datafusion_err!("Expects to have column"))?- .name();- let field = Field::new(- name,- source.data_type(input_schema)?,- source.nullable(input_schema)?,- );-- Ok(field)- })- .collect();-- let output_schema = Arc::new(Schema::new_with_metadata(- fields?,- input_schema.metadata().clone(),- ));-- Ok(output_schema)- }-- // Generate a schema which consists of 8 columns (a, b, c, d, e, f, g, h)- fn create_test_schema() -> Result<SchemaRef> {- let a = Field::new("a", DataType::Int32, true);- let b = Field::new("b", DataType::Int32, true);- let c = Field::new("c", DataType::Int32, true);- let d = Field::new("d", DataType::Int32, true);- let e = Field::new("e", DataType::Int32, true);- let f = Field::new("f", DataType::Int32, true);- let g = Field::new("g", DataType::Int32, true);- let h = Field::new("h", DataType::Int32, true);- let schema = Arc::new(Schema::new(vec![a, b, c, d, e, f, g, h]));-- Ok(schema)- }-- /// Construct a schema with following properties- /// Schema satisfies following orderings:- /// [a ASC], [d ASC, b ASC], [e DESC, f ASC, g ASC]- /// and- /// Column [a=c] (e.g they are aliases).- fn create_test_params() -> Result<(SchemaRef, EquivalenceProperties)> {- let test_schema = create_test_schema()?;- let col_a = &col("a", &test_schema)?;- let col_b = &col("b", &test_schema)?;- let col_c = &col("c", &test_schema)?;- let col_d = &col("d", &test_schema)?;- let col_e = &col("e", &test_schema)?;- let col_f = &col("f", &test_schema)?;- let col_g = &col("g", &test_schema)?;- let mut eq_properties = EquivalenceProperties::new(test_schema.clone());- eq_properties.add_equal_conditions(col_a, col_c);-- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- let option_desc = SortOptions {- descending: true,- nulls_first: true,- };- let orderings = vec![- // [a ASC]- vec![(col_a, option_asc)],- // [d ASC, b ASC]- vec![(col_d, option_asc), (col_b, option_asc)],- // [e DESC, f ASC, g ASC]- vec![- (col_e, option_desc),- (col_f, option_asc),- (col_g, option_asc),- ],- ];- let orderings = convert_to_orderings(&orderings);- eq_properties.add_new_orderings(orderings);- Ok((test_schema, eq_properties))- }-- // Generate a schema which consists of 6 columns (a, b, c, d, e, f)- fn create_test_schema_2() -> Result<SchemaRef> {- let a = Field::new("a", DataType::Float64, true);- let b = Field::new("b", DataType::Float64, true);- let c = Field::new("c", DataType::Float64, true);- let d = Field::new("d", DataType::Float64, true);- let e = Field::new("e", DataType::Float64, true);- let f = Field::new("f", DataType::Float64, true);- let schema = Arc::new(Schema::new(vec![a, b, c, d, e, f]));-- Ok(schema)- }-- /// Construct a schema with random ordering- /// among column a, b, c, d- /// where- /// Column [a=f] (e.g they are aliases).- /// Column e is constant.- fn create_random_schema(seed: u64) -> Result<(SchemaRef, EquivalenceProperties)> {- let test_schema = create_test_schema_2()?;- let col_a = &col("a", &test_schema)?;- let col_b = &col("b", &test_schema)?;- let col_c = &col("c", &test_schema)?;- let col_d = &col("d", &test_schema)?;- let col_e = &col("e", &test_schema)?;- let col_f = &col("f", &test_schema)?;- let col_exprs = [col_a, col_b, col_c, col_d, col_e, col_f];-- let mut eq_properties = EquivalenceProperties::new(test_schema.clone());- // Define a and f are aliases- eq_properties.add_equal_conditions(col_a, col_f);- // Column e has constant value.- eq_properties = eq_properties.add_constants([col_e.clone()]);-- // Randomly order columns for sorting- let mut rng = StdRng::seed_from_u64(seed);- let mut remaining_exprs = col_exprs[0..4].to_vec(); // only a, b, c, d are sorted-- let options_asc = SortOptions {- descending: false,- nulls_first: false,- };-- while !remaining_exprs.is_empty() {- let n_sort_expr = rng.gen_range(0..remaining_exprs.len() + 1);- remaining_exprs.shuffle(&mut rng);-- let ordering = remaining_exprs- .drain(0..n_sort_expr)- .map(|expr| PhysicalSortExpr {- expr: expr.clone(),- options: options_asc,- })- .collect();-- eq_properties.add_new_orderings([ordering]);- }-- Ok((test_schema, eq_properties))- }-- // Convert each tuple to PhysicalSortRequirement- fn convert_to_sort_reqs(- in_data: &[(&Arc<dyn PhysicalExpr>, Option<SortOptions>)],- ) -> Vec<PhysicalSortRequirement> {- in_data- .iter()- .map(|(expr, options)| {- PhysicalSortRequirement::new((*expr).clone(), *options)- })- .collect()- }-- // Convert each tuple to PhysicalSortExpr- fn convert_to_sort_exprs(- in_data: &[(&Arc<dyn PhysicalExpr>, SortOptions)],- ) -> Vec<PhysicalSortExpr> {- in_data- .iter()- .map(|(expr, options)| PhysicalSortExpr {- expr: (*expr).clone(),- options: *options,- })- .collect()- }-- // Convert each inner tuple to PhysicalSortExpr- fn convert_to_orderings(- orderings: &[Vec<(&Arc<dyn PhysicalExpr>, SortOptions)>],- ) -> Vec<Vec<PhysicalSortExpr>> {- orderings- .iter()- .map(|sort_exprs| convert_to_sort_exprs(sort_exprs))- .collect()- }-- // Convert each tuple to PhysicalSortExpr- fn convert_to_sort_exprs_owned(- in_data: &[(Arc<dyn PhysicalExpr>, SortOptions)],- ) -> Vec<PhysicalSortExpr> {- in_data- .iter()- .map(|(expr, options)| PhysicalSortExpr {- expr: (*expr).clone(),- options: *options,- })- .collect()- }-- // Convert each inner tuple to PhysicalSortExpr- fn convert_to_orderings_owned(- orderings: &[Vec<(Arc<dyn PhysicalExpr>, SortOptions)>],- ) -> Vec<Vec<PhysicalSortExpr>> {- orderings- .iter()- .map(|sort_exprs| convert_to_sort_exprs_owned(sort_exprs))- .collect()- }-- // Apply projection to the input_data, return projected equivalence properties and record batch- fn apply_projection(- proj_exprs: Vec<(Arc<dyn PhysicalExpr>, String)>,- input_data: &RecordBatch,- input_eq_properties: &EquivalenceProperties,- ) -> Result<(RecordBatch, EquivalenceProperties)> {- let input_schema = input_data.schema();- let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &input_schema)?;-- let output_schema = output_schema(&projection_mapping, &input_schema)?;- let num_rows = input_data.num_rows();- // Apply projection to the input record batch.- let projected_values = projection_mapping- .iter()- .map(|(source, _target)| source.evaluate(input_data)?.into_array(num_rows))- .collect::<Result<Vec<_>>>()?;- let projected_batch = if projected_values.is_empty() {- RecordBatch::new_empty(output_schema.clone())- } else {- RecordBatch::try_new(output_schema.clone(), projected_values)?- };-- let projected_eq =- input_eq_properties.project(&projection_mapping, output_schema);- Ok((projected_batch, projected_eq))- }-- #[test]- fn add_equal_conditions_test() -> Result<()> {- let schema = Arc::new(Schema::new(vec![- Field::new("a", DataType::Int64, true),- Field::new("b", DataType::Int64, true),- Field::new("c", DataType::Int64, true),- Field::new("x", DataType::Int64, true),- Field::new("y", DataType::Int64, true),- ]));-- let mut eq_properties = EquivalenceProperties::new(schema);- let col_a_expr = Arc::new(Column::new("a", 0)) as Arc<dyn PhysicalExpr>;- let col_b_expr = Arc::new(Column::new("b", 1)) as Arc<dyn PhysicalExpr>;- let col_c_expr = Arc::new(Column::new("c", 2)) as Arc<dyn PhysicalExpr>;- let col_x_expr = Arc::new(Column::new("x", 3)) as Arc<dyn PhysicalExpr>;- let col_y_expr = Arc::new(Column::new("y", 4)) as Arc<dyn PhysicalExpr>;-- // a and b are aliases- eq_properties.add_equal_conditions(&col_a_expr, &col_b_expr);- assert_eq!(eq_properties.eq_group().len(), 1);-- // This new entry is redundant, size shouldn't increase- eq_properties.add_equal_conditions(&col_b_expr, &col_a_expr);- assert_eq!(eq_properties.eq_group().len(), 1);- let eq_groups = &eq_properties.eq_group().classes[0];- assert_eq!(eq_groups.len(), 2);- assert!(eq_groups.contains(&col_a_expr));- assert!(eq_groups.contains(&col_b_expr));-- // b and c are aliases. Exising equivalence class should expand,- // however there shouldn't be any new equivalence class- eq_properties.add_equal_conditions(&col_b_expr, &col_c_expr);- assert_eq!(eq_properties.eq_group().len(), 1);- let eq_groups = &eq_properties.eq_group().classes[0];- assert_eq!(eq_groups.len(), 3);- assert!(eq_groups.contains(&col_a_expr));- assert!(eq_groups.contains(&col_b_expr));- assert!(eq_groups.contains(&col_c_expr));-- // This is a new set of equality. Hence equivalent class count should be 2.- eq_properties.add_equal_conditions(&col_x_expr, &col_y_expr);- assert_eq!(eq_properties.eq_group().len(), 2);-- // This equality bridges distinct equality sets.- // Hence equivalent class count should decrease from 2 to 1.- eq_properties.add_equal_conditions(&col_x_expr, &col_a_expr);- assert_eq!(eq_properties.eq_group().len(), 1);- let eq_groups = &eq_properties.eq_group().classes[0];- assert_eq!(eq_groups.len(), 5);- assert!(eq_groups.contains(&col_a_expr));- assert!(eq_groups.contains(&col_b_expr));- assert!(eq_groups.contains(&col_c_expr));- assert!(eq_groups.contains(&col_x_expr));- assert!(eq_groups.contains(&col_y_expr));-- Ok(())- }-- #[test]- fn project_equivalence_properties_test() -> Result<()> {- let input_schema = Arc::new(Schema::new(vec![- Field::new("a", DataType::Int64, true),- Field::new("b", DataType::Int64, true),- Field::new("c", DataType::Int64, true),- ]));-- let input_properties = EquivalenceProperties::new(input_schema.clone());- let col_a = col("a", &input_schema)?;-- // a as a1, a as a2, a as a3, a as a3- let proj_exprs = vec![- (col_a.clone(), "a1".to_string()),- (col_a.clone(), "a2".to_string()),- (col_a.clone(), "a3".to_string()),- (col_a.clone(), "a4".to_string()),- ];- let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &input_schema)?;-- let out_schema = output_schema(&projection_mapping, &input_schema)?;- // a as a1, a as a2, a as a3, a as a3- let proj_exprs = vec![- (col_a.clone(), "a1".to_string()),- (col_a.clone(), "a2".to_string()),- (col_a.clone(), "a3".to_string()),- (col_a.clone(), "a4".to_string()),- ];- let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &input_schema)?;-- // a as a1, a as a2, a as a3, a as a3- let col_a1 = &col("a1", &out_schema)?;- let col_a2 = &col("a2", &out_schema)?;- let col_a3 = &col("a3", &out_schema)?;- let col_a4 = &col("a4", &out_schema)?;- let out_properties = input_properties.project(&projection_mapping, out_schema);-- // At the output a1=a2=a3=a4- assert_eq!(out_properties.eq_group().len(), 1);- let eq_class = &out_properties.eq_group().classes[0];- assert_eq!(eq_class.len(), 4);- assert!(eq_class.contains(col_a1));- assert!(eq_class.contains(col_a2));- assert!(eq_class.contains(col_a3));- assert!(eq_class.contains(col_a4));-- Ok(())- }-- #[test]- fn test_ordering_satisfy() -> Result<()> {- let input_schema = Arc::new(Schema::new(vec![- Field::new("a", DataType::Int64, true),- Field::new("b", DataType::Int64, true),- ]));- let crude = vec![PhysicalSortExpr {- expr: Arc::new(Column::new("a", 0)),- options: SortOptions::default(),- }];- let finer = vec![- PhysicalSortExpr {- expr: Arc::new(Column::new("a", 0)),- options: SortOptions::default(),- },- PhysicalSortExpr {- expr: Arc::new(Column::new("b", 1)),- options: SortOptions::default(),- },- ];- // finer ordering satisfies, crude ordering should return true- let mut eq_properties_finer = EquivalenceProperties::new(input_schema.clone());- eq_properties_finer.oeq_class.push(finer.clone());- assert!(eq_properties_finer.ordering_satisfy(&crude));-- // Crude ordering doesn't satisfy finer ordering. should return false- let mut eq_properties_crude = EquivalenceProperties::new(input_schema.clone());- eq_properties_crude.oeq_class.push(crude.clone());- assert!(!eq_properties_crude.ordering_satisfy(&finer));- Ok(())- }-- #[test]- fn test_ordering_satisfy_with_equivalence() -> Result<()> {- // Schema satisfies following orderings:- // [a ASC], [d ASC, b ASC], [e DESC, f ASC, g ASC]- // and- // Column [a=c] (e.g they are aliases).- let (test_schema, eq_properties) = create_test_params()?;- let col_a = &col("a", &test_schema)?;- let col_b = &col("b", &test_schema)?;- let col_c = &col("c", &test_schema)?;- let col_d = &col("d", &test_schema)?;- let col_e = &col("e", &test_schema)?;- let col_f = &col("f", &test_schema)?;- let col_g = &col("g", &test_schema)?;- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- let option_desc = SortOptions {- descending: true,- nulls_first: true,- };- let table_data_with_properties =- generate_table_for_eq_properties(&eq_properties, 625, 5)?;-- // First element in the tuple stores vector of requirement, second element is the expected return value for ordering_satisfy function- let requirements = vec![- // `a ASC NULLS LAST`, expects `ordering_satisfy` to be `true`, since existing ordering `a ASC NULLS LAST, b ASC NULLS LAST` satisfies it- (vec![(col_a, option_asc)], true),- (vec![(col_a, option_desc)], false),- // Test whether equivalence works as expected- (vec![(col_c, option_asc)], true),- (vec![(col_c, option_desc)], false),- // Test whether ordering equivalence works as expected- (vec![(col_d, option_asc)], true),- (vec![(col_d, option_asc), (col_b, option_asc)], true),- (vec![(col_d, option_desc), (col_b, option_asc)], false),- (- vec![- (col_e, option_desc),- (col_f, option_asc),- (col_g, option_asc),- ],- true,- ),- (vec![(col_e, option_desc), (col_f, option_asc)], true),- (vec![(col_e, option_asc), (col_f, option_asc)], false),- (vec![(col_e, option_desc), (col_b, option_asc)], false),- (vec![(col_e, option_asc), (col_b, option_asc)], false),- (- vec![- (col_d, option_asc),- (col_b, option_asc),- (col_d, option_asc),- (col_b, option_asc),- ],- true,- ),- (- vec![- (col_d, option_asc),- (col_b, option_asc),- (col_e, option_desc),- (col_f, option_asc),- ],- true,- ),- (- vec![- (col_d, option_asc),- (col_b, option_asc),- (col_e, option_desc),- (col_b, option_asc),- ],- true,- ),- (- vec![- (col_d, option_asc),- (col_b, option_asc),- (col_d, option_desc),- (col_b, option_asc),- ],- true,- ),- (- vec![- (col_d, option_asc),- (col_b, option_asc),- (col_e, option_asc),- (col_f, option_asc),- ],- false,- ),- (- vec![- (col_d, option_asc),- (col_b, option_asc),- (col_e, option_asc),- (col_b, option_asc),- ],- false,- ),- (vec![(col_d, option_asc), (col_e, option_desc)], true),- (- vec![- (col_d, option_asc),- (col_c, option_asc),- (col_b, option_asc),- ],- true,- ),- (- vec![- (col_d, option_asc),- (col_e, option_desc),- (col_f, option_asc),- (col_b, option_asc),- ],- true,- ),- (- vec![- (col_d, option_asc),- (col_e, option_desc),- (col_c, option_asc),- (col_b, option_asc),- ],- true,- ),- (- vec![- (col_d, option_asc),- (col_e, option_desc),- (col_b, option_asc),- (col_f, option_asc),- ],- true,- ),- ];-- for (cols, expected) in requirements {- let err_msg = format!("Error in test case:{cols:?}");- let required = cols- .into_iter()- .map(|(expr, options)| PhysicalSortExpr {- expr: expr.clone(),- options,- })- .collect::<Vec<_>>();-- // Check expected result with experimental result.- assert_eq!(- is_table_same_after_sort(- required.clone(),- table_data_with_properties.clone()- )?,- expected- );- assert_eq!(- eq_properties.ordering_satisfy(&required),- expected,- "{err_msg}"- );- }- Ok(())- }-- #[test]- fn test_ordering_satisfy_with_equivalence2() -> Result<()> {- let test_schema = create_test_schema()?;- let col_a = &col("a", &test_schema)?;- let col_b = &col("b", &test_schema)?;- let col_c = &col("c", &test_schema)?;- let col_d = &col("d", &test_schema)?;- let col_e = &col("e", &test_schema)?;- let col_f = &col("f", &test_schema)?;- let floor_a = &create_physical_expr(- &BuiltinScalarFunction::Floor,- &[col("a", &test_schema)?],- &test_schema,- &ExecutionProps::default(),- )?;- let floor_f = &create_physical_expr(- &BuiltinScalarFunction::Floor,- &[col("f", &test_schema)?],- &test_schema,- &ExecutionProps::default(),- )?;- let exp_a = &create_physical_expr(- &BuiltinScalarFunction::Exp,- &[col("a", &test_schema)?],- &test_schema,- &ExecutionProps::default(),- )?;- let a_plus_b = Arc::new(BinaryExpr::new(- col_a.clone(),- Operator::Plus,- col_b.clone(),- )) as Arc<dyn PhysicalExpr>;- let options = SortOptions {- descending: false,- nulls_first: false,- };-- let test_cases = vec![- // ------------ TEST CASE 1 ------------- (- // orderings- vec![- // [a ASC, d ASC, b ASC]- vec![(col_a, options), (col_d, options), (col_b, options)],- // [c ASC]- vec![(col_c, options)],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [a ASC, b ASC], requirement is not satisfied.- vec![(col_a, options), (col_b, options)],- // expected: requirement is not satisfied.- false,- ),- // ------------ TEST CASE 2 ------------- (- // orderings- vec![- // [a ASC, c ASC, b ASC]- vec![(col_a, options), (col_c, options), (col_b, options)],- // [d ASC]- vec![(col_d, options)],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [floor(a) ASC],- vec![(floor_a, options)],- // expected: requirement is satisfied.- true,- ),- // ------------ TEST CASE 2.1 ------------- (- // orderings- vec![- // [a ASC, c ASC, b ASC]- vec![(col_a, options), (col_c, options), (col_b, options)],- // [d ASC]- vec![(col_d, options)],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [floor(f) ASC], (Please note that a=f)- vec![(floor_f, options)],- // expected: requirement is satisfied.- true,- ),- // ------------ TEST CASE 3 ------------- (- // orderings- vec![- // [a ASC, c ASC, b ASC]- vec![(col_a, options), (col_c, options), (col_b, options)],- // [d ASC]- vec![(col_d, options)],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [a ASC, c ASC, a+b ASC],- vec![(col_a, options), (col_c, options), (&a_plus_b, options)],- // expected: requirement is satisfied.- true,- ),- // ------------ TEST CASE 4 ------------- (- // orderings- vec![- // [a ASC, b ASC, c ASC, d ASC]- vec![- (col_a, options),- (col_b, options),- (col_c, options),- (col_d, options),- ],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [floor(a) ASC, a+b ASC],- vec![(floor_a, options), (&a_plus_b, options)],- // expected: requirement is satisfied.- false,- ),- // ------------ TEST CASE 5 ------------- (- // orderings- vec![- // [a ASC, b ASC, c ASC, d ASC]- vec![- (col_a, options),- (col_b, options),- (col_c, options),- (col_d, options),- ],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [exp(a) ASC, a+b ASC],- vec![(exp_a, options), (&a_plus_b, options)],- // expected: requirement is not satisfied.- // TODO: If we know that exp function is 1-to-1 function.- // we could have deduced that above requirement is satisfied.- false,- ),- // ------------ TEST CASE 6 ------------- (- // orderings- vec![- // [a ASC, d ASC, b ASC]- vec![(col_a, options), (col_d, options), (col_b, options)],- // [c ASC]- vec![(col_c, options)],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [a ASC, d ASC, floor(a) ASC],- vec![(col_a, options), (col_d, options), (floor_a, options)],- // expected: requirement is satisfied.- true,- ),- // ------------ TEST CASE 7 ------------- (- // orderings- vec![- // [a ASC, c ASC, b ASC]- vec![(col_a, options), (col_c, options), (col_b, options)],- // [d ASC]- vec![(col_d, options)],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [a ASC, floor(a) ASC, a + b ASC],- vec![(col_a, options), (floor_a, options), (&a_plus_b, options)],- // expected: requirement is not satisfied.- false,- ),- // ------------ TEST CASE 8 ------------- (- // orderings- vec![- // [a ASC, b ASC, c ASC]- vec![(col_a, options), (col_b, options), (col_c, options)],- // [d ASC]- vec![(col_d, options)],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [a ASC, c ASC, floor(a) ASC, a + b ASC],- vec![- (col_a, options),- (col_c, options),- (&floor_a, options),- (&a_plus_b, options),- ],- // expected: requirement is not satisfied.- false,- ),- // ------------ TEST CASE 9 ------------- (- // orderings- vec![- // [a ASC, b ASC, c ASC, d ASC]- vec![- (col_a, options),- (col_b, options),- (col_c, options),- (col_d, options),- ],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [a ASC, b ASC, c ASC, floor(a) ASC],- vec![- (col_a, options),- (col_b, options),- (&col_c, options),- (&floor_a, options),- ],- // expected: requirement is satisfied.- true,- ),- // ------------ TEST CASE 10 ------------- (- // orderings- vec![- // [d ASC, b ASC]- vec![(col_d, options), (col_b, options)],- // [c ASC, a ASC]- vec![(col_c, options), (col_a, options)],- ],- // equivalence classes- vec![vec![col_a, col_f]],- // constants- vec![col_e],- // requirement [c ASC, d ASC, a + b ASC],- vec![(col_c, options), (col_d, options), (&a_plus_b, options)],- // expected: requirement is satisfied.- true,- ),- ];-- for (orderings, eq_group, constants, reqs, expected) in test_cases {- let err_msg =- format!("error in test orderings: {orderings:?}, eq_group: {eq_group:?}, constants: {constants:?}, reqs: {reqs:?}, expected: {expected:?}");- let mut eq_properties = EquivalenceProperties::new(test_schema.clone());- let orderings = convert_to_orderings(&orderings);- eq_properties.add_new_orderings(orderings);- let eq_group = eq_group- .into_iter()- .map(|eq_class| {- let eq_classes = eq_class.into_iter().cloned().collect::<Vec<_>>();- EquivalenceClass::new(eq_classes)- })- .collect::<Vec<_>>();- let eq_group = EquivalenceGroup::new(eq_group);- eq_properties.add_equivalence_group(eq_group);-- let constants = constants.into_iter().cloned();- eq_properties = eq_properties.add_constants(constants);-- let reqs = convert_to_sort_exprs(&reqs);- assert_eq!(- eq_properties.ordering_satisfy(&reqs),- expected,- "{}",- err_msg- );- }-- Ok(())- }-- #[test]- fn test_ordering_satisfy_with_equivalence_random() -> Result<()> {- const N_RANDOM_SCHEMA: usize = 5;- const N_ELEMENTS: usize = 125;- const N_DISTINCT: usize = 5;- const SORT_OPTIONS: SortOptions = SortOptions {- descending: false,- nulls_first: false,- };-- for seed in 0..N_RANDOM_SCHEMA {- // Create a random schema with random properties- let (test_schema, eq_properties) = create_random_schema(seed as u64)?;- // Generate a data that satisfies properties given- let table_data_with_properties =- generate_table_for_eq_properties(&eq_properties, N_ELEMENTS, N_DISTINCT)?;- let col_exprs = vec![- col("a", &test_schema)?,- col("b", &test_schema)?,- col("c", &test_schema)?,- col("d", &test_schema)?,- col("e", &test_schema)?,- col("f", &test_schema)?,- ];-- for n_req in 0..=col_exprs.len() {- for exprs in col_exprs.iter().combinations(n_req) {- let requirement = exprs- .into_iter()- .map(|expr| PhysicalSortExpr {- expr: expr.clone(),- options: SORT_OPTIONS,- })- .collect::<Vec<_>>();- let expected = is_table_same_after_sort(- requirement.clone(),- table_data_with_properties.clone(),- )?;- let err_msg = format!(- "Error in test case requirement:{:?}, expected: {:?}, eq_properties.oeq_class: {:?}, eq_properties.eq_group: {:?}, eq_properties.constants: {:?}",- requirement, expected, eq_properties.oeq_class, eq_properties.eq_group, eq_properties.constants- );- // Check whether ordering_satisfy API result and- // experimental result matches.- assert_eq!(- eq_properties.ordering_satisfy(&requirement),- expected,- "{}",- err_msg- );- }- }- }-- Ok(())- }-- #[test]- fn test_ordering_satisfy_with_equivalence_complex_random() -> Result<()> {- const N_RANDOM_SCHEMA: usize = 100;- const N_ELEMENTS: usize = 125;- const N_DISTINCT: usize = 5;- const SORT_OPTIONS: SortOptions = SortOptions {- descending: false,- nulls_first: false,- };-- for seed in 0..N_RANDOM_SCHEMA {- // Create a random schema with random properties- let (test_schema, eq_properties) = create_random_schema(seed as u64)?;- // Generate a data that satisfies properties given- let table_data_with_properties =- generate_table_for_eq_properties(&eq_properties, N_ELEMENTS, N_DISTINCT)?;-- let floor_a = create_physical_expr(- &BuiltinScalarFunction::Floor,- &[col("a", &test_schema)?],- &test_schema,- &ExecutionProps::default(),- )?;- let a_plus_b = Arc::new(BinaryExpr::new(- col("a", &test_schema)?,- Operator::Plus,- col("b", &test_schema)?,- )) as Arc<dyn PhysicalExpr>;- let exprs = vec![- col("a", &test_schema)?,- col("b", &test_schema)?,- col("c", &test_schema)?,- col("d", &test_schema)?,- col("e", &test_schema)?,- col("f", &test_schema)?,- floor_a,- a_plus_b,- ];-- for n_req in 0..=exprs.len() {- for exprs in exprs.iter().combinations(n_req) {- let requirement = exprs- .into_iter()- .map(|expr| PhysicalSortExpr {- expr: expr.clone(),- options: SORT_OPTIONS,- })- .collect::<Vec<_>>();- let expected = is_table_same_after_sort(- requirement.clone(),- table_data_with_properties.clone(),- )?;- let err_msg = format!(- "Error in test case requirement:{:?}, expected: {:?}, eq_properties.oeq_class: {:?}, eq_properties.eq_group: {:?}, eq_properties.constants: {:?}",- requirement, expected, eq_properties.oeq_class, eq_properties.eq_group, eq_properties.constants- );- // Check whether ordering_satisfy API result and- // experimental result matches.-- assert_eq!(- eq_properties.ordering_satisfy(&requirement),- (expected | false),- "{}",- err_msg- );- }- }- }-- Ok(())- }-- #[test]- fn test_ordering_satisfy_different_lengths() -> Result<()> {- let test_schema = create_test_schema()?;- let col_a = &col("a", &test_schema)?;- let col_b = &col("b", &test_schema)?;- let col_c = &col("c", &test_schema)?;- let col_d = &col("d", &test_schema)?;- let col_e = &col("e", &test_schema)?;- let col_f = &col("f", &test_schema)?;- let options = SortOptions {- descending: false,- nulls_first: false,- };- // a=c (e.g they are aliases).- let mut eq_properties = EquivalenceProperties::new(test_schema);- eq_properties.add_equal_conditions(col_a, col_c);-- let orderings = vec![- vec![(col_a, options)],- vec![(col_e, options)],- vec![(col_d, options), (col_f, options)],- ];- let orderings = convert_to_orderings(&orderings);-- // Column [a ASC], [e ASC], [d ASC, f ASC] are all valid orderings for the schema.- eq_properties.add_new_orderings(orderings);-- // First entry in the tuple is required ordering, second entry is the expected flag- // that indicates whether this required ordering is satisfied.- // ([a ASC], true) indicate a ASC requirement is already satisfied by existing orderings.- let test_cases = vec![- // [c ASC, a ASC, e ASC], expected represents this requirement is satisfied- (- vec![(col_c, options), (col_a, options), (col_e, options)],- true,- ),- (vec![(col_c, options), (col_b, options)], false),- (vec![(col_c, options), (col_d, options)], true),- (- vec![(col_d, options), (col_f, options), (col_b, options)],- false,- ),- (vec![(col_d, options), (col_f, options)], true),- ];-- for (reqs, expected) in test_cases {- let err_msg =- format!("error in test reqs: {:?}, expected: {:?}", reqs, expected,);- let reqs = convert_to_sort_exprs(&reqs);- assert_eq!(- eq_properties.ordering_satisfy(&reqs),- expected,- "{}",- err_msg- );- }-- Ok(())- }-- #[test]- fn test_bridge_groups() -> Result<()> {- // First entry in the tuple is argument, second entry is the bridged result- let test_cases = vec![- // ------- TEST CASE 1 -----------//- (- vec![vec![1, 2, 3], vec![2, 4, 5], vec![11, 12, 9], vec![7, 6, 5]],- // Expected is compared with set equality. Order of the specific results may change.- vec![vec![1, 2, 3, 4, 5, 6, 7], vec![9, 11, 12]],- ),- // ------- TEST CASE 2 -----------//- (- vec![vec![1, 2, 3], vec![3, 4, 5], vec![9, 8, 7], vec![7, 6, 5]],- // Expected- vec![vec![1, 2, 3, 4, 5, 6, 7, 8, 9]],- ),- ];- for (entries, expected) in test_cases {- let entries = entries- .into_iter()- .map(|entry| entry.into_iter().map(lit).collect::<Vec<_>>())- .map(EquivalenceClass::new)- .collect::<Vec<_>>();- let expected = expected- .into_iter()- .map(|entry| entry.into_iter().map(lit).collect::<Vec<_>>())- .map(EquivalenceClass::new)- .collect::<Vec<_>>();- let mut eq_groups = EquivalenceGroup::new(entries.clone());- eq_groups.bridge_classes();- let eq_groups = eq_groups.classes;- let err_msg = format!(- "error in test entries: {:?}, expected: {:?}, actual:{:?}",- entries, expected, eq_groups- );- assert_eq!(eq_groups.len(), expected.len(), "{}", err_msg);- for idx in 0..eq_groups.len() {- assert_eq!(&eq_groups[idx], &expected[idx], "{}", err_msg);- }- }- Ok(())- }-- #[test]- fn test_remove_redundant_entries_eq_group() -> Result<()> {- let entries = vec![- EquivalenceClass::new(vec![lit(1), lit(1), lit(2)]),- // This group is meaningless should be removed- EquivalenceClass::new(vec![lit(3), lit(3)]),- EquivalenceClass::new(vec![lit(4), lit(5), lit(6)]),- ];- // Given equivalences classes are not in succinct form.- // Expected form is the most plain representation that is functionally same.- let expected = vec![- EquivalenceClass::new(vec![lit(1), lit(2)]),- EquivalenceClass::new(vec![lit(4), lit(5), lit(6)]),- ];- let mut eq_groups = EquivalenceGroup::new(entries);- eq_groups.remove_redundant_entries();-- let eq_groups = eq_groups.classes;- assert_eq!(eq_groups.len(), expected.len());- assert_eq!(eq_groups.len(), 2);-- assert_eq!(eq_groups[0], expected[0]);- assert_eq!(eq_groups[1], expected[1]);- Ok(())- }-- #[test]- fn test_remove_redundant_entries_oeq_class() -> Result<()> {- let schema = create_test_schema()?;- let col_a = &col("a", &schema)?;- let col_b = &col("b", &schema)?;- let col_c = &col("c", &schema)?;- let col_d = &col("d", &schema)?;- let col_e = &col("e", &schema)?;-- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- let option_desc = SortOptions {- descending: true,- nulls_first: true,- };-- // First entry in the tuple is the given orderings for the table- // Second entry is the simplest version of the given orderings that is functionally equivalent.- let test_cases = vec![- // ------- TEST CASE 1 ---------- (- // ORDERINGS GIVEN- vec![- // [a ASC, b ASC]- vec![(col_a, option_asc), (col_b, option_asc)],- ],- // EXPECTED orderings that is succinct.- vec![- // [a ASC, b ASC]- vec![(col_a, option_asc), (col_b, option_asc)],- ],- ),- // ------- TEST CASE 2 ---------- (- // ORDERINGS GIVEN- vec![- // [a ASC, b ASC]- vec![(col_a, option_asc), (col_b, option_asc)],- // [a ASC, b ASC, c ASC]- vec![- (col_a, option_asc),- (col_b, option_asc),- (col_c, option_asc),- ],- ],- // EXPECTED orderings that is succinct.- vec![- // [a ASC, b ASC, c ASC]- vec![- (col_a, option_asc),- (col_b, option_asc),- (col_c, option_asc),- ],- ],- ),- // ------- TEST CASE 3 ---------- (- // ORDERINGS GIVEN- vec![- // [a ASC, b DESC]- vec![(col_a, option_asc), (col_b, option_desc)],- // [a ASC]- vec![(col_a, option_asc)],- // [a ASC, c ASC]- vec![(col_a, option_asc), (col_c, option_asc)],- ],- // EXPECTED orderings that is succinct.- vec![- // [a ASC, b DESC]- vec![(col_a, option_asc), (col_b, option_desc)],- // [a ASC, c ASC]- vec![(col_a, option_asc), (col_c, option_asc)],- ],- ),- // ------- TEST CASE 4 ---------- (- // ORDERINGS GIVEN- vec![- // [a ASC, b ASC]- vec![(col_a, option_asc), (col_b, option_asc)],- // [a ASC, b ASC, c ASC]- vec![- (col_a, option_asc),- (col_b, option_asc),- (col_c, option_asc),- ],- // [a ASC]- vec![(col_a, option_asc)],- ],- // EXPECTED orderings that is succinct.- vec![- // [a ASC, b ASC, c ASC]- vec![- (col_a, option_asc),- (col_b, option_asc),- (col_c, option_asc),- ],- ],- ),- // ------- TEST CASE 5 ---------- // Empty ordering- (- vec![vec![]],- // No ordering in the state (empty ordering is ignored).- vec![],- ),- // ------- TEST CASE 6 ---------- (- // ORDERINGS GIVEN- vec![- // [a ASC, b ASC]- vec![(col_a, option_asc), (col_b, option_asc)],- // [b ASC]- vec![(col_b, option_asc)],- ],- // EXPECTED orderings that is succinct.- vec![- // [a ASC]- vec![(col_a, option_asc)],- // [b ASC]- vec![(col_b, option_asc)],- ],- ),- // ------- TEST CASE 7 ---------- // b, a- // c, a- // d, b, c- (- // ORDERINGS GIVEN- vec![- // [b ASC, a ASC]- vec![(col_b, option_asc), (col_a, option_asc)],- // [c ASC, a ASC]- vec![(col_c, option_asc), (col_a, option_asc)],- // [d ASC, b ASC, c ASC]- vec![- (col_d, option_asc),- (col_b, option_asc),- (col_c, option_asc),- ],- ],- // EXPECTED orderings that is succinct.- vec![- // [b ASC, a ASC]- vec![(col_b, option_asc), (col_a, option_asc)],- // [c ASC, a ASC]- vec![(col_c, option_asc), (col_a, option_asc)],- // [d ASC]- vec![(col_d, option_asc)],- ],- ),- // ------- TEST CASE 8 ---------- // b, e- // c, a- // d, b, e, c, a- (- // ORDERINGS GIVEN- vec![- // [b ASC, e ASC]- vec![(col_b, option_asc), (col_e, option_asc)],- // [c ASC, a ASC]- vec![(col_c, option_asc), (col_a, option_asc)],- // [d ASC, b ASC, e ASC, c ASC, a ASC]- vec![- (col_d, option_asc),- (col_b, option_asc),- (col_e, option_asc),- (col_c, option_asc),- (col_a, option_asc),- ],- ],- // EXPECTED orderings that is succinct.- vec![- // [b ASC, e ASC]- vec![(col_b, option_asc), (col_e, option_asc)],- // [c ASC, a ASC]- vec![(col_c, option_asc), (col_a, option_asc)],- // [d ASC]- vec![(col_d, option_asc)],- ],- ),- // ------- TEST CASE 9 ---------- // b- // a, b, c- // d, a, b- (- // ORDERINGS GIVEN- vec![- // [b ASC]- vec![(col_b, option_asc)],- // [a ASC, b ASC, c ASC]- vec![- (col_a, option_asc),- (col_b, option_asc),- (col_c, option_asc),- ],- // [d ASC, a ASC, b ASC]- vec![- (col_d, option_asc),- (col_a, option_asc),- (col_b, option_asc),- ],- ],- // EXPECTED orderings that is succinct.- vec![- // [b ASC]- vec![(col_b, option_asc)],- // [a ASC, b ASC, c ASC]- vec![- (col_a, option_asc),- (col_b, option_asc),- (col_c, option_asc),- ],- // [d ASC]- vec![(col_d, option_asc)],- ],- ),- ];- for (orderings, expected) in test_cases {- let orderings = convert_to_orderings(&orderings);- let expected = convert_to_orderings(&expected);- let actual = OrderingEquivalenceClass::new(orderings.clone());- let actual = actual.orderings;- let err_msg = format!(- "orderings: {:?}, expected: {:?}, actual :{:?}",- orderings, expected, actual- );- assert_eq!(actual.len(), expected.len(), "{}", err_msg);- for elem in actual {- assert!(expected.contains(&elem), "{}", err_msg);- }- }-- Ok(())- }-- #[test]- fn test_get_updated_right_ordering_equivalence_properties() -> Result<()> {- let join_type = JoinType::Inner;- // Join right child schema- let child_fields: Fields = ["x", "y", "z", "w"]- .into_iter()- .map(|name| Field::new(name, DataType::Int32, true))- .collect();- let child_schema = Schema::new(child_fields);- let col_x = &col("x", &child_schema)?;- let col_y = &col("y", &child_schema)?;- let col_z = &col("z", &child_schema)?;- let col_w = &col("w", &child_schema)?;- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- // [x ASC, y ASC], [z ASC, w ASC]- let orderings = vec![- vec![(col_x, option_asc), (col_y, option_asc)],- vec![(col_z, option_asc), (col_w, option_asc)],- ];- let orderings = convert_to_orderings(&orderings);- // Right child ordering equivalences- let mut right_oeq_class = OrderingEquivalenceClass::new(orderings);-- let left_columns_len = 4;-- let fields: Fields = ["a", "b", "c", "d", "x", "y", "z", "w"]- .into_iter()- .map(|name| Field::new(name, DataType::Int32, true))- .collect();-- // Join Schema- let schema = Schema::new(fields);- let col_a = &col("a", &schema)?;- let col_d = &col("d", &schema)?;- let col_x = &col("x", &schema)?;- let col_y = &col("y", &schema)?;- let col_z = &col("z", &schema)?;- let col_w = &col("w", &schema)?;-- let mut join_eq_properties = EquivalenceProperties::new(Arc::new(schema));- // a=x and d=w- join_eq_properties.add_equal_conditions(col_a, col_x);- join_eq_properties.add_equal_conditions(col_d, col_w);-- updated_right_ordering_equivalence_class(- &mut right_oeq_class,- &join_type,- left_columns_len,- );- join_eq_properties.add_ordering_equivalence_class(right_oeq_class);- let result = join_eq_properties.oeq_class().clone();-- // [x ASC, y ASC], [z ASC, w ASC]- let orderings = vec![- vec![(col_x, option_asc), (col_y, option_asc)],- vec![(col_z, option_asc), (col_w, option_asc)],- ];- let orderings = convert_to_orderings(&orderings);- let expected = OrderingEquivalenceClass::new(orderings);-- assert_eq!(result, expected);-- Ok(())- }-- /// Checks if the table (RecordBatch) remains unchanged when sorted according to the provided `required_ordering`.- ///- /// The function works by adding a unique column of ascending integers to the original table. This column ensures- /// that rows that are otherwise indistinguishable (e.g., if they have the same values in all other columns) can- /// still be differentiated. When sorting the extended table, the unique column acts as a tie-breaker to produce- /// deterministic sorting results.- ///- /// If the table remains the same after sorting with the added unique column, it indicates that the table was- /// already sorted according to `required_ordering` to begin with.- fn is_table_same_after_sort(- mut required_ordering: Vec<PhysicalSortExpr>,- batch: RecordBatch,- ) -> Result<bool> {- // Clone the original schema and columns- let original_schema = batch.schema();- let mut columns = batch.columns().to_vec();-- // Create a new unique column- let n_row = batch.num_rows();- let vals: Vec<usize> = (0..n_row).collect::<Vec<_>>();- let vals: Vec<f64> = vals.into_iter().map(|val| val as f64).collect();- let unique_col = Arc::new(Float64Array::from_iter_values(vals)) as ArrayRef;- columns.push(unique_col.clone());-- // Create a new schema with the added unique column- let unique_col_name = "unique";- let unique_field =- Arc::new(Field::new(unique_col_name, DataType::Float64, false));- let fields: Vec<_> = original_schema- .fields()- .iter()- .cloned()- .chain(std::iter::once(unique_field))- .collect();- let schema = Arc::new(Schema::new(fields));-- // Create a new batch with the added column- let new_batch = RecordBatch::try_new(schema.clone(), columns)?;-- // Add the unique column to the required ordering to ensure deterministic results- required_ordering.push(PhysicalSortExpr {- expr: Arc::new(Column::new(unique_col_name, original_schema.fields().len())),- options: Default::default(),- });-- // Convert the required ordering to a list of SortColumn- let sort_columns = required_ordering- .iter()- .map(|order_expr| {- let expr_result = order_expr.expr.evaluate(&new_batch)?;- let values = expr_result.into_array(new_batch.num_rows())?;- Ok(SortColumn {- values,- options: Some(order_expr.options),- })- })- .collect::<Result<Vec<_>>>()?;-- // Check if the indices after sorting match the initial ordering- let sorted_indices = lexsort_to_indices(&sort_columns, None)?;- let original_indices = UInt32Array::from_iter_values(0..n_row as u32);-- Ok(sorted_indices == original_indices)- }-- // If we already generated a random result for one of the- // expressions in the equivalence classes. For other expressions in the same- // equivalence class use same result. This util gets already calculated result, when available.- fn get_representative_arr(- eq_group: &EquivalenceClass,- existing_vec: &[Option<ArrayRef>],- schema: SchemaRef,- ) -> Option<ArrayRef> {- for expr in eq_group.iter() {- let col = expr.as_any().downcast_ref::<Column>().unwrap();- let (idx, _field) = schema.column_with_name(col.name()).unwrap();- if let Some(res) = &existing_vec[idx] {- return Some(res.clone());- }- }- None- }-- // Generate a table that satisfies the given equivalence properties; i.e.- // equivalences, ordering equivalences, and constants.- fn generate_table_for_eq_properties(- eq_properties: &EquivalenceProperties,- n_elem: usize,- n_distinct: usize,- ) -> Result<RecordBatch> {- let mut rng = StdRng::seed_from_u64(23);-- let schema = eq_properties.schema();- let mut schema_vec = vec![None; schema.fields.len()];-- // Utility closure to generate random array- let mut generate_random_array = |num_elems: usize, max_val: usize| -> ArrayRef {- let values: Vec<f64> = (0..num_elems)- .map(|_| rng.gen_range(0..max_val) as f64 / 2.0)- .collect();- Arc::new(Float64Array::from_iter_values(values))- };-- // Fill constant columns- for constant in &eq_properties.constants {- let col = constant.as_any().downcast_ref::<Column>().unwrap();- let (idx, _field) = schema.column_with_name(col.name()).unwrap();- let arr = Arc::new(Float64Array::from_iter_values(vec![0 as f64; n_elem]))- as ArrayRef;- schema_vec[idx] = Some(arr);- }-- // Fill columns based on ordering equivalences- for ordering in eq_properties.oeq_class.iter() {- let (sort_columns, indices): (Vec<_>, Vec<_>) = ordering- .iter()- .map(|PhysicalSortExpr { expr, options }| {- let col = expr.as_any().downcast_ref::<Column>().unwrap();- let (idx, _field) = schema.column_with_name(col.name()).unwrap();- let arr = generate_random_array(n_elem, n_distinct);- (- SortColumn {- values: arr,- options: Some(*options),- },- idx,- )- })- .unzip();-- let sort_arrs = arrow::compute::lexsort(&sort_columns, None)?;- for (idx, arr) in izip!(indices, sort_arrs) {- schema_vec[idx] = Some(arr);- }- }-- // Fill columns based on equivalence groups- for eq_group in eq_properties.eq_group.iter() {- let representative_array =- get_representative_arr(eq_group, &schema_vec, schema.clone())- .unwrap_or_else(|| generate_random_array(n_elem, n_distinct));-- for expr in eq_group.iter() {- let col = expr.as_any().downcast_ref::<Column>().unwrap();- let (idx, _field) = schema.column_with_name(col.name()).unwrap();- schema_vec[idx] = Some(representative_array.clone());- }- }-- let res: Vec<_> = schema_vec- .into_iter()- .zip(schema.fields.iter())- .map(|(elem, field)| {- (- field.name(),- // Generate random values for columns that do not occur in any of the groups (equivalence, ordering equivalence, constants)- elem.unwrap_or_else(|| generate_random_array(n_elem, n_distinct)),- )- })- .collect();-- Ok(RecordBatch::try_from_iter(res)?)- }-- #[test]- fn test_schema_normalize_expr_with_equivalence() -> Result<()> {- let col_a = &Column::new("a", 0);- let col_b = &Column::new("b", 1);- let col_c = &Column::new("c", 2);- // Assume that column a and c are aliases.- let (_test_schema, eq_properties) = create_test_params()?;-- let col_a_expr = Arc::new(col_a.clone()) as Arc<dyn PhysicalExpr>;- let col_b_expr = Arc::new(col_b.clone()) as Arc<dyn PhysicalExpr>;- let col_c_expr = Arc::new(col_c.clone()) as Arc<dyn PhysicalExpr>;- // Test cases for equivalence normalization,- // First entry in the tuple is argument, second entry is expected result after normalization.- let expressions = vec![- // Normalized version of the column a and c should go to a- // (by convention all the expressions inside equivalence class are mapped to the first entry- // in this case a is the first entry in the equivalence class.)- (&col_a_expr, &col_a_expr),- (&col_c_expr, &col_a_expr),- // Cannot normalize column b- (&col_b_expr, &col_b_expr),- ];- let eq_group = eq_properties.eq_group();- for (expr, expected_eq) in expressions {- assert!(- expected_eq.eq(&eq_group.normalize_expr(expr.clone())),- "error in test: expr: {expr:?}"- );- }-- Ok(())- }-- #[test]- fn test_schema_normalize_sort_requirement_with_equivalence() -> Result<()> {- let option1 = SortOptions {- descending: false,- nulls_first: false,- };- // Assume that column a and c are aliases.- let (test_schema, eq_properties) = create_test_params()?;- let col_a = &col("a", &test_schema)?;- let col_c = &col("c", &test_schema)?;- let col_d = &col("d", &test_schema)?;-- // Test cases for equivalence normalization- // First entry in the tuple is PhysicalSortRequirement, second entry in the tuple is- // expected PhysicalSortRequirement after normalization.- let test_cases = vec![- (vec![(col_a, Some(option1))], vec![(col_a, Some(option1))]),- // In the normalized version column c should be replace with column a- (vec![(col_c, Some(option1))], vec![(col_a, Some(option1))]),- (vec![(col_c, None)], vec![(col_a, None)]),- (vec![(col_d, Some(option1))], vec![(col_d, Some(option1))]),- ];- for (reqs, expected) in test_cases.into_iter() {- let reqs = convert_to_sort_reqs(&reqs);- let expected = convert_to_sort_reqs(&expected);-- let normalized = eq_properties.normalize_sort_requirements(&reqs);- assert!(- expected.eq(&normalized),- "error in test: reqs: {reqs:?}, expected: {expected:?}, normalized: {normalized:?}"- );- }-- Ok(())- }-- #[test]- fn test_normalize_sort_reqs() -> Result<()> {- // Schema satisfies following properties- // a=c- // and following orderings are valid- // [a ASC], [d ASC, b ASC], [e DESC, f ASC, g ASC]- let (test_schema, eq_properties) = create_test_params()?;- let col_a = &col("a", &test_schema)?;- let col_b = &col("b", &test_schema)?;- let col_c = &col("c", &test_schema)?;- let col_d = &col("d", &test_schema)?;- let col_e = &col("e", &test_schema)?;- let col_f = &col("f", &test_schema)?;- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- let option_desc = SortOptions {- descending: true,- nulls_first: true,- };- // First element in the tuple stores vector of requirement, second element is the expected return value for ordering_satisfy function- let requirements = vec![- (- vec![(col_a, Some(option_asc))],- vec![(col_a, Some(option_asc))],- ),- (- vec![(col_a, Some(option_desc))],- vec![(col_a, Some(option_desc))],- ),- (vec![(col_a, None)], vec![(col_a, None)]),- // Test whether equivalence works as expected- (- vec![(col_c, Some(option_asc))],- vec![(col_a, Some(option_asc))],- ),- (vec![(col_c, None)], vec![(col_a, None)]),- // Test whether ordering equivalence works as expected- (- vec![(col_d, Some(option_asc)), (col_b, Some(option_asc))],- vec![(col_d, Some(option_asc)), (col_b, Some(option_asc))],- ),- (- vec![(col_d, None), (col_b, None)],- vec![(col_d, None), (col_b, None)],- ),- (- vec![(col_e, Some(option_desc)), (col_f, Some(option_asc))],- vec![(col_e, Some(option_desc)), (col_f, Some(option_asc))],- ),- // We should be able to normalize in compatible requirements also (not exactly equal)- (- vec![(col_e, Some(option_desc)), (col_f, None)],- vec![(col_e, Some(option_desc)), (col_f, None)],- ),- (- vec![(col_e, None), (col_f, None)],- vec![(col_e, None), (col_f, None)],- ),- ];-- for (reqs, expected_normalized) in requirements.into_iter() {- let req = convert_to_sort_reqs(&reqs);- let expected_normalized = convert_to_sort_reqs(&expected_normalized);-- assert_eq!(- eq_properties.normalize_sort_requirements(&req),- expected_normalized- );- }-- Ok(())- }-- #[test]- fn test_get_finer() -> Result<()> {- let schema = create_test_schema()?;- let col_a = &col("a", &schema)?;- let col_b = &col("b", &schema)?;- let col_c = &col("c", &schema)?;- let eq_properties = EquivalenceProperties::new(schema);- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- let option_desc = SortOptions {- descending: true,- nulls_first: true,- };- // First entry, and second entry are the physical sort requirement that are argument for get_finer_requirement.- // Third entry is the expected result.- let tests_cases = vec![- // Get finer requirement between [a Some(ASC)] and [a None, b Some(ASC)]- // result should be [a Some(ASC), b Some(ASC)]- (- vec![(col_a, Some(option_asc))],- vec![(col_a, None), (col_b, Some(option_asc))],- Some(vec![(col_a, Some(option_asc)), (col_b, Some(option_asc))]),- ),- // Get finer requirement between [a Some(ASC), b Some(ASC), c Some(ASC)] and [a Some(ASC), b Some(ASC)]- // result should be [a Some(ASC), b Some(ASC), c Some(ASC)]- (- vec![- (col_a, Some(option_asc)),- (col_b, Some(option_asc)),- (col_c, Some(option_asc)),- ],- vec![(col_a, Some(option_asc)), (col_b, Some(option_asc))],- Some(vec![- (col_a, Some(option_asc)),- (col_b, Some(option_asc)),- (col_c, Some(option_asc)),- ]),- ),- // Get finer requirement between [a Some(ASC), b Some(ASC)] and [a Some(ASC), b Some(DESC)]- // result should be None- (- vec![(col_a, Some(option_asc)), (col_b, Some(option_asc))],- vec![(col_a, Some(option_asc)), (col_b, Some(option_desc))],- None,- ),- ];- for (lhs, rhs, expected) in tests_cases {- let lhs = convert_to_sort_reqs(&lhs);- let rhs = convert_to_sort_reqs(&rhs);- let expected = expected.map(|expected| convert_to_sort_reqs(&expected));- let finer = eq_properties.get_finer_requirement(&lhs, &rhs);- assert_eq!(finer, expected)- }-- Ok(())- }-- #[test]- fn test_get_meet_ordering() -> Result<()> {- let schema = create_test_schema()?;- let col_a = &col("a", &schema)?;- let col_b = &col("b", &schema)?;- let eq_properties = EquivalenceProperties::new(schema);- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- let option_desc = SortOptions {- descending: true,- nulls_first: true,- };- let tests_cases = vec![- // Get meet ordering between [a ASC] and [a ASC, b ASC]- // result should be [a ASC]- (- vec![(col_a, option_asc)],- vec![(col_a, option_asc), (col_b, option_asc)],- Some(vec![(col_a, option_asc)]),- ),- // Get meet ordering between [a ASC] and [a DESC]- // result should be None.- (vec![(col_a, option_asc)], vec![(col_a, option_desc)], None),- // Get meet ordering between [a ASC, b ASC] and [a ASC, b DESC]- // result should be [a ASC].- (- vec![(col_a, option_asc), (col_b, option_asc)],- vec![(col_a, option_asc), (col_b, option_desc)],- Some(vec![(col_a, option_asc)]),- ),- ];- for (lhs, rhs, expected) in tests_cases {- let lhs = convert_to_sort_exprs(&lhs);- let rhs = convert_to_sort_exprs(&rhs);- let expected = expected.map(|expected| convert_to_sort_exprs(&expected));- let finer = eq_properties.get_meet_ordering(&lhs, &rhs);- assert_eq!(finer, expected)- }-- Ok(())- }-- #[test]- fn test_find_longest_permutation() -> Result<()> {- // Schema satisfies following orderings:- // [a ASC], [d ASC, b ASC], [e DESC, f ASC, g ASC]- // and- // Column [a=c] (e.g they are aliases).- // At below we add [d ASC, h DESC] also, for test purposes- let (test_schema, mut eq_properties) = create_test_params()?;- let col_a = &col("a", &test_schema)?;- let col_b = &col("b", &test_schema)?;- let col_c = &col("c", &test_schema)?;- let col_d = &col("d", &test_schema)?;- let col_e = &col("e", &test_schema)?;- let col_h = &col("h", &test_schema)?;- // a + d- let a_plus_d = Arc::new(BinaryExpr::new(- col_a.clone(),- Operator::Plus,- col_d.clone(),- )) as Arc<dyn PhysicalExpr>;-- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- let option_desc = SortOptions {- descending: true,- nulls_first: true,- };- // [d ASC, h ASC] also satisfies schema.- eq_properties.add_new_orderings([vec![- PhysicalSortExpr {- expr: col_d.clone(),- options: option_asc,- },- PhysicalSortExpr {- expr: col_h.clone(),- options: option_desc,- },- ]]);- let test_cases = vec![- // TEST CASE 1- (vec![col_a], vec![(col_a, option_asc)]),- // TEST CASE 2- (vec![col_c], vec![(col_c, option_asc)]),- // TEST CASE 3- (- vec![col_d, col_e, col_b],- vec![- (col_d, option_asc),- (col_e, option_desc),- (col_b, option_asc),- ],- ),- // TEST CASE 4- (vec![col_b], vec![]),- // TEST CASE 5- (vec![col_d], vec![(col_d, option_asc)]),- // TEST CASE 5- (vec![&a_plus_d], vec![(&a_plus_d, option_asc)]),- // TEST CASE 6- (- vec![col_b, col_d],- vec![(col_d, option_asc), (col_b, option_asc)],- ),- // TEST CASE 6- (- vec![col_c, col_e],- vec![(col_c, option_asc), (col_e, option_desc)],- ),- ];- for (exprs, expected) in test_cases {- let exprs = exprs.into_iter().cloned().collect::<Vec<_>>();- let expected = convert_to_sort_exprs(&expected);- let (actual, _) = eq_properties.find_longest_permutation(&exprs);- assert_eq!(actual, expected);- }-- Ok(())- }-- #[test]- fn test_find_longest_permutation_random() -> Result<()> {- const N_RANDOM_SCHEMA: usize = 100;- const N_ELEMENTS: usize = 125;- const N_DISTINCT: usize = 5;-- for seed in 0..N_RANDOM_SCHEMA {- // Create a random schema with random properties- let (test_schema, eq_properties) = create_random_schema(seed as u64)?;- // Generate a data that satisfies properties given- let table_data_with_properties =- generate_table_for_eq_properties(&eq_properties, N_ELEMENTS, N_DISTINCT)?;-- let floor_a = create_physical_expr(- &BuiltinScalarFunction::Floor,- &[col("a", &test_schema)?],- &test_schema,- &ExecutionProps::default(),- )?;- let a_plus_b = Arc::new(BinaryExpr::new(- col("a", &test_schema)?,- Operator::Plus,- col("b", &test_schema)?,- )) as Arc<dyn PhysicalExpr>;- let exprs = vec![- col("a", &test_schema)?,- col("b", &test_schema)?,- col("c", &test_schema)?,- col("d", &test_schema)?,- col("e", &test_schema)?,- col("f", &test_schema)?,- floor_a,- a_plus_b,- ];-- for n_req in 0..=exprs.len() {- for exprs in exprs.iter().combinations(n_req) {- let exprs = exprs.into_iter().cloned().collect::<Vec<_>>();- let (ordering, indices) =- eq_properties.find_longest_permutation(&exprs);- // Make sure that find_longest_permutation return values are consistent- let ordering2 = indices- .iter()- .zip(ordering.iter())- .map(|(&idx, sort_expr)| PhysicalSortExpr {- expr: exprs[idx].clone(),- options: sort_expr.options,- })- .collect::<Vec<_>>();- assert_eq!(- ordering, ordering2,- "indices and lexicographical ordering do not match"- );-- let err_msg = format!(- "Error in test case ordering:{:?}, eq_properties.oeq_class: {:?}, eq_properties.eq_group: {:?}, eq_properties.constants: {:?}",- ordering, eq_properties.oeq_class, eq_properties.eq_group, eq_properties.constants- );- assert_eq!(ordering.len(), indices.len(), "{}", err_msg);- // Since ordered section satisfies schema, we expect- // that result will be same after sort (e.g sort was unnecessary).- assert!(- is_table_same_after_sort(- ordering.clone(),- table_data_with_properties.clone(),- )?,- "{}",- err_msg- );- }- }- }-- Ok(())- }-- #[test]- fn test_update_ordering() -> Result<()> {- let schema = Schema::new(vec![- Field::new("a", DataType::Int32, true),- Field::new("b", DataType::Int32, true),- Field::new("c", DataType::Int32, true),- Field::new("d", DataType::Int32, true),- ]);-- let mut eq_properties = EquivalenceProperties::new(Arc::new(schema.clone()));- let col_a = &col("a", &schema)?;- let col_b = &col("b", &schema)?;- let col_c = &col("c", &schema)?;- let col_d = &col("d", &schema)?;- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- // b=a (e.g they are aliases)- eq_properties.add_equal_conditions(col_b, col_a);- // [b ASC], [d ASC]- eq_properties.add_new_orderings(vec![- vec![PhysicalSortExpr {- expr: col_b.clone(),- options: option_asc,- }],- vec![PhysicalSortExpr {- expr: col_d.clone(),- options: option_asc,- }],- ]);-- let test_cases = vec![- // d + b- (- Arc::new(BinaryExpr::new(- col_d.clone(),- Operator::Plus,- col_b.clone(),- )) as Arc<dyn PhysicalExpr>,- SortProperties::Ordered(option_asc),- ),- // b- (col_b.clone(), SortProperties::Ordered(option_asc)),- // a- (col_a.clone(), SortProperties::Ordered(option_asc)),- // a + c- (- Arc::new(BinaryExpr::new(- col_a.clone(),- Operator::Plus,- col_c.clone(),- )),- SortProperties::Unordered,- ),- ];- for (expr, expected) in test_cases {- let leading_orderings = eq_properties- .oeq_class()- .iter()- .flat_map(|ordering| ordering.first().cloned())- .collect::<Vec<_>>();- let expr_ordering = eq_properties.get_expr_ordering(expr.clone());- let err_msg = format!(- "expr:{:?}, expected: {:?}, actual: {:?}, leading_orderings: {leading_orderings:?}",- expr, expected, expr_ordering.state- );- assert_eq!(expr_ordering.state, expected, "{}", err_msg);- }-- Ok(())- }-- #[test]- fn test_contains_any() {- let lit_true = Arc::new(Literal::new(ScalarValue::Boolean(Some(true))))- as Arc<dyn PhysicalExpr>;- let lit_false = Arc::new(Literal::new(ScalarValue::Boolean(Some(false))))- as Arc<dyn PhysicalExpr>;- let lit2 =- Arc::new(Literal::new(ScalarValue::Int32(Some(2)))) as Arc<dyn PhysicalExpr>;- let lit1 =- Arc::new(Literal::new(ScalarValue::Int32(Some(1)))) as Arc<dyn PhysicalExpr>;- let col_b_expr = Arc::new(Column::new("b", 1)) as Arc<dyn PhysicalExpr>;-- let cls1 = EquivalenceClass::new(vec![lit_true.clone(), lit_false.clone()]);- let cls2 = EquivalenceClass::new(vec![lit_true.clone(), col_b_expr.clone()]);- let cls3 = EquivalenceClass::new(vec![lit2.clone(), lit1.clone()]);-- // lit_true is common- assert!(cls1.contains_any(&cls2));- // there is no common entry- assert!(!cls1.contains_any(&cls3));- assert!(!cls2.contains_any(&cls3));- }-- #[test]- fn test_get_indices_of_matching_sort_exprs_with_order_eq() -> Result<()> {- let sort_options = SortOptions::default();- let sort_options_not = SortOptions::default().not();-- let schema = Schema::new(vec![- Field::new("a", DataType::Int32, true),- Field::new("b", DataType::Int32, true),- ]);- let col_a = &col("a", &schema)?;- let col_b = &col("b", &schema)?;- let required_columns = [col_b.clone(), col_a.clone()];- let mut eq_properties = EquivalenceProperties::new(Arc::new(schema));- eq_properties.add_new_orderings([vec![- PhysicalSortExpr {- expr: Arc::new(Column::new("b", 1)),- options: sort_options_not,- },- PhysicalSortExpr {- expr: Arc::new(Column::new("a", 0)),- options: sort_options,- },- ]]);- let (result, idxs) = eq_properties.find_longest_permutation(&required_columns);- assert_eq!(idxs, vec![0, 1]);- assert_eq!(- result,- vec![- PhysicalSortExpr {- expr: col_b.clone(),- options: sort_options_not- },- PhysicalSortExpr {- expr: col_a.clone(),- options: sort_options- }- ]- );-- let schema = Schema::new(vec![- Field::new("a", DataType::Int32, true),- Field::new("b", DataType::Int32, true),- Field::new("c", DataType::Int32, true),- ]);- let col_a = &col("a", &schema)?;- let col_b = &col("b", &schema)?;- let required_columns = [col_b.clone(), col_a.clone()];- let mut eq_properties = EquivalenceProperties::new(Arc::new(schema));- eq_properties.add_new_orderings([- vec![PhysicalSortExpr {- expr: Arc::new(Column::new("c", 2)),- options: sort_options,- }],- vec![- PhysicalSortExpr {- expr: Arc::new(Column::new("b", 1)),- options: sort_options_not,- },- PhysicalSortExpr {- expr: Arc::new(Column::new("a", 0)),- options: sort_options,- },- ],- ]);- let (result, idxs) = eq_properties.find_longest_permutation(&required_columns);- assert_eq!(idxs, vec![0, 1]);- assert_eq!(- result,- vec![- PhysicalSortExpr {- expr: col_b.clone(),- options: sort_options_not- },- PhysicalSortExpr {- expr: col_a.clone(),- options: sort_options- }- ]- );-- let required_columns = [- Arc::new(Column::new("b", 1)) as _,- Arc::new(Column::new("a", 0)) as _,- ];- let schema = Schema::new(vec![- Field::new("a", DataType::Int32, true),- Field::new("b", DataType::Int32, true),- Field::new("c", DataType::Int32, true),- ]);- let mut eq_properties = EquivalenceProperties::new(Arc::new(schema));-- // not satisfied orders- eq_properties.add_new_orderings([vec![- PhysicalSortExpr {- expr: Arc::new(Column::new("b", 1)),- options: sort_options_not,- },- PhysicalSortExpr {- expr: Arc::new(Column::new("c", 2)),- options: sort_options,- },- PhysicalSortExpr {- expr: Arc::new(Column::new("a", 0)),- options: sort_options,- },- ]]);- let (_, idxs) = eq_properties.find_longest_permutation(&required_columns);- assert_eq!(idxs, vec![0]);-- Ok(())- }-- #[test]- fn test_normalize_ordering_equivalence_classes() -> Result<()> {- let sort_options = SortOptions::default();-- let schema = Schema::new(vec![- Field::new("a", DataType::Int32, true),- Field::new("b", DataType::Int32, true),- Field::new("c", DataType::Int32, true),- ]);- let col_a_expr = col("a", &schema)?;- let col_b_expr = col("b", &schema)?;- let col_c_expr = col("c", &schema)?;- let mut eq_properties = EquivalenceProperties::new(Arc::new(schema.clone()));-- eq_properties.add_equal_conditions(&col_a_expr, &col_c_expr);- let others = vec![- vec![PhysicalSortExpr {- expr: col_b_expr.clone(),- options: sort_options,- }],- vec![PhysicalSortExpr {- expr: col_c_expr.clone(),- options: sort_options,- }],- ];- eq_properties.add_new_orderings(others);-- let mut expected_eqs = EquivalenceProperties::new(Arc::new(schema));- expected_eqs.add_new_orderings([- vec![PhysicalSortExpr {- expr: col_b_expr.clone(),- options: sort_options,- }],- vec![PhysicalSortExpr {- expr: col_c_expr.clone(),- options: sort_options,- }],- ]);-- let oeq_class = eq_properties.oeq_class().clone();- let expected = expected_eqs.oeq_class();- assert!(oeq_class.eq(expected));-- Ok(())- }-- #[test]- fn project_orderings() -> Result<()> {- let schema = Arc::new(Schema::new(vec![- Field::new("a", DataType::Int32, true),- Field::new("b", DataType::Int32, true),- Field::new("c", DataType::Int32, true),- Field::new("d", DataType::Int32, true),- Field::new("e", DataType::Int32, true),- Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),- ]));- let col_a = &col("a", &schema)?;- let col_b = &col("b", &schema)?;- let col_c = &col("c", &schema)?;- let col_d = &col("d", &schema)?;- let col_e = &col("e", &schema)?;- let col_ts = &col("ts", &schema)?;- let interval = Arc::new(Literal::new(ScalarValue::IntervalDayTime(Some(2))))- as Arc<dyn PhysicalExpr>;- let date_bin_func = &create_physical_expr(- &BuiltinScalarFunction::DateBin,- &[interval, col_ts.clone()],- &schema,- &ExecutionProps::default(),- )?;- let a_plus_b = Arc::new(BinaryExpr::new(- col_a.clone(),- Operator::Plus,- col_b.clone(),- )) as Arc<dyn PhysicalExpr>;- let b_plus_d = Arc::new(BinaryExpr::new(- col_b.clone(),- Operator::Plus,- col_d.clone(),- )) as Arc<dyn PhysicalExpr>;- let b_plus_e = Arc::new(BinaryExpr::new(- col_b.clone(),- Operator::Plus,- col_e.clone(),- )) as Arc<dyn PhysicalExpr>;- let c_plus_d = Arc::new(BinaryExpr::new(- col_c.clone(),- Operator::Plus,- col_d.clone(),- )) as Arc<dyn PhysicalExpr>;-- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- let option_desc = SortOptions {- descending: true,- nulls_first: true,- };-- let test_cases = vec![- // ---------- TEST CASE 1 ------------- (- // orderings- vec![- // [b ASC]- vec![(col_b, option_asc)],- ],- // projection exprs- vec![(col_b, "b_new".to_string()), (col_a, "a_new".to_string())],- // expected- vec![- // [b_new ASC]- vec![("b_new", option_asc)],- ],- ),- // ---------- TEST CASE 2 ------------- (- // orderings- vec![- // empty ordering- ],- // projection exprs- vec![(col_c, "c_new".to_string()), (col_b, "b_new".to_string())],- // expected- vec![- // no ordering at the output- ],- ),- // ---------- TEST CASE 3 ------------- (- // orderings- vec![- // [ts ASC]- vec![(col_ts, option_asc)],- ],- // projection exprs- vec![- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (col_ts, "ts_new".to_string()),- (date_bin_func, "date_bin_res".to_string()),- ],- // expected- vec![- // [date_bin_res ASC]- vec![("date_bin_res", option_asc)],- // [ts_new ASC]- vec![("ts_new", option_asc)],- ],- ),- // ---------- TEST CASE 4 ------------- (- // orderings- vec![- // [a ASC, ts ASC]- vec![(col_a, option_asc), (col_ts, option_asc)],- // [b ASC, ts ASC]- vec![(col_b, option_asc), (col_ts, option_asc)],- ],- // projection exprs- vec![- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (col_ts, "ts_new".to_string()),- (date_bin_func, "date_bin_res".to_string()),- ],- // expected- vec![- // [a_new ASC, ts_new ASC]- vec![("a_new", option_asc), ("ts_new", option_asc)],- // [a_new ASC, date_bin_res ASC]- vec![("a_new", option_asc), ("date_bin_res", option_asc)],- // [b_new ASC, ts_new ASC]- vec![("b_new", option_asc), ("ts_new", option_asc)],- // [b_new ASC, date_bin_res ASC]- vec![("b_new", option_asc), ("date_bin_res", option_asc)],- ],- ),- // ---------- TEST CASE 5 ------------- (- // orderings- vec![- // [a + b ASC]- vec![(&a_plus_b, option_asc)],- ],- // projection exprs- vec![- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (&a_plus_b, "a+b".to_string()),- ],- // expected- vec![- // [a + b ASC]- vec![("a+b", option_asc)],- ],- ),- // ---------- TEST CASE 6 ------------- (- // orderings- vec![- // [a + b ASC, c ASC]- vec![(&a_plus_b, option_asc), (&col_c, option_asc)],- ],- // projection exprs- vec![- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (col_c, "c_new".to_string()),- (&a_plus_b, "a+b".to_string()),- ],- // expected- vec![- // [a + b ASC, c_new ASC]- vec![("a+b", option_asc), ("c_new", option_asc)],- ],- ),- // ------- TEST CASE 7 ----------- (- vec![- // [a ASC, b ASC, c ASC]- vec![(col_a, option_asc), (col_b, option_asc)],- // [a ASC, d ASC]- vec![(col_a, option_asc), (col_d, option_asc)],- ],- // b as b_new, a as a_new, d as d_new b+d- vec![- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (col_d, "d_new".to_string()),- (&b_plus_d, "b+d".to_string()),- ],- // expected- vec![- // [a_new ASC, b_new ASC]- vec![("a_new", option_asc), ("b_new", option_asc)],- // [a_new ASC, d_new ASC]- vec![("a_new", option_asc), ("d_new", option_asc)],- // [a_new ASC, b+d ASC]- vec![("a_new", option_asc), ("b+d", option_asc)],- ],- ),- // ------- TEST CASE 8 ----------- (- // orderings- vec![- // [b+d ASC]- vec![(&b_plus_d, option_asc)],- ],- // proj exprs- vec![- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (col_d, "d_new".to_string()),- (&b_plus_d, "b+d".to_string()),- ],- // expected- vec![- // [b+d ASC]- vec![("b+d", option_asc)],- ],- ),- // ------- TEST CASE 9 ----------- (- // orderings- vec![- // [a ASC, d ASC, b ASC]- vec![- (col_a, option_asc),- (col_d, option_asc),- (col_b, option_asc),- ],- // [c ASC]- vec![(col_c, option_asc)],- ],- // proj exprs- vec![- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (col_d, "d_new".to_string()),- (col_c, "c_new".to_string()),- ],- // expected- vec![- // [a_new ASC, d_new ASC, b_new ASC]- vec![- ("a_new", option_asc),- ("d_new", option_asc),- ("b_new", option_asc),- ],- // [c_new ASC],- vec![("c_new", option_asc)],- ],- ),- // ------- TEST CASE 10 ----------- (- vec![- // [a ASC, b ASC, c ASC]- vec![- (col_a, option_asc),- (col_b, option_asc),- (col_c, option_asc),- ],- // [a ASC, d ASC]- vec![(col_a, option_asc), (col_d, option_asc)],- ],- // proj exprs- vec![- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (col_c, "c_new".to_string()),- (&c_plus_d, "c+d".to_string()),- ],- // expected- vec![- // [a_new ASC, b_new ASC, c_new ASC]- vec![- ("a_new", option_asc),- ("b_new", option_asc),- ("c_new", option_asc),- ],- // [a_new ASC, b_new ASC, c+d ASC]- vec![- ("a_new", option_asc),- ("b_new", option_asc),- ("c+d", option_asc),- ],- ],- ),- // ------- TEST CASE 11 ----------- (- // orderings- vec![- // [a ASC, b ASC]- vec![(col_a, option_asc), (col_b, option_asc)],- // [a ASC, d ASC]- vec![(col_a, option_asc), (col_d, option_asc)],- ],- // proj exprs- vec![- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (&b_plus_d, "b+d".to_string()),- ],- // expected- vec![- // [a_new ASC, b_new ASC]- vec![("a_new", option_asc), ("b_new", option_asc)],- // [a_new ASC, b + d ASC]- vec![("a_new", option_asc), ("b+d", option_asc)],- ],- ),- // ------- TEST CASE 12 ----------- (- // orderings- vec![- // [a ASC, b ASC, c ASC]- vec![- (col_a, option_asc),- (col_b, option_asc),- (col_c, option_asc),- ],- ],- // proj exprs- vec![(col_c, "c_new".to_string()), (col_a, "a_new".to_string())],- // expected- vec![- // [a_new ASC]- vec![("a_new", option_asc)],- ],- ),- // ------- TEST CASE 13 ----------- (- // orderings- vec![- // [a ASC, b ASC, c ASC]- vec![- (col_a, option_asc),- (col_b, option_asc),- (col_c, option_asc),- ],- // [a ASC, a + b ASC, c ASC]- vec![- (col_a, option_asc),- (&a_plus_b, option_asc),- (col_c, option_asc),- ],- ],- // proj exprs- vec![- (col_c, "c_new".to_string()),- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (&a_plus_b, "a+b".to_string()),- ],- // expected- vec![- // [a_new ASC, b_new ASC, c_new ASC]- vec![- ("a_new", option_asc),- ("b_new", option_asc),- ("c_new", option_asc),- ],- // [a_new ASC, a+b ASC, c_new ASC]- vec![- ("a_new", option_asc),- ("a+b", option_asc),- ("c_new", option_asc),- ],- ],- ),- // ------- TEST CASE 14 ----------- (- // orderings- vec![- // [a ASC, b ASC]- vec![(col_a, option_asc), (col_b, option_asc)],- // [c ASC, b ASC]- vec![(col_c, option_asc), (col_b, option_asc)],- // [d ASC, e ASC]- vec![(col_d, option_asc), (col_e, option_asc)],- ],- // proj exprs- vec![- (col_c, "c_new".to_string()),- (col_d, "d_new".to_string()),- (col_a, "a_new".to_string()),- (&b_plus_e, "b+e".to_string()),- ],- // expected- vec![- // [a_new ASC, d_new ASC, b+e ASC]- vec![- ("a_new", option_asc),- ("d_new", option_asc),- ("b+e", option_asc),- ],- // [d_new ASC, a_new ASC, b+e ASC]- vec![- ("d_new", option_asc),- ("a_new", option_asc),- ("b+e", option_asc),- ],- // [c_new ASC, d_new ASC, b+e ASC]- vec![- ("c_new", option_asc),- ("d_new", option_asc),- ("b+e", option_asc),- ],- // [d_new ASC, c_new ASC, b+e ASC]- vec![- ("d_new", option_asc),- ("c_new", option_asc),- ("b+e", option_asc),- ],- ],- ),- // ------- TEST CASE 15 ----------- (- // orderings- vec![- // [a ASC, c ASC, b ASC]- vec![- (col_a, option_asc),- (col_c, option_asc),- (&col_b, option_asc),- ],- ],- // proj exprs- vec![- (col_c, "c_new".to_string()),- (col_a, "a_new".to_string()),- (&a_plus_b, "a+b".to_string()),- ],- // expected- vec![- // [a_new ASC, d_new ASC, b+e ASC]- vec![- ("a_new", option_asc),- ("c_new", option_asc),- ("a+b", option_asc),- ],- ],- ),- // ------- TEST CASE 16 ----------- (- // orderings- vec![- // [a ASC, b ASC]- vec![(col_a, option_asc), (col_b, option_asc)],- // [c ASC, b DESC]- vec![(col_c, option_asc), (col_b, option_desc)],- // [e ASC]- vec![(col_e, option_asc)],- ],- // proj exprs- vec![- (col_c, "c_new".to_string()),- (col_a, "a_new".to_string()),- (col_b, "b_new".to_string()),- (&b_plus_e, "b+e".to_string()),- ],- // expected- vec![- // [a_new ASC, b_new ASC]- vec![("a_new", option_asc), ("b_new", option_asc)],- // [a_new ASC, b_new ASC]- vec![("a_new", option_asc), ("b+e", option_asc)],- // [c_new ASC, b_new DESC]- vec![("c_new", option_asc), ("b_new", option_desc)],- ],- ),- ];-- for (idx, (orderings, proj_exprs, expected)) in test_cases.into_iter().enumerate()- {- let mut eq_properties = EquivalenceProperties::new(schema.clone());-- let orderings = convert_to_orderings(&orderings);- eq_properties.add_new_orderings(orderings);-- let proj_exprs = proj_exprs- .into_iter()- .map(|(expr, name)| (expr.clone(), name))- .collect::<Vec<_>>();- let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &schema)?;- let output_schema = output_schema(&projection_mapping, &schema)?;-- let expected = expected- .into_iter()- .map(|ordering| {- ordering- .into_iter()- .map(|(name, options)| {- (col(name, &output_schema).unwrap(), options)- })- .collect::<Vec<_>>()- })- .collect::<Vec<_>>();- let expected = convert_to_orderings_owned(&expected);-- let projected_eq = eq_properties.project(&projection_mapping, output_schema);- let orderings = projected_eq.oeq_class();-- let err_msg = format!(- "test_idx: {:?}, actual: {:?}, expected: {:?}, projection_mapping: {:?}",- idx, orderings.orderings, expected, projection_mapping- );-- assert_eq!(orderings.len(), expected.len(), "{}", err_msg);- for expected_ordering in &expected {- assert!(orderings.contains(expected_ordering), "{}", err_msg)- }- }-- Ok(())- }-- #[test]- fn project_orderings2() -> Result<()> {- let schema = Arc::new(Schema::new(vec![- Field::new("a", DataType::Int32, true),- Field::new("b", DataType::Int32, true),- Field::new("c", DataType::Int32, true),- Field::new("d", DataType::Int32, true),- Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),- ]));- let col_a = &col("a", &schema)?;- let col_b = &col("b", &schema)?;- let col_c = &col("c", &schema)?;- let col_ts = &col("ts", &schema)?;- let a_plus_b = Arc::new(BinaryExpr::new(- col_a.clone(),- Operator::Plus,- col_b.clone(),- )) as Arc<dyn PhysicalExpr>;- let interval = Arc::new(Literal::new(ScalarValue::IntervalDayTime(Some(2))))- as Arc<dyn PhysicalExpr>;- let date_bin_ts = &create_physical_expr(- &BuiltinScalarFunction::DateBin,- &[interval, col_ts.clone()],- &schema,- &ExecutionProps::default(),- )?;-- let round_c = &create_physical_expr(- &BuiltinScalarFunction::Round,- &[col_c.clone()],- &schema,- &ExecutionProps::default(),- )?;-- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };-- let proj_exprs = vec![- (col_b, "b_new".to_string()),- (col_a, "a_new".to_string()),- (col_c, "c_new".to_string()),- (date_bin_ts, "date_bin_res".to_string()),- (round_c, "round_c_res".to_string()),- ];- let proj_exprs = proj_exprs- .into_iter()- .map(|(expr, name)| (expr.clone(), name))- .collect::<Vec<_>>();- let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &schema)?;- let output_schema = output_schema(&projection_mapping, &schema)?;-- let col_a_new = &col("a_new", &output_schema)?;- let col_b_new = &col("b_new", &output_schema)?;- let col_c_new = &col("c_new", &output_schema)?;- let col_date_bin_res = &col("date_bin_res", &output_schema)?;- let col_round_c_res = &col("round_c_res", &output_schema)?;- let a_new_plus_b_new = Arc::new(BinaryExpr::new(- col_a_new.clone(),- Operator::Plus,- col_b_new.clone(),- )) as Arc<dyn PhysicalExpr>;-- let test_cases = vec![- // ---------- TEST CASE 1 ------------- (- // orderings- vec![- // [a ASC]- vec![(col_a, option_asc)],- ],- // expected- vec![- // [b_new ASC]- vec![(col_a_new, option_asc)],- ],- ),- // ---------- TEST CASE 2 ------------- (- // orderings- vec![- // [a+b ASC]- vec![(&a_plus_b, option_asc)],- ],- // expected- vec![- // [b_new ASC]- vec![(&a_new_plus_b_new, option_asc)],- ],- ),- // ---------- TEST CASE 3 ------------- (- // orderings- vec![- // [a ASC, ts ASC]- vec![(col_a, option_asc), (col_ts, option_asc)],- ],- // expected- vec![- // [a_new ASC, date_bin_res ASC]- vec![(col_a_new, option_asc), (col_date_bin_res, option_asc)],- ],- ),- // ---------- TEST CASE 4 ------------- (- // orderings- vec![- // [a ASC, ts ASC, b ASC]- vec![- (col_a, option_asc),- (col_ts, option_asc),- (col_b, option_asc),- ],- ],- // expected- vec![- // [a_new ASC, date_bin_res ASC]- // Please note that result is not [a_new ASC, date_bin_res ASC, b_new ASC]- // because, datebin_res may not be 1-1 function. Hence without introducing ts- // dependency we cannot guarantee any ordering after date_bin_res column.- vec![(col_a_new, option_asc), (col_date_bin_res, option_asc)],- ],- ),- // ---------- TEST CASE 5 ------------- (- // orderings- vec![- // [a ASC, c ASC]- vec![(col_a, option_asc), (col_c, option_asc)],- ],- // expected- vec![- // [a_new ASC, round_c_res ASC, c_new ASC]- vec![(col_a_new, option_asc), (col_round_c_res, option_asc)],- // [a_new ASC, c_new ASC]- vec![(col_a_new, option_asc), (col_c_new, option_asc)],- ],- ),- // ---------- TEST CASE 6 ------------- (- // orderings- vec![- // [c ASC, b ASC]- vec![(col_c, option_asc), (col_b, option_asc)],- ],- // expected- vec![- // [round_c_res ASC]- vec![(col_round_c_res, option_asc)],- // [c_new ASC, b_new ASC]- vec![(col_c_new, option_asc), (col_b_new, option_asc)],- ],- ),- // ---------- TEST CASE 7 ------------- (- // orderings- vec![- // [a+b ASC, c ASC]- vec![(&a_plus_b, option_asc), (col_c, option_asc)],- ],- // expected- vec![- // [a+b ASC, round(c) ASC, c_new ASC]- vec![- (&a_new_plus_b_new, option_asc),- (&col_round_c_res, option_asc),- ],- // [a+b ASC, c_new ASC]- vec![(&a_new_plus_b_new, option_asc), (col_c_new, option_asc)],- ],- ),- ];-- for (idx, (orderings, expected)) in test_cases.iter().enumerate() {- let mut eq_properties = EquivalenceProperties::new(schema.clone());-- let orderings = convert_to_orderings(orderings);- eq_properties.add_new_orderings(orderings);-- let expected = convert_to_orderings(expected);-- let projected_eq =- eq_properties.project(&projection_mapping, output_schema.clone());- let orderings = projected_eq.oeq_class();-- let err_msg = format!(- "test idx: {:?}, actual: {:?}, expected: {:?}, projection_mapping: {:?}",- idx, orderings.orderings, expected, projection_mapping- );-- assert_eq!(orderings.len(), expected.len(), "{}", err_msg);- for expected_ordering in &expected {- assert!(orderings.contains(expected_ordering), "{}", err_msg)- }- }- Ok(())- }-- #[test]- fn project_orderings3() -> Result<()> {- let schema = Arc::new(Schema::new(vec![- Field::new("a", DataType::Int32, true),- Field::new("b", DataType::Int32, true),- Field::new("c", DataType::Int32, true),- Field::new("d", DataType::Int32, true),- Field::new("e", DataType::Int32, true),- Field::new("f", DataType::Int32, true),- ]));- let col_a = &col("a", &schema)?;- let col_b = &col("b", &schema)?;- let col_c = &col("c", &schema)?;- let col_d = &col("d", &schema)?;- let col_e = &col("e", &schema)?;- let col_f = &col("f", &schema)?;- let a_plus_b = Arc::new(BinaryExpr::new(- col_a.clone(),- Operator::Plus,- col_b.clone(),- )) as Arc<dyn PhysicalExpr>;-- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };-- let proj_exprs = vec![- (col_c, "c_new".to_string()),- (col_d, "d_new".to_string()),- (&a_plus_b, "a+b".to_string()),- ];- let proj_exprs = proj_exprs- .into_iter()- .map(|(expr, name)| (expr.clone(), name))- .collect::<Vec<_>>();- let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &schema)?;- let output_schema = output_schema(&projection_mapping, &schema)?;-- let col_a_plus_b_new = &col("a+b", &output_schema)?;- let col_c_new = &col("c_new", &output_schema)?;- let col_d_new = &col("d_new", &output_schema)?;-- let test_cases = vec![- // ---------- TEST CASE 1 ------------- (- // orderings- vec![- // [d ASC, b ASC]- vec![(col_d, option_asc), (col_b, option_asc)],- // [c ASC, a ASC]- vec![(col_c, option_asc), (col_a, option_asc)],- ],- // equal conditions- vec![],- // expected- vec![- // [d_new ASC, c_new ASC, a+b ASC]- vec![- (col_d_new, option_asc),- (col_c_new, option_asc),- (col_a_plus_b_new, option_asc),- ],- // [c_new ASC, d_new ASC, a+b ASC]- vec![- (col_c_new, option_asc),- (col_d_new, option_asc),- (col_a_plus_b_new, option_asc),- ],- ],- ),- // ---------- TEST CASE 2 ------------- (- // orderings- vec![- // [d ASC, b ASC]- vec![(col_d, option_asc), (col_b, option_asc)],- // [c ASC, e ASC], Please note that a=e- vec![(col_c, option_asc), (col_e, option_asc)],- ],- // equal conditions- vec![(col_e, col_a)],- // expected- vec![- // [d_new ASC, c_new ASC, a+b ASC]- vec![- (col_d_new, option_asc),- (col_c_new, option_asc),- (col_a_plus_b_new, option_asc),- ],- // [c_new ASC, d_new ASC, a+b ASC]- vec![- (col_c_new, option_asc),- (col_d_new, option_asc),- (col_a_plus_b_new, option_asc),- ],- ],- ),- // ---------- TEST CASE 3 ------------- (- // orderings- vec![- // [d ASC, b ASC]- vec![(col_d, option_asc), (col_b, option_asc)],- // [c ASC, e ASC], Please note that a=f- vec![(col_c, option_asc), (col_e, option_asc)],- ],- // equal conditions- vec![(col_a, col_f)],- // expected- vec![- // [d_new ASC]- vec![(col_d_new, option_asc)],- // [c_new ASC]- vec![(col_c_new, option_asc)],- ],- ),- ];- for (orderings, equal_columns, expected) in test_cases {- let mut eq_properties = EquivalenceProperties::new(schema.clone());- for (lhs, rhs) in equal_columns {- eq_properties.add_equal_conditions(lhs, rhs);- }-- let orderings = convert_to_orderings(&orderings);- eq_properties.add_new_orderings(orderings);-- let expected = convert_to_orderings(&expected);-- let projected_eq =- eq_properties.project(&projection_mapping, output_schema.clone());- let orderings = projected_eq.oeq_class();-- let err_msg = format!(- "actual: {:?}, expected: {:?}, projection_mapping: {:?}",- orderings.orderings, expected, projection_mapping- );-- assert_eq!(orderings.len(), expected.len(), "{}", err_msg);- for expected_ordering in &expected {- assert!(orderings.contains(expected_ordering), "{}", err_msg)- }- }-- Ok(())- }-- #[test]- fn project_orderings_random() -> Result<()> {- const N_RANDOM_SCHEMA: usize = 20;- const N_ELEMENTS: usize = 125;- const N_DISTINCT: usize = 5;-- for seed in 0..N_RANDOM_SCHEMA {- // Create a random schema with random properties- let (test_schema, eq_properties) = create_random_schema(seed as u64)?;- // Generate a data that satisfies properties given- let table_data_with_properties =- generate_table_for_eq_properties(&eq_properties, N_ELEMENTS, N_DISTINCT)?;- // Floor(a)- let floor_a = create_physical_expr(- &BuiltinScalarFunction::Floor,- &[col("a", &test_schema)?],- &test_schema,- &ExecutionProps::default(),- )?;- // a + b- let a_plus_b = Arc::new(BinaryExpr::new(- col("a", &test_schema)?,- Operator::Plus,- col("b", &test_schema)?,- )) as Arc<dyn PhysicalExpr>;- let proj_exprs = vec![- (col("a", &test_schema)?, "a_new"),- (col("b", &test_schema)?, "b_new"),- (col("c", &test_schema)?, "c_new"),- (col("d", &test_schema)?, "d_new"),- (col("e", &test_schema)?, "e_new"),- (col("f", &test_schema)?, "f_new"),- (floor_a, "floor(a)"),- (a_plus_b, "a+b"),- ];-- for n_req in 0..=proj_exprs.len() {- for proj_exprs in proj_exprs.iter().combinations(n_req) {- let proj_exprs = proj_exprs- .into_iter()- .map(|(expr, name)| (expr.clone(), name.to_string()))- .collect::<Vec<_>>();- let (projected_batch, projected_eq) = apply_projection(- proj_exprs.clone(),- &table_data_with_properties,- &eq_properties,- )?;-- // Make sure each ordering after projection is valid.- for ordering in projected_eq.oeq_class().iter() {- let err_msg = format!(- "Error in test case ordering:{:?}, eq_properties.oeq_class: {:?}, eq_properties.eq_group: {:?}, eq_properties.constants: {:?}, proj_exprs: {:?}",- ordering, eq_properties.oeq_class, eq_properties.eq_group, eq_properties.constants, proj_exprs- );- // Since ordered section satisfies schema, we expect- // that result will be same after sort (e.g sort was unnecessary).- assert!(- is_table_same_after_sort(- ordering.clone(),- projected_batch.clone(),- )?,- "{}",- err_msg- );- }- }- }- }-- Ok(())- }-- #[test]- fn ordering_satisfy_after_projection_random() -> Result<()> {- const N_RANDOM_SCHEMA: usize = 20;- const N_ELEMENTS: usize = 125;- const N_DISTINCT: usize = 5;- const SORT_OPTIONS: SortOptions = SortOptions {- descending: false,- nulls_first: false,- };-- for seed in 0..N_RANDOM_SCHEMA {- // Create a random schema with random properties- let (test_schema, eq_properties) = create_random_schema(seed as u64)?;- // Generate a data that satisfies properties given- let table_data_with_properties =- generate_table_for_eq_properties(&eq_properties, N_ELEMENTS, N_DISTINCT)?;- // Floor(a)- let floor_a = create_physical_expr(- &BuiltinScalarFunction::Floor,- &[col("a", &test_schema)?],- &test_schema,- &ExecutionProps::default(),- )?;- // a + b- let a_plus_b = Arc::new(BinaryExpr::new(- col("a", &test_schema)?,- Operator::Plus,- col("b", &test_schema)?,- )) as Arc<dyn PhysicalExpr>;- let proj_exprs = vec![- (col("a", &test_schema)?, "a_new"),- (col("b", &test_schema)?, "b_new"),- (col("c", &test_schema)?, "c_new"),- (col("d", &test_schema)?, "d_new"),- (col("e", &test_schema)?, "e_new"),- (col("f", &test_schema)?, "f_new"),- (floor_a, "floor(a)"),- (a_plus_b, "a+b"),- ];-- for n_req in 0..=proj_exprs.len() {- for proj_exprs in proj_exprs.iter().combinations(n_req) {- let proj_exprs = proj_exprs- .into_iter()- .map(|(expr, name)| (expr.clone(), name.to_string()))- .collect::<Vec<_>>();- let (projected_batch, projected_eq) = apply_projection(- proj_exprs.clone(),- &table_data_with_properties,- &eq_properties,- )?;-- let projection_mapping =- ProjectionMapping::try_new(&proj_exprs, &test_schema)?;-- let projected_exprs = projection_mapping- .iter()- .map(|(_source, target)| target.clone())- .collect::<Vec<_>>();-- for n_req in 0..=projected_exprs.len() {- for exprs in projected_exprs.iter().combinations(n_req) {- let requirement = exprs- .into_iter()- .map(|expr| PhysicalSortExpr {- expr: expr.clone(),- options: SORT_OPTIONS,- })- .collect::<Vec<_>>();- let expected = is_table_same_after_sort(- requirement.clone(),- projected_batch.clone(),- )?;- let err_msg = format!(- "Error in test case requirement:{:?}, expected: {:?}, eq_properties.oeq_class: {:?}, eq_properties.eq_group: {:?}, eq_properties.constants: {:?}, projected_eq.oeq_class: {:?}, projected_eq.eq_group: {:?}, projected_eq.constants: {:?}, projection_mapping: {:?}",- requirement, expected, eq_properties.oeq_class, eq_properties.eq_group, eq_properties.constants, projected_eq.oeq_class, projected_eq.eq_group, projected_eq.constants, projection_mapping- );- // Check whether ordering_satisfy API result and- // experimental result matches.- assert_eq!(- projected_eq.ordering_satisfy(&requirement),- expected,- "{}",- err_msg- );- }- }- }- }- }-- Ok(())- }-- #[test]- fn test_expr_consists_of_constants() -> Result<()> {- let schema = Arc::new(Schema::new(vec![- Field::new("a", DataType::Int32, true),- Field::new("b", DataType::Int32, true),- Field::new("c", DataType::Int32, true),- Field::new("d", DataType::Int32, true),- Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),- ]));- let col_a = col("a", &schema)?;- let col_b = col("b", &schema)?;- let col_d = col("d", &schema)?;- let b_plus_d = Arc::new(BinaryExpr::new(- col_b.clone(),- Operator::Plus,- col_d.clone(),- )) as Arc<dyn PhysicalExpr>;-- let constants = vec![col_a.clone(), col_b.clone()];- let expr = b_plus_d.clone();- assert!(!is_constant_recurse(&constants, &expr));-- let constants = vec![col_a.clone(), col_b.clone(), col_d.clone()];- let expr = b_plus_d.clone();- assert!(is_constant_recurse(&constants, &expr));- Ok(())- }-- #[test]- fn test_join_equivalence_properties() -> Result<()> {- let schema = create_test_schema()?;- let col_a = &col("a", &schema)?;- let col_b = &col("b", &schema)?;- let col_c = &col("c", &schema)?;- let offset = schema.fields.len();- let col_a2 = &add_offset_to_expr(col_a.clone(), offset);- let col_b2 = &add_offset_to_expr(col_b.clone(), offset);- let option_asc = SortOptions {- descending: false,- nulls_first: false,- };- let test_cases = vec![- // ------- TEST CASE 1 --------- // [a ASC], [b ASC]- (- // [a ASC], [b ASC]- vec![vec![(col_a, option_asc)], vec![(col_b, option_asc)]],- // [a ASC], [b ASC]- vec![vec![(col_a, option_asc)], vec![(col_b, option_asc)]],- // expected [a ASC, a2 ASC], [a ASC, b2 ASC], [b ASC, a2 ASC], [b ASC, b2 ASC]- vec![- vec![(col_a, option_asc), (col_a2, option_asc)],- vec![(col_a, option_asc), (col_b2, option_asc)],- vec![(col_b, option_asc), (col_a2, option_asc)],- vec![(col_b, option_asc), (col_b2, option_asc)],- ],- ),- // ------- TEST CASE 2 --------- // [a ASC], [b ASC]- (- // [a ASC], [b ASC], [c ASC]- vec![- vec![(col_a, option_asc)],- vec![(col_b, option_asc)],- vec![(col_c, option_asc)],- ],- // [a ASC], [b ASC]- vec![vec![(col_a, option_asc)], vec![(col_b, option_asc)]],- // expected [a ASC, a2 ASC], [a ASC, b2 ASC], [b ASC, a2 ASC], [b ASC, b2 ASC], [c ASC, a2 ASC], [c ASC, b2 ASC]- vec![- vec![(col_a, option_asc), (col_a2, option_asc)],- vec![(col_a, option_asc), (col_b2, option_asc)],- vec![(col_b, option_asc), (col_a2, option_asc)],- vec![(col_b, option_asc), (col_b2, option_asc)],- vec![(col_c, option_asc), (col_a2, option_asc)],- vec![(col_c, option_asc), (col_b2, option_asc)],- ],- ),- ];- for (left_orderings, right_orderings, expected) in test_cases {- let mut left_eq_properties = EquivalenceProperties::new(schema.clone());- let mut right_eq_properties = EquivalenceProperties::new(schema.clone());- let left_orderings = convert_to_orderings(&left_orderings);- let right_orderings = convert_to_orderings(&right_orderings);- let expected = convert_to_orderings(&expected);- left_eq_properties.add_new_orderings(left_orderings);- right_eq_properties.add_new_orderings(right_orderings);- let join_eq = join_equivalence_properties(- left_eq_properties,- right_eq_properties,- &JoinType::Inner,- Arc::new(Schema::empty()),- &[true, false],- Some(JoinSide::Left),- &[],- );- let orderings = &join_eq.oeq_class.orderings;- let err_msg = format!("expected: {:?}, actual:{:?}", expected, orderings);- assert_eq!(- join_eq.oeq_class.orderings.len(),- expected.len(),- "{}",- err_msg- );- for ordering in orderings {- assert!(- expected.contains(ordering),- "{}, ordering: {:?}",- err_msg,- ordering- );- }- }- Ok(())- }-}diff --git a/datafusion/physical-expr/src/equivalence/class.rs b/datafusion/physical-expr/src/equivalence/class.rsnew file mode 100644index 0000000000..f0bd1740d5--- /dev/null+++ b/datafusion/physical-expr/src/equivalence/class.rs@@ -0,0 +1,598 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++use super::{add_offset_to_expr, collapse_lex_req, ProjectionMapping};+use crate::{+ expressions::Column, physical_expr::deduplicate_physical_exprs,+ physical_exprs_bag_equal, physical_exprs_contains, LexOrdering, LexOrderingRef,+ LexRequirement, LexRequirementRef, PhysicalExpr, PhysicalSortExpr,+ PhysicalSortRequirement,+};+use datafusion_common::tree_node::TreeNode;+use datafusion_common::{tree_node::Transformed, JoinType};+use std::sync::Arc;++/// An `EquivalenceClass` is a set of [`Arc<dyn PhysicalExpr>`]s that are known+/// to have the same value for all tuples in a relation. These are generated by+/// equality predicates (e.g. `a = b`), typically equi-join conditions and+/// equality conditions in filters.+///+/// Two `EquivalenceClass`es are equal if they contains the same expressions in+/// without any ordering.+#[derive(Debug, Clone)]+pub struct EquivalenceClass {+ /// The expressions in this equivalence class. The order doesn't+ /// matter for equivalence purposes+ ///+ /// TODO: use a HashSet for this instead of a Vec+ exprs: Vec<Arc<dyn PhysicalExpr>>,+}++impl PartialEq for EquivalenceClass {+ /// Returns true if other is equal in the sense+ /// of bags (multi-sets), disregarding their orderings.+ fn eq(&self, other: &Self) -> bool {+ physical_exprs_bag_equal(&self.exprs, &other.exprs)+ }+}++impl EquivalenceClass {+ /// Create a new empty equivalence class+ pub fn new_empty() -> Self {+ Self { exprs: vec![] }+ }++ // Create a new equivalence class from a pre-existing `Vec`+ pub fn new(mut exprs: Vec<Arc<dyn PhysicalExpr>>) -> Self {+ deduplicate_physical_exprs(&mut exprs);+ Self { exprs }+ }++ /// Return the inner vector of expressions+ pub fn into_vec(self) -> Vec<Arc<dyn PhysicalExpr>> {+ self.exprs+ }++ /// Return the "canonical" expression for this class (the first element)+ /// if any+ fn canonical_expr(&self) -> Option<Arc<dyn PhysicalExpr>> {+ self.exprs.first().cloned()+ }++ /// Insert the expression into this class, meaning it is known to be equal to+ /// all other expressions in this class+ pub fn push(&mut self, expr: Arc<dyn PhysicalExpr>) {+ if !self.contains(&expr) {+ self.exprs.push(expr);+ }+ }++ /// Inserts all the expressions from other into this class+ pub fn extend(&mut self, other: Self) {+ for expr in other.exprs {+ // use push so entries are deduplicated+ self.push(expr);+ }+ }++ /// Returns true if this equivalence class contains t expression+ pub fn contains(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {+ physical_exprs_contains(&self.exprs, expr)+ }++ /// Returns true if this equivalence class has any entries in common with `other`+ pub fn contains_any(&self, other: &Self) -> bool {+ self.exprs.iter().any(|e| other.contains(e))+ }++ /// return the number of items in this class+ pub fn len(&self) -> usize {+ self.exprs.len()+ }++ /// return true if this class is empty+ pub fn is_empty(&self) -> bool {+ self.exprs.is_empty()+ }++ /// Iterate over all elements in this class, in some arbitrary order+ pub fn iter(&self) -> impl Iterator<Item = &Arc<dyn PhysicalExpr>> {+ self.exprs.iter()+ }++ /// Return a new equivalence class that have the specified offset added to+ /// each expression (used when schemas are appended such as in joins)+ pub fn with_offset(&self, offset: usize) -> Self {+ let new_exprs = self+ .exprs+ .iter()+ .cloned()+ .map(|e| add_offset_to_expr(e, offset))+ .collect();+ Self::new(new_exprs)+ }+}++/// An `EquivalenceGroup` is a collection of `EquivalenceClass`es where each+/// class represents a distinct equivalence class in a relation.+#[derive(Debug, Clone)]+pub struct EquivalenceGroup {+ pub classes: Vec<EquivalenceClass>,+}++impl EquivalenceGroup {+ /// Creates an empty equivalence group.+ pub fn empty() -> Self {+ Self { classes: vec![] }+ }++ /// Creates an equivalence group from the given equivalence classes.+ pub fn new(classes: Vec<EquivalenceClass>) -> Self {+ let mut result = Self { classes };+ result.remove_redundant_entries();+ result+ }++ /// Returns how many equivalence classes there are in this group.+ pub fn len(&self) -> usize {+ self.classes.len()+ }++ /// Checks whether this equivalence group is empty.+ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }++ /// Returns an iterator over the equivalence classes in this group.+ pub fn iter(&self) -> impl Iterator<Item = &EquivalenceClass> {+ self.classes.iter()+ }++ /// Adds the equality `left` = `right` to this equivalence group.+ /// New equality conditions often arise after steps like `Filter(a = b)`,+ /// `Alias(a, a as b)` etc.+ pub fn add_equal_conditions(+ &mut self,+ left: &Arc<dyn PhysicalExpr>,+ right: &Arc<dyn PhysicalExpr>,+ ) {+ let mut first_class = None;+ let mut second_class = None;+ for (idx, cls) in self.classes.iter().enumerate() {+ if cls.contains(left) {+ first_class = Some(idx);+ }+ if cls.contains(right) {+ second_class = Some(idx);+ }+ }+ match (first_class, second_class) {+ (Some(mut first_idx), Some(mut second_idx)) => {+ // If the given left and right sides belong to different classes,+ // we should unify/bridge these classes.+ if first_idx != second_idx {+ // By convention, make sure `second_idx` is larger than `first_idx`.+ if first_idx > second_idx {+ (first_idx, second_idx) = (second_idx, first_idx);+ }+ // Remove the class at `second_idx` and merge its values with+ // the class at `first_idx`. The convention above makes sure+ // that `first_idx` is still valid after removing `second_idx`.+ let other_class = self.classes.swap_remove(second_idx);+ self.classes[first_idx].extend(other_class);+ }+ }+ (Some(group_idx), None) => {+ // Right side is new, extend left side's class:+ self.classes[group_idx].push(right.clone());+ }+ (None, Some(group_idx)) => {+ // Left side is new, extend right side's class:+ self.classes[group_idx].push(left.clone());+ }+ (None, None) => {+ // None of the expressions is among existing classes.+ // Create a new equivalence class and extend the group.+ self.classes+ .push(EquivalenceClass::new(vec![left.clone(), right.clone()]));+ }+ }+ }++ /// Removes redundant entries from this group.+ fn remove_redundant_entries(&mut self) {+ // Remove duplicate entries from each equivalence class:+ self.classes.retain_mut(|cls| {+ // Keep groups that have at least two entries as singleton class is+ // meaningless (i.e. it contains no non-trivial information):+ cls.len() > 1+ });+ // Unify/bridge groups that have common expressions:+ self.bridge_classes()+ }++ /// This utility function unifies/bridges classes that have common expressions.+ /// For example, assume that we have [`EquivalenceClass`]es `[a, b]` and `[b, c]`.+ /// Since both classes contain `b`, columns `a`, `b` and `c` are actually all+ /// equal and belong to one class. This utility converts merges such classes.+ fn bridge_classes(&mut self) {+ let mut idx = 0;+ while idx < self.classes.len() {+ let mut next_idx = idx + 1;+ let start_size = self.classes[idx].len();+ while next_idx < self.classes.len() {+ if self.classes[idx].contains_any(&self.classes[next_idx]) {+ let extension = self.classes.swap_remove(next_idx);+ self.classes[idx].extend(extension);+ } else {+ next_idx += 1;+ }+ }+ if self.classes[idx].len() > start_size {+ continue;+ }+ idx += 1;+ }+ }++ /// Extends this equivalence group with the `other` equivalence group.+ pub fn extend(&mut self, other: Self) {+ self.classes.extend(other.classes);+ self.remove_redundant_entries();+ }++ /// Normalizes the given physical expression according to this group.+ /// The expression is replaced with the first expression in the equivalence+ /// class it matches with (if any).+ pub fn normalize_expr(&self, expr: Arc<dyn PhysicalExpr>) -> Arc<dyn PhysicalExpr> {+ expr.clone()+ .transform(&|expr| {+ for cls in self.iter() {+ if cls.contains(&expr) {+ return Ok(Transformed::Yes(cls.canonical_expr().unwrap()));+ }+ }+ Ok(Transformed::No(expr))+ })+ .unwrap_or(expr)+ }++ /// Normalizes the given sort expression according to this group.+ /// The underlying physical expression is replaced with the first expression+ /// in the equivalence class it matches with (if any). If the underlying+ /// expression does not belong to any equivalence class in this group, returns+ /// the sort expression as is.+ pub fn normalize_sort_expr(+ &self,+ mut sort_expr: PhysicalSortExpr,+ ) -> PhysicalSortExpr {+ sort_expr.expr = self.normalize_expr(sort_expr.expr);+ sort_expr+ }++ /// Normalizes the given sort requirement according to this group.+ /// The underlying physical expression is replaced with the first expression+ /// in the equivalence class it matches with (if any). If the underlying+ /// expression does not belong to any equivalence class in this group, returns+ /// the given sort requirement as is.+ pub fn normalize_sort_requirement(+ &self,+ mut sort_requirement: PhysicalSortRequirement,+ ) -> PhysicalSortRequirement {+ sort_requirement.expr = self.normalize_expr(sort_requirement.expr);+ sort_requirement+ }++ /// This function applies the `normalize_expr` function for all expressions+ /// in `exprs` and returns the corresponding normalized physical expressions.+ pub fn normalize_exprs(+ &self,+ exprs: impl IntoIterator<Item = Arc<dyn PhysicalExpr>>,+ ) -> Vec<Arc<dyn PhysicalExpr>> {+ exprs+ .into_iter()+ .map(|expr| self.normalize_expr(expr))+ .collect()+ }++ /// This function applies the `normalize_sort_expr` function for all sort+ /// expressions in `sort_exprs` and returns the corresponding normalized+ /// sort expressions.+ pub fn normalize_sort_exprs(&self, sort_exprs: LexOrderingRef) -> LexOrdering {+ // Convert sort expressions to sort requirements:+ let sort_reqs = PhysicalSortRequirement::from_sort_exprs(sort_exprs.iter());+ // Normalize the requirements:+ let normalized_sort_reqs = self.normalize_sort_requirements(&sort_reqs);+ // Convert sort requirements back to sort expressions:+ PhysicalSortRequirement::to_sort_exprs(normalized_sort_reqs)+ }++ /// This function applies the `normalize_sort_requirement` function for all+ /// requirements in `sort_reqs` and returns the corresponding normalized+ /// sort requirements.+ pub fn normalize_sort_requirements(+ &self,+ sort_reqs: LexRequirementRef,+ ) -> LexRequirement {+ collapse_lex_req(+ sort_reqs+ .iter()+ .map(|sort_req| self.normalize_sort_requirement(sort_req.clone()))+ .collect(),+ )+ }++ /// Projects `expr` according to the given projection mapping.+ /// If the resulting expression is invalid after projection, returns `None`.+ pub fn project_expr(+ &self,+ mapping: &ProjectionMapping,+ expr: &Arc<dyn PhysicalExpr>,+ ) -> Option<Arc<dyn PhysicalExpr>> {+ // First, we try to project expressions with an exact match. If we are+ // unable to do this, we consult equivalence classes.+ if let Some(target) = mapping.target_expr(expr) {+ // If we match the source, we can project directly:+ return Some(target);+ } else {+ // If the given expression is not inside the mapping, try to project+ // expressions considering the equivalence classes.+ for (source, target) in mapping.iter() {+ // If we match an equivalent expression to `source`, then we can+ // project. For example, if we have the mapping `(a as a1, a + c)`+ // and the equivalence class `(a, b)`, expression `b` projects to `a1`.+ if self+ .get_equivalence_class(source)+ .map_or(false, |group| group.contains(expr))+ {+ return Some(target.clone());+ }+ }+ }+ // Project a non-leaf expression by projecting its children.+ let children = expr.children();+ if children.is_empty() {+ // Leaf expression should be inside mapping.+ return None;+ }+ children+ .into_iter()+ .map(|child| self.project_expr(mapping, &child))+ .collect::<Option<Vec<_>>>()+ .map(|children| expr.clone().with_new_children(children).unwrap())+ }++ /// Projects this equivalence group according to the given projection mapping.+ pub fn project(&self, mapping: &ProjectionMapping) -> Self {+ let projected_classes = self.iter().filter_map(|cls| {+ let new_class = cls+ .iter()+ .filter_map(|expr| self.project_expr(mapping, expr))+ .collect::<Vec<_>>();+ (new_class.len() > 1).then_some(EquivalenceClass::new(new_class))+ });+ // TODO: Convert the algorithm below to a version that uses `HashMap`.+ // once `Arc<dyn PhysicalExpr>` can be stored in `HashMap`.+ // See issue: https://github.com/apache/arrow-datafusion/issues/8027+ let mut new_classes = vec![];+ for (source, target) in mapping.iter() {+ if new_classes.is_empty() {+ new_classes.push((source, vec![target.clone()]));+ }+ if let Some((_, values)) =+ new_classes.iter_mut().find(|(key, _)| key.eq(source))+ {+ if !physical_exprs_contains(values, target) {+ values.push(target.clone());+ }+ }+ }+ // Only add equivalence classes with at least two members as singleton+ // equivalence classes are meaningless.+ let new_classes = new_classes+ .into_iter()+ .filter_map(|(_, values)| (values.len() > 1).then_some(values))+ .map(EquivalenceClass::new);++ let classes = projected_classes.chain(new_classes).collect();+ Self::new(classes)+ }++ /// Returns the equivalence class containing `expr`. If no equivalence class+ /// contains `expr`, returns `None`.+ fn get_equivalence_class(+ &self,+ expr: &Arc<dyn PhysicalExpr>,+ ) -> Option<&EquivalenceClass> {+ self.iter().find(|cls| cls.contains(expr))+ }++ /// Combine equivalence groups of the given join children.+ pub fn join(+ &self,+ right_equivalences: &Self,+ join_type: &JoinType,+ left_size: usize,+ on: &[(Column, Column)],+ ) -> Self {+ match join_type {+ JoinType::Inner | JoinType::Left | JoinType::Full | JoinType::Right => {+ let mut result = Self::new(+ self.iter()+ .cloned()+ .chain(+ right_equivalences+ .iter()+ .map(|cls| cls.with_offset(left_size)),+ )+ .collect(),+ );+ // In we have an inner join, expressions in the "on" condition+ // are equal in the resulting table.+ if join_type == &JoinType::Inner {+ for (lhs, rhs) in on.iter() {+ let index = rhs.index() + left_size;+ let new_lhs = Arc::new(lhs.clone()) as _;+ let new_rhs = Arc::new(Column::new(rhs.name(), index)) as _;+ result.add_equal_conditions(&new_lhs, &new_rhs);+ }+ }+ result+ }+ JoinType::LeftSemi | JoinType::LeftAnti => self.clone(),+ JoinType::RightSemi | JoinType::RightAnti => right_equivalences.clone(),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::equivalence::tests::create_test_params;+ use crate::equivalence::{EquivalenceClass, EquivalenceGroup};+ use crate::expressions::lit;+ use crate::expressions::Column;+ use crate::expressions::Literal;+ use datafusion_common::Result;+ use datafusion_common::ScalarValue;+ use std::sync::Arc;++ #[test]+ fn test_bridge_groups() -> Result<()> {+ // First entry in the tuple is argument, second entry is the bridged result+ let test_cases = vec![+ // ------- TEST CASE 1 -----------//+ (+ vec![vec![1, 2, 3], vec![2, 4, 5], vec![11, 12, 9], vec![7, 6, 5]],+ // Expected is compared with set equality. Order of the specific results may change.+ vec![vec![1, 2, 3, 4, 5, 6, 7], vec![9, 11, 12]],+ ),+ // ------- TEST CASE 2 -----------//+ (+ vec![vec![1, 2, 3], vec![3, 4, 5], vec![9, 8, 7], vec![7, 6, 5]],+ // Expected+ vec![vec![1, 2, 3, 4, 5, 6, 7, 8, 9]],+ ),+ ];+ for (entries, expected) in test_cases {+ let entries = entries+ .into_iter()+ .map(|entry| entry.into_iter().map(lit).collect::<Vec<_>>())+ .map(EquivalenceClass::new)+ .collect::<Vec<_>>();+ let expected = expected+ .into_iter()+ .map(|entry| entry.into_iter().map(lit).collect::<Vec<_>>())+ .map(EquivalenceClass::new)+ .collect::<Vec<_>>();+ let mut eq_groups = EquivalenceGroup::new(entries.clone());+ eq_groups.bridge_classes();+ let eq_groups = eq_groups.classes;+ let err_msg = format!(+ "error in test entries: {:?}, expected: {:?}, actual:{:?}",+ entries, expected, eq_groups+ );+ assert_eq!(eq_groups.len(), expected.len(), "{}", err_msg);+ for idx in 0..eq_groups.len() {+ assert_eq!(&eq_groups[idx], &expected[idx], "{}", err_msg);+ }+ }+ Ok(())+ }++ #[test]+ fn test_remove_redundant_entries_eq_group() -> Result<()> {+ let entries = vec![+ EquivalenceClass::new(vec![lit(1), lit(1), lit(2)]),+ // This group is meaningless should be removed+ EquivalenceClass::new(vec![lit(3), lit(3)]),+ EquivalenceClass::new(vec![lit(4), lit(5), lit(6)]),+ ];+ // Given equivalences classes are not in succinct form.+ // Expected form is the most plain representation that is functionally same.+ let expected = vec![+ EquivalenceClass::new(vec![lit(1), lit(2)]),+ EquivalenceClass::new(vec![lit(4), lit(5), lit(6)]),+ ];+ let mut eq_groups = EquivalenceGroup::new(entries);+ eq_groups.remove_redundant_entries();++ let eq_groups = eq_groups.classes;+ assert_eq!(eq_groups.len(), expected.len());+ assert_eq!(eq_groups.len(), 2);++ assert_eq!(eq_groups[0], expected[0]);+ assert_eq!(eq_groups[1], expected[1]);+ Ok(())+ }++ #[test]+ fn test_schema_normalize_expr_with_equivalence() -> Result<()> {+ let col_a = &Column::new("a", 0);+ let col_b = &Column::new("b", 1);+ let col_c = &Column::new("c", 2);+ // Assume that column a and c are aliases.+ let (_test_schema, eq_properties) = create_test_params()?;++ let col_a_expr = Arc::new(col_a.clone()) as Arc<dyn PhysicalExpr>;+ let col_b_expr = Arc::new(col_b.clone()) as Arc<dyn PhysicalExpr>;+ let col_c_expr = Arc::new(col_c.clone()) as Arc<dyn PhysicalExpr>;+ // Test cases for equivalence normalization,+ // First entry in the tuple is argument, second entry is expected result after normalization.+ let expressions = vec![+ // Normalized version of the column a and c should go to a+ // (by convention all the expressions inside equivalence class are mapped to the first entry+ // in this case a is the first entry in the equivalence class.)+ (&col_a_expr, &col_a_expr),+ (&col_c_expr, &col_a_expr),+ // Cannot normalize column b+ (&col_b_expr, &col_b_expr),+ ];+ let eq_group = eq_properties.eq_group();+ for (expr, expected_eq) in expressions {+ assert!(+ expected_eq.eq(&eq_group.normalize_expr(expr.clone())),+ "error in test: expr: {expr:?}"+ );+ }++ Ok(())+ }++ #[test]+ fn test_contains_any() {+ let lit_true = Arc::new(Literal::new(ScalarValue::Boolean(Some(true))))+ as Arc<dyn PhysicalExpr>;+ let lit_false = Arc::new(Literal::new(ScalarValue::Boolean(Some(false))))+ as Arc<dyn PhysicalExpr>;+ let lit2 =+ Arc::new(Literal::new(ScalarValue::Int32(Some(2)))) as Arc<dyn PhysicalExpr>;+ let lit1 =+ Arc::new(Literal::new(ScalarValue::Int32(Some(1)))) as Arc<dyn PhysicalExpr>;+ let col_b_expr = Arc::new(Column::new("b", 1)) as Arc<dyn PhysicalExpr>;++ let cls1 = EquivalenceClass::new(vec![lit_true.clone(), lit_false.clone()]);+ let cls2 = EquivalenceClass::new(vec![lit_true.clone(), col_b_expr.clone()]);+ let cls3 = EquivalenceClass::new(vec![lit2.clone(), lit1.clone()]);++ // lit_true is common+ assert!(cls1.contains_any(&cls2));+ // there is no common entry+ assert!(!cls1.contains_any(&cls3));+ assert!(!cls2.contains_any(&cls3));+ }+}diff --git a/datafusion/physical-expr/src/equivalence/mod.rs b/datafusion/physical-expr/src/equivalence/mod.rsnew file mode 100644index 0000000000..387dce2cdc--- /dev/null+++ b/datafusion/physical-expr/src/equivalence/mod.rs@@ -0,0 +1,533 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++mod class;+mod ordering;+mod projection;+mod properties;+use crate::expressions::Column;+use crate::{LexRequirement, PhysicalExpr, PhysicalSortRequirement};+pub use class::{EquivalenceClass, EquivalenceGroup};+use datafusion_common::tree_node::{Transformed, TreeNode};+pub use ordering::OrderingEquivalenceClass;+pub use projection::ProjectionMapping;+pub use properties::{join_equivalence_properties, EquivalenceProperties};+use std::sync::Arc;++/// This function constructs a duplicate-free `LexOrderingReq` by filtering out+/// duplicate entries that have same physical expression inside. For example,+/// `vec![a Some(ASC), a Some(DESC)]` collapses to `vec![a Some(ASC)]`.+pub fn collapse_lex_req(input: LexRequirement) -> LexRequirement {+ let mut output = Vec::<PhysicalSortRequirement>::new();+ for item in input {+ if !output.iter().any(|req| req.expr.eq(&item.expr)) {+ output.push(item);+ }+ }+ output+}++/// 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 fn add_offset_to_expr(+ expr: Arc<dyn PhysicalExpr>,+ offset: usize,+) -> Arc<dyn PhysicalExpr> {+ expr.transform_down(&|e| match e.as_any().downcast_ref::<Column>() {+ Some(col) => Ok(Transformed::Yes(Arc::new(Column::new(+ col.name(),+ offset + col.index(),+ )))),+ None => Ok(Transformed::No(e)),+ })+ .unwrap()+ // Note that we can safely unwrap here since our transform always returns+ // an `Ok` value.+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::expressions::{col, Column};+ use crate::PhysicalSortExpr;+ use arrow::compute::{lexsort_to_indices, SortColumn};+ use arrow::datatypes::{DataType, Field, Schema};+ use arrow_array::{ArrayRef, Float64Array, RecordBatch, UInt32Array};+ use arrow_schema::{SchemaRef, SortOptions};+ use datafusion_common::{plan_datafusion_err, DataFusionError, Result};+ use itertools::izip;+ use rand::rngs::StdRng;+ use rand::seq::SliceRandom;+ use rand::{Rng, SeedableRng};+ use std::sync::Arc;++ pub fn output_schema(+ mapping: &ProjectionMapping,+ input_schema: &Arc<Schema>,+ ) -> Result<SchemaRef> {+ // Calculate output schema+ let fields: Result<Vec<Field>> = mapping+ .iter()+ .map(|(source, target)| {+ let name = target+ .as_any()+ .downcast_ref::<Column>()+ .ok_or_else(|| plan_datafusion_err!("Expects to have column"))?+ .name();+ let field = Field::new(+ name,+ source.data_type(input_schema)?,+ source.nullable(input_schema)?,+ );++ Ok(field)+ })+ .collect();++ let output_schema = Arc::new(Schema::new_with_metadata(+ fields?,+ input_schema.metadata().clone(),+ ));++ Ok(output_schema)+ }++ // Generate a schema which consists of 8 columns (a, b, c, d, e, f, g, h)+ pub fn create_test_schema() -> Result<SchemaRef> {+ let a = Field::new("a", DataType::Int32, true);+ let b = Field::new("b", DataType::Int32, true);+ let c = Field::new("c", DataType::Int32, true);+ let d = Field::new("d", DataType::Int32, true);+ let e = Field::new("e", DataType::Int32, true);+ let f = Field::new("f", DataType::Int32, true);+ let g = Field::new("g", DataType::Int32, true);+ let h = Field::new("h", DataType::Int32, true);+ let schema = Arc::new(Schema::new(vec![a, b, c, d, e, f, g, h]));++ Ok(schema)+ }++ /// Construct a schema with following properties+ /// Schema satisfies following orderings:+ /// [a ASC], [d ASC, b ASC], [e DESC, f ASC, g ASC]+ /// and+ /// Column [a=c] (e.g they are aliases).+ pub fn create_test_params() -> Result<(SchemaRef, EquivalenceProperties)> {+ let test_schema = create_test_schema()?;+ let col_a = &col("a", &test_schema)?;+ let col_b = &col("b", &test_schema)?;+ let col_c = &col("c", &test_schema)?;+ let col_d = &col("d", &test_schema)?;+ let col_e = &col("e", &test_schema)?;+ let col_f = &col("f", &test_schema)?;+ let col_g = &col("g", &test_schema)?;+ let mut eq_properties = EquivalenceProperties::new(test_schema.clone());+ eq_properties.add_equal_conditions(col_a, col_c);++ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ let option_desc = SortOptions {+ descending: true,+ nulls_first: true,+ };+ let orderings = vec![+ // [a ASC]+ vec![(col_a, option_asc)],+ // [d ASC, b ASC]+ vec![(col_d, option_asc), (col_b, option_asc)],+ // [e DESC, f ASC, g ASC]+ vec![+ (col_e, option_desc),+ (col_f, option_asc),+ (col_g, option_asc),+ ],+ ];+ let orderings = convert_to_orderings(&orderings);+ eq_properties.add_new_orderings(orderings);+ Ok((test_schema, eq_properties))+ }++ // Generate a schema which consists of 6 columns (a, b, c, d, e, f)+ fn create_test_schema_2() -> Result<SchemaRef> {+ let a = Field::new("a", DataType::Float64, true);+ let b = Field::new("b", DataType::Float64, true);+ let c = Field::new("c", DataType::Float64, true);+ let d = Field::new("d", DataType::Float64, true);+ let e = Field::new("e", DataType::Float64, true);+ let f = Field::new("f", DataType::Float64, true);+ let schema = Arc::new(Schema::new(vec![a, b, c, d, e, f]));++ Ok(schema)+ }++ /// Construct a schema with random ordering+ /// among column a, b, c, d+ /// where+ /// Column [a=f] (e.g they are aliases).+ /// Column e is constant.+ pub fn create_random_schema(seed: u64) -> Result<(SchemaRef, EquivalenceProperties)> {+ let test_schema = create_test_schema_2()?;+ let col_a = &col("a", &test_schema)?;+ let col_b = &col("b", &test_schema)?;+ let col_c = &col("c", &test_schema)?;+ let col_d = &col("d", &test_schema)?;+ let col_e = &col("e", &test_schema)?;+ let col_f = &col("f", &test_schema)?;+ let col_exprs = [col_a, col_b, col_c, col_d, col_e, col_f];++ let mut eq_properties = EquivalenceProperties::new(test_schema.clone());+ // Define a and f are aliases+ eq_properties.add_equal_conditions(col_a, col_f);+ // Column e has constant value.+ eq_properties = eq_properties.add_constants([col_e.clone()]);++ // Randomly order columns for sorting+ let mut rng = StdRng::seed_from_u64(seed);+ let mut remaining_exprs = col_exprs[0..4].to_vec(); // only a, b, c, d are sorted++ let options_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };++ while !remaining_exprs.is_empty() {+ let n_sort_expr = rng.gen_range(0..remaining_exprs.len() + 1);+ remaining_exprs.shuffle(&mut rng);++ let ordering = remaining_exprs+ .drain(0..n_sort_expr)+ .map(|expr| PhysicalSortExpr {+ expr: expr.clone(),+ options: options_asc,+ })+ .collect();++ eq_properties.add_new_orderings([ordering]);+ }++ Ok((test_schema, eq_properties))+ }++ // Convert each tuple to PhysicalSortRequirement+ pub fn convert_to_sort_reqs(+ in_data: &[(&Arc<dyn PhysicalExpr>, Option<SortOptions>)],+ ) -> Vec<PhysicalSortRequirement> {+ in_data+ .iter()+ .map(|(expr, options)| {+ PhysicalSortRequirement::new((*expr).clone(), *options)+ })+ .collect()+ }++ // Convert each tuple to PhysicalSortExpr+ pub fn convert_to_sort_exprs(+ in_data: &[(&Arc<dyn PhysicalExpr>, SortOptions)],+ ) -> Vec<PhysicalSortExpr> {+ in_data+ .iter()+ .map(|(expr, options)| PhysicalSortExpr {+ expr: (*expr).clone(),+ options: *options,+ })+ .collect()+ }++ // Convert each inner tuple to PhysicalSortExpr+ pub fn convert_to_orderings(+ orderings: &[Vec<(&Arc<dyn PhysicalExpr>, SortOptions)>],+ ) -> Vec<Vec<PhysicalSortExpr>> {+ orderings+ .iter()+ .map(|sort_exprs| convert_to_sort_exprs(sort_exprs))+ .collect()+ }++ // Convert each tuple to PhysicalSortExpr+ pub fn convert_to_sort_exprs_owned(+ in_data: &[(Arc<dyn PhysicalExpr>, SortOptions)],+ ) -> Vec<PhysicalSortExpr> {+ in_data+ .iter()+ .map(|(expr, options)| PhysicalSortExpr {+ expr: (*expr).clone(),+ options: *options,+ })+ .collect()+ }++ // Convert each inner tuple to PhysicalSortExpr+ pub fn convert_to_orderings_owned(+ orderings: &[Vec<(Arc<dyn PhysicalExpr>, SortOptions)>],+ ) -> Vec<Vec<PhysicalSortExpr>> {+ orderings+ .iter()+ .map(|sort_exprs| convert_to_sort_exprs_owned(sort_exprs))+ .collect()+ }++ // Apply projection to the input_data, return projected equivalence properties and record batch+ pub fn apply_projection(+ proj_exprs: Vec<(Arc<dyn PhysicalExpr>, String)>,+ input_data: &RecordBatch,+ input_eq_properties: &EquivalenceProperties,+ ) -> Result<(RecordBatch, EquivalenceProperties)> {+ let input_schema = input_data.schema();+ let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &input_schema)?;++ let output_schema = output_schema(&projection_mapping, &input_schema)?;+ let num_rows = input_data.num_rows();+ // Apply projection to the input record batch.+ let projected_values = projection_mapping+ .iter()+ .map(|(source, _target)| source.evaluate(input_data)?.into_array(num_rows))+ .collect::<Result<Vec<_>>>()?;+ let projected_batch = if projected_values.is_empty() {+ RecordBatch::new_empty(output_schema.clone())+ } else {+ RecordBatch::try_new(output_schema.clone(), projected_values)?+ };++ let projected_eq =+ input_eq_properties.project(&projection_mapping, output_schema);+ Ok((projected_batch, projected_eq))+ }++ #[test]+ fn add_equal_conditions_test() -> Result<()> {+ let schema = Arc::new(Schema::new(vec![+ Field::new("a", DataType::Int64, true),+ Field::new("b", DataType::Int64, true),+ Field::new("c", DataType::Int64, true),+ Field::new("x", DataType::Int64, true),+ Field::new("y", DataType::Int64, true),+ ]));++ let mut eq_properties = EquivalenceProperties::new(schema);+ let col_a_expr = Arc::new(Column::new("a", 0)) as Arc<dyn PhysicalExpr>;+ let col_b_expr = Arc::new(Column::new("b", 1)) as Arc<dyn PhysicalExpr>;+ let col_c_expr = Arc::new(Column::new("c", 2)) as Arc<dyn PhysicalExpr>;+ let col_x_expr = Arc::new(Column::new("x", 3)) as Arc<dyn PhysicalExpr>;+ let col_y_expr = Arc::new(Column::new("y", 4)) as Arc<dyn PhysicalExpr>;++ // a and b are aliases+ eq_properties.add_equal_conditions(&col_a_expr, &col_b_expr);+ assert_eq!(eq_properties.eq_group().len(), 1);++ // This new entry is redundant, size shouldn't increase+ eq_properties.add_equal_conditions(&col_b_expr, &col_a_expr);+ assert_eq!(eq_properties.eq_group().len(), 1);+ let eq_groups = &eq_properties.eq_group().classes[0];+ assert_eq!(eq_groups.len(), 2);+ assert!(eq_groups.contains(&col_a_expr));+ assert!(eq_groups.contains(&col_b_expr));++ // b and c are aliases. Exising equivalence class should expand,+ // however there shouldn't be any new equivalence class+ eq_properties.add_equal_conditions(&col_b_expr, &col_c_expr);+ assert_eq!(eq_properties.eq_group().len(), 1);+ let eq_groups = &eq_properties.eq_group().classes[0];+ assert_eq!(eq_groups.len(), 3);+ assert!(eq_groups.contains(&col_a_expr));+ assert!(eq_groups.contains(&col_b_expr));+ assert!(eq_groups.contains(&col_c_expr));++ // This is a new set of equality. Hence equivalent class count should be 2.+ eq_properties.add_equal_conditions(&col_x_expr, &col_y_expr);+ assert_eq!(eq_properties.eq_group().len(), 2);++ // This equality bridges distinct equality sets.+ // Hence equivalent class count should decrease from 2 to 1.+ eq_properties.add_equal_conditions(&col_x_expr, &col_a_expr);+ assert_eq!(eq_properties.eq_group().len(), 1);+ let eq_groups = &eq_properties.eq_group().classes[0];+ assert_eq!(eq_groups.len(), 5);+ assert!(eq_groups.contains(&col_a_expr));+ assert!(eq_groups.contains(&col_b_expr));+ assert!(eq_groups.contains(&col_c_expr));+ assert!(eq_groups.contains(&col_x_expr));+ assert!(eq_groups.contains(&col_y_expr));++ Ok(())+ }++ /// Checks if the table (RecordBatch) remains unchanged when sorted according to the provided `required_ordering`.+ ///+ /// The function works by adding a unique column of ascending integers to the original table. This column ensures+ /// that rows that are otherwise indistinguishable (e.g., if they have the same values in all other columns) can+ /// still be differentiated. When sorting the extended table, the unique column acts as a tie-breaker to produce+ /// deterministic sorting results.+ ///+ /// If the table remains the same after sorting with the added unique column, it indicates that the table was+ /// already sorted according to `required_ordering` to begin with.+ pub fn is_table_same_after_sort(+ mut required_ordering: Vec<PhysicalSortExpr>,+ batch: RecordBatch,+ ) -> Result<bool> {+ // Clone the original schema and columns+ let original_schema = batch.schema();+ let mut columns = batch.columns().to_vec();++ // Create a new unique column+ let n_row = batch.num_rows();+ let vals: Vec<usize> = (0..n_row).collect::<Vec<_>>();+ let vals: Vec<f64> = vals.into_iter().map(|val| val as f64).collect();+ let unique_col = Arc::new(Float64Array::from_iter_values(vals)) as ArrayRef;+ columns.push(unique_col.clone());++ // Create a new schema with the added unique column+ let unique_col_name = "unique";+ let unique_field =+ Arc::new(Field::new(unique_col_name, DataType::Float64, false));+ let fields: Vec<_> = original_schema+ .fields()+ .iter()+ .cloned()+ .chain(std::iter::once(unique_field))+ .collect();+ let schema = Arc::new(Schema::new(fields));++ // Create a new batch with the added column+ let new_batch = RecordBatch::try_new(schema.clone(), columns)?;++ // Add the unique column to the required ordering to ensure deterministic results+ required_ordering.push(PhysicalSortExpr {+ expr: Arc::new(Column::new(unique_col_name, original_schema.fields().len())),+ options: Default::default(),+ });++ // Convert the required ordering to a list of SortColumn+ let sort_columns = required_ordering+ .iter()+ .map(|order_expr| {+ let expr_result = order_expr.expr.evaluate(&new_batch)?;+ let values = expr_result.into_array(new_batch.num_rows())?;+ Ok(SortColumn {+ values,+ options: Some(order_expr.options),+ })+ })+ .collect::<Result<Vec<_>>>()?;++ // Check if the indices after sorting match the initial ordering+ let sorted_indices = lexsort_to_indices(&sort_columns, None)?;+ let original_indices = UInt32Array::from_iter_values(0..n_row as u32);++ Ok(sorted_indices == original_indices)+ }++ // If we already generated a random result for one of the+ // expressions in the equivalence classes. For other expressions in the same+ // equivalence class use same result. This util gets already calculated result, when available.+ fn get_representative_arr(+ eq_group: &EquivalenceClass,+ existing_vec: &[Option<ArrayRef>],+ schema: SchemaRef,+ ) -> Option<ArrayRef> {+ for expr in eq_group.iter() {+ let col = expr.as_any().downcast_ref::<Column>().unwrap();+ let (idx, _field) = schema.column_with_name(col.name()).unwrap();+ if let Some(res) = &existing_vec[idx] {+ return Some(res.clone());+ }+ }+ None+ }++ // Generate a table that satisfies the given equivalence properties; i.e.+ // equivalences, ordering equivalences, and constants.+ pub fn generate_table_for_eq_properties(+ eq_properties: &EquivalenceProperties,+ n_elem: usize,+ n_distinct: usize,+ ) -> Result<RecordBatch> {+ let mut rng = StdRng::seed_from_u64(23);++ let schema = eq_properties.schema();+ let mut schema_vec = vec![None; schema.fields.len()];++ // Utility closure to generate random array+ let mut generate_random_array = |num_elems: usize, max_val: usize| -> ArrayRef {+ let values: Vec<f64> = (0..num_elems)+ .map(|_| rng.gen_range(0..max_val) as f64 / 2.0)+ .collect();+ Arc::new(Float64Array::from_iter_values(values))+ };++ // Fill constant columns+ for constant in &eq_properties.constants {+ let col = constant.as_any().downcast_ref::<Column>().unwrap();+ let (idx, _field) = schema.column_with_name(col.name()).unwrap();+ let arr = Arc::new(Float64Array::from_iter_values(vec![0 as f64; n_elem]))+ as ArrayRef;+ schema_vec[idx] = Some(arr);+ }++ // Fill columns based on ordering equivalences+ for ordering in eq_properties.oeq_class.iter() {+ let (sort_columns, indices): (Vec<_>, Vec<_>) = ordering+ .iter()+ .map(|PhysicalSortExpr { expr, options }| {+ let col = expr.as_any().downcast_ref::<Column>().unwrap();+ let (idx, _field) = schema.column_with_name(col.name()).unwrap();+ let arr = generate_random_array(n_elem, n_distinct);+ (+ SortColumn {+ values: arr,+ options: Some(*options),+ },+ idx,+ )+ })+ .unzip();++ let sort_arrs = arrow::compute::lexsort(&sort_columns, None)?;+ for (idx, arr) in izip!(indices, sort_arrs) {+ schema_vec[idx] = Some(arr);+ }+ }++ // Fill columns based on equivalence groups+ for eq_group in eq_properties.eq_group.iter() {+ let representative_array =+ get_representative_arr(eq_group, &schema_vec, schema.clone())+ .unwrap_or_else(|| generate_random_array(n_elem, n_distinct));++ for expr in eq_group.iter() {+ let col = expr.as_any().downcast_ref::<Column>().unwrap();+ let (idx, _field) = schema.column_with_name(col.name()).unwrap();+ schema_vec[idx] = Some(representative_array.clone());+ }+ }++ let res: Vec<_> = schema_vec+ .into_iter()+ .zip(schema.fields.iter())+ .map(|(elem, field)| {+ (+ field.name(),+ // Generate random values for columns that do not occur in any of the groups (equivalence, ordering equivalence, constants)+ elem.unwrap_or_else(|| generate_random_array(n_elem, n_distinct)),+ )+ })+ .collect();++ Ok(RecordBatch::try_from_iter(res)?)+ }+}diff --git a/datafusion/physical-expr/src/equivalence/ordering.rs b/datafusion/physical-expr/src/equivalence/ordering.rsnew file mode 100644index 0000000000..1a414592ce--- /dev/null+++ b/datafusion/physical-expr/src/equivalence/ordering.rs@@ -0,0 +1,1159 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++use arrow_schema::SortOptions;+use std::hash::Hash;+use std::sync::Arc;++use crate::equivalence::add_offset_to_expr;+use crate::{LexOrdering, PhysicalExpr, PhysicalSortExpr};++/// An `OrderingEquivalenceClass` object keeps track of different alternative+/// orderings than can describe a schema. For example, consider the following table:+///+/// ```text+/// |a|b|c|d|+/// |1|4|3|1|+/// |2|3|3|2|+/// |3|1|2|2|+/// |3|2|1|3|+/// ```+///+/// Here, both `vec![a ASC, b ASC]` and `vec![c DESC, d ASC]` describe the table+/// ordering. In this case, we say that these orderings are equivalent.+#[derive(Debug, Clone, Eq, PartialEq, Hash)]+pub struct OrderingEquivalenceClass {+ pub orderings: Vec<LexOrdering>,+}++impl OrderingEquivalenceClass {+ /// Creates new empty ordering equivalence class.+ pub fn empty() -> Self {+ Self { orderings: vec![] }+ }++ /// Clears (empties) this ordering equivalence class.+ pub fn clear(&mut self) {+ self.orderings.clear();+ }++ /// Creates new ordering equivalence class from the given orderings.+ pub fn new(orderings: Vec<LexOrdering>) -> Self {+ let mut result = Self { orderings };+ result.remove_redundant_entries();+ result+ }++ /// Checks whether `ordering` is a member of this equivalence class.+ pub fn contains(&self, ordering: &LexOrdering) -> bool {+ self.orderings.contains(ordering)+ }++ /// Adds `ordering` to this equivalence class.+ #[allow(dead_code)]+ fn push(&mut self, ordering: LexOrdering) {+ self.orderings.push(ordering);+ // Make sure that there are no redundant orderings:+ self.remove_redundant_entries();+ }++ /// Checks whether this ordering equivalence class is empty.+ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }++ /// Returns an iterator over the equivalent orderings in this class.+ pub fn iter(&self) -> impl Iterator<Item = &LexOrdering> {+ self.orderings.iter()+ }++ /// Returns how many equivalent orderings there are in this class.+ pub fn len(&self) -> usize {+ self.orderings.len()+ }++ /// Extend this ordering equivalence class with the `other` class.+ pub fn extend(&mut self, other: Self) {+ self.orderings.extend(other.orderings);+ // Make sure that there are no redundant orderings:+ self.remove_redundant_entries();+ }++ /// Adds new orderings into this ordering equivalence class.+ pub fn add_new_orderings(+ &mut self,+ orderings: impl IntoIterator<Item = LexOrdering>,+ ) {+ self.orderings.extend(orderings);+ // Make sure that there are no redundant orderings:+ self.remove_redundant_entries();+ }++ /// Removes redundant orderings from this equivalence class. For instance,+ /// if we already have the ordering `[a ASC, b ASC, c DESC]`, then there is+ /// no need to keep ordering `[a ASC, b ASC]` in the state.+ fn remove_redundant_entries(&mut self) {+ let mut work = true;+ while work {+ work = false;+ let mut idx = 0;+ while idx < self.orderings.len() {+ let mut ordering_idx = idx + 1;+ let mut removal = self.orderings[idx].is_empty();+ while ordering_idx < self.orderings.len() {+ work |= resolve_overlap(&mut self.orderings, idx, ordering_idx);+ if self.orderings[idx].is_empty() {+ removal = true;+ break;+ }+ work |= resolve_overlap(&mut self.orderings, ordering_idx, idx);+ if self.orderings[ordering_idx].is_empty() {+ self.orderings.swap_remove(ordering_idx);+ } else {+ ordering_idx += 1;+ }+ }+ if removal {+ self.orderings.swap_remove(idx);+ } else {+ idx += 1;+ }+ }+ }+ }++ /// Returns the concatenation of all the orderings. This enables merge+ /// operations to preserve all equivalent orderings simultaneously.+ pub fn output_ordering(&self) -> Option<LexOrdering> {+ let output_ordering = self.orderings.iter().flatten().cloned().collect();+ let output_ordering = collapse_lex_ordering(output_ordering);+ (!output_ordering.is_empty()).then_some(output_ordering)+ }++ // Append orderings in `other` to all existing orderings in this equivalence+ // class.+ pub fn join_suffix(mut self, other: &Self) -> Self {+ let n_ordering = self.orderings.len();+ // Replicate entries before cross product+ let n_cross = std::cmp::max(n_ordering, other.len() * n_ordering);+ self.orderings = self+ .orderings+ .iter()+ .cloned()+ .cycle()+ .take(n_cross)+ .collect();+ // Suffix orderings of other to the current orderings.+ for (outer_idx, ordering) in other.iter().enumerate() {+ for idx in 0..n_ordering {+ // Calculate cross product index+ let idx = outer_idx * n_ordering + idx;+ self.orderings[idx].extend(ordering.iter().cloned());+ }+ }+ self+ }++ /// Adds `offset` value to the index of each expression inside this+ /// ordering equivalence class.+ pub fn add_offset(&mut self, offset: usize) {+ for ordering in self.orderings.iter_mut() {+ for sort_expr in ordering {+ sort_expr.expr = add_offset_to_expr(sort_expr.expr.clone(), offset);+ }+ }+ }++ /// Gets sort options associated with this expression if it is a leading+ /// ordering expression. Otherwise, returns `None`.+ pub fn get_options(&self, expr: &Arc<dyn PhysicalExpr>) -> Option<SortOptions> {+ for ordering in self.iter() {+ let leading_ordering = &ordering[0];+ if leading_ordering.expr.eq(expr) {+ return Some(leading_ordering.options);+ }+ }+ None+ }+}++/// This function constructs a duplicate-free `LexOrdering` by filtering out+/// duplicate entries that have same physical expression inside. For example,+/// `vec![a ASC, a DESC]` collapses to `vec![a ASC]`.+pub fn collapse_lex_ordering(input: LexOrdering) -> LexOrdering {+ let mut output = Vec::<PhysicalSortExpr>::new();+ for item in input {+ if !output.iter().any(|req| req.expr.eq(&item.expr)) {+ output.push(item);+ }+ }+ output+}++/// Trims `orderings[idx]` if some suffix of it overlaps with a prefix of+/// `orderings[pre_idx]`. Returns `true` if there is any overlap, `false` otherwise.+fn resolve_overlap(orderings: &mut [LexOrdering], idx: usize, pre_idx: usize) -> bool {+ let length = orderings[idx].len();+ let other_length = orderings[pre_idx].len();+ for overlap in 1..=length.min(other_length) {+ if orderings[idx][length - overlap..] == orderings[pre_idx][..overlap] {+ orderings[idx].truncate(length - overlap);+ return true;+ }+ }+ false+}++#[cfg(test)]+mod tests {+ use crate::equivalence::tests::{+ convert_to_orderings, convert_to_sort_exprs, create_random_schema,+ create_test_params, generate_table_for_eq_properties, is_table_same_after_sort,+ };+ use crate::equivalence::{tests::create_test_schema, EquivalenceProperties};+ use crate::equivalence::{+ EquivalenceClass, EquivalenceGroup, OrderingEquivalenceClass,+ };+ use crate::execution_props::ExecutionProps;+ use crate::expressions::Column;+ use crate::expressions::{col, BinaryExpr};+ use crate::functions::create_physical_expr;+ use crate::{PhysicalExpr, PhysicalSortExpr};+ use arrow::datatypes::{DataType, Field, Schema};+ use arrow_schema::SortOptions;+ use datafusion_common::Result;+ use datafusion_expr::{BuiltinScalarFunction, Operator};+ use itertools::Itertools;+ use std::sync::Arc;++ #[test]+ fn test_ordering_satisfy() -> Result<()> {+ let input_schema = Arc::new(Schema::new(vec![+ Field::new("a", DataType::Int64, true),+ Field::new("b", DataType::Int64, true),+ ]));+ let crude = vec![PhysicalSortExpr {+ expr: Arc::new(Column::new("a", 0)),+ options: SortOptions::default(),+ }];+ let finer = vec![+ PhysicalSortExpr {+ expr: Arc::new(Column::new("a", 0)),+ options: SortOptions::default(),+ },+ PhysicalSortExpr {+ expr: Arc::new(Column::new("b", 1)),+ options: SortOptions::default(),+ },+ ];+ // finer ordering satisfies, crude ordering should return true+ let mut eq_properties_finer = EquivalenceProperties::new(input_schema.clone());+ eq_properties_finer.oeq_class.push(finer.clone());+ assert!(eq_properties_finer.ordering_satisfy(&crude));++ // Crude ordering doesn't satisfy finer ordering. should return false+ let mut eq_properties_crude = EquivalenceProperties::new(input_schema.clone());+ eq_properties_crude.oeq_class.push(crude.clone());+ assert!(!eq_properties_crude.ordering_satisfy(&finer));+ Ok(())+ }++ #[test]+ fn test_ordering_satisfy_with_equivalence2() -> Result<()> {+ let test_schema = create_test_schema()?;+ let col_a = &col("a", &test_schema)?;+ let col_b = &col("b", &test_schema)?;+ let col_c = &col("c", &test_schema)?;+ let col_d = &col("d", &test_schema)?;+ let col_e = &col("e", &test_schema)?;+ let col_f = &col("f", &test_schema)?;+ let floor_a = &create_physical_expr(+ &BuiltinScalarFunction::Floor,+ &[col("a", &test_schema)?],+ &test_schema,+ &ExecutionProps::default(),+ )?;+ let floor_f = &create_physical_expr(+ &BuiltinScalarFunction::Floor,+ &[col("f", &test_schema)?],+ &test_schema,+ &ExecutionProps::default(),+ )?;+ let exp_a = &create_physical_expr(+ &BuiltinScalarFunction::Exp,+ &[col("a", &test_schema)?],+ &test_schema,+ &ExecutionProps::default(),+ )?;+ let a_plus_b = Arc::new(BinaryExpr::new(+ col_a.clone(),+ Operator::Plus,+ col_b.clone(),+ )) as Arc<dyn PhysicalExpr>;+ let options = SortOptions {+ descending: false,+ nulls_first: false,+ };++ let test_cases = vec![+ // ------------ TEST CASE 1 ------------+ (+ // orderings+ vec![+ // [a ASC, d ASC, b ASC]+ vec![(col_a, options), (col_d, options), (col_b, options)],+ // [c ASC]+ vec![(col_c, options)],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [a ASC, b ASC], requirement is not satisfied.+ vec![(col_a, options), (col_b, options)],+ // expected: requirement is not satisfied.+ false,+ ),+ // ------------ TEST CASE 2 ------------+ (+ // orderings+ vec![+ // [a ASC, c ASC, b ASC]+ vec![(col_a, options), (col_c, options), (col_b, options)],+ // [d ASC]+ vec![(col_d, options)],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [floor(a) ASC],+ vec![(floor_a, options)],+ // expected: requirement is satisfied.+ true,+ ),+ // ------------ TEST CASE 2.1 ------------+ (+ // orderings+ vec![+ // [a ASC, c ASC, b ASC]+ vec![(col_a, options), (col_c, options), (col_b, options)],+ // [d ASC]+ vec![(col_d, options)],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [floor(f) ASC], (Please note that a=f)+ vec![(floor_f, options)],+ // expected: requirement is satisfied.+ true,+ ),+ // ------------ TEST CASE 3 ------------+ (+ // orderings+ vec![+ // [a ASC, c ASC, b ASC]+ vec![(col_a, options), (col_c, options), (col_b, options)],+ // [d ASC]+ vec![(col_d, options)],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [a ASC, c ASC, a+b ASC],+ vec![(col_a, options), (col_c, options), (&a_plus_b, options)],+ // expected: requirement is satisfied.+ true,+ ),+ // ------------ TEST CASE 4 ------------+ (+ // orderings+ vec![+ // [a ASC, b ASC, c ASC, d ASC]+ vec![+ (col_a, options),+ (col_b, options),+ (col_c, options),+ (col_d, options),+ ],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [floor(a) ASC, a+b ASC],+ vec![(floor_a, options), (&a_plus_b, options)],+ // expected: requirement is satisfied.+ false,+ ),+ // ------------ TEST CASE 5 ------------+ (+ // orderings+ vec![+ // [a ASC, b ASC, c ASC, d ASC]+ vec![+ (col_a, options),+ (col_b, options),+ (col_c, options),+ (col_d, options),+ ],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [exp(a) ASC, a+b ASC],+ vec![(exp_a, options), (&a_plus_b, options)],+ // expected: requirement is not satisfied.+ // TODO: If we know that exp function is 1-to-1 function.+ // we could have deduced that above requirement is satisfied.+ false,+ ),+ // ------------ TEST CASE 6 ------------+ (+ // orderings+ vec![+ // [a ASC, d ASC, b ASC]+ vec![(col_a, options), (col_d, options), (col_b, options)],+ // [c ASC]+ vec![(col_c, options)],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [a ASC, d ASC, floor(a) ASC],+ vec![(col_a, options), (col_d, options), (floor_a, options)],+ // expected: requirement is satisfied.+ true,+ ),+ // ------------ TEST CASE 7 ------------+ (+ // orderings+ vec![+ // [a ASC, c ASC, b ASC]+ vec![(col_a, options), (col_c, options), (col_b, options)],+ // [d ASC]+ vec![(col_d, options)],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [a ASC, floor(a) ASC, a + b ASC],+ vec![(col_a, options), (floor_a, options), (&a_plus_b, options)],+ // expected: requirement is not satisfied.+ false,+ ),+ // ------------ TEST CASE 8 ------------+ (+ // orderings+ vec![+ // [a ASC, b ASC, c ASC]+ vec![(col_a, options), (col_b, options), (col_c, options)],+ // [d ASC]+ vec![(col_d, options)],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [a ASC, c ASC, floor(a) ASC, a + b ASC],+ vec![+ (col_a, options),+ (col_c, options),+ (&floor_a, options),+ (&a_plus_b, options),+ ],+ // expected: requirement is not satisfied.+ false,+ ),+ // ------------ TEST CASE 9 ------------+ (+ // orderings+ vec![+ // [a ASC, b ASC, c ASC, d ASC]+ vec![+ (col_a, options),+ (col_b, options),+ (col_c, options),+ (col_d, options),+ ],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [a ASC, b ASC, c ASC, floor(a) ASC],+ vec![+ (col_a, options),+ (col_b, options),+ (&col_c, options),+ (&floor_a, options),+ ],+ // expected: requirement is satisfied.+ true,+ ),+ // ------------ TEST CASE 10 ------------+ (+ // orderings+ vec![+ // [d ASC, b ASC]+ vec![(col_d, options), (col_b, options)],+ // [c ASC, a ASC]+ vec![(col_c, options), (col_a, options)],+ ],+ // equivalence classes+ vec![vec![col_a, col_f]],+ // constants+ vec![col_e],+ // requirement [c ASC, d ASC, a + b ASC],+ vec![(col_c, options), (col_d, options), (&a_plus_b, options)],+ // expected: requirement is satisfied.+ true,+ ),+ ];++ for (orderings, eq_group, constants, reqs, expected) in test_cases {+ let err_msg =+ format!("error in test orderings: {orderings:?}, eq_group: {eq_group:?}, constants: {constants:?}, reqs: {reqs:?}, expected: {expected:?}");+ let mut eq_properties = EquivalenceProperties::new(test_schema.clone());+ let orderings = convert_to_orderings(&orderings);+ eq_properties.add_new_orderings(orderings);+ let eq_group = eq_group+ .into_iter()+ .map(|eq_class| {+ let eq_classes = eq_class.into_iter().cloned().collect::<Vec<_>>();+ EquivalenceClass::new(eq_classes)+ })+ .collect::<Vec<_>>();+ let eq_group = EquivalenceGroup::new(eq_group);+ eq_properties.add_equivalence_group(eq_group);++ let constants = constants.into_iter().cloned();+ eq_properties = eq_properties.add_constants(constants);++ let reqs = convert_to_sort_exprs(&reqs);+ assert_eq!(+ eq_properties.ordering_satisfy(&reqs),+ expected,+ "{}",+ err_msg+ );+ }++ Ok(())+ }++ #[test]+ fn test_ordering_satisfy_with_equivalence() -> Result<()> {+ // Schema satisfies following orderings:+ // [a ASC], [d ASC, b ASC], [e DESC, f ASC, g ASC]+ // and+ // Column [a=c] (e.g they are aliases).+ let (test_schema, eq_properties) = create_test_params()?;+ let col_a = &col("a", &test_schema)?;+ let col_b = &col("b", &test_schema)?;+ let col_c = &col("c", &test_schema)?;+ let col_d = &col("d", &test_schema)?;+ let col_e = &col("e", &test_schema)?;+ let col_f = &col("f", &test_schema)?;+ let col_g = &col("g", &test_schema)?;+ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ let option_desc = SortOptions {+ descending: true,+ nulls_first: true,+ };+ let table_data_with_properties =+ generate_table_for_eq_properties(&eq_properties, 625, 5)?;++ // First element in the tuple stores vector of requirement, second element is the expected return value for ordering_satisfy function+ let requirements = vec![+ // `a ASC NULLS LAST`, expects `ordering_satisfy` to be `true`, since existing ordering `a ASC NULLS LAST, b ASC NULLS LAST` satisfies it+ (vec![(col_a, option_asc)], true),+ (vec![(col_a, option_desc)], false),+ // Test whether equivalence works as expected+ (vec![(col_c, option_asc)], true),+ (vec![(col_c, option_desc)], false),+ // Test whether ordering equivalence works as expected+ (vec![(col_d, option_asc)], true),+ (vec![(col_d, option_asc), (col_b, option_asc)], true),+ (vec![(col_d, option_desc), (col_b, option_asc)], false),+ (+ vec![+ (col_e, option_desc),+ (col_f, option_asc),+ (col_g, option_asc),+ ],+ true,+ ),+ (vec![(col_e, option_desc), (col_f, option_asc)], true),+ (vec![(col_e, option_asc), (col_f, option_asc)], false),+ (vec![(col_e, option_desc), (col_b, option_asc)], false),+ (vec![(col_e, option_asc), (col_b, option_asc)], false),+ (+ vec![+ (col_d, option_asc),+ (col_b, option_asc),+ (col_d, option_asc),+ (col_b, option_asc),+ ],+ true,+ ),+ (+ vec![+ (col_d, option_asc),+ (col_b, option_asc),+ (col_e, option_desc),+ (col_f, option_asc),+ ],+ true,+ ),+ (+ vec![+ (col_d, option_asc),+ (col_b, option_asc),+ (col_e, option_desc),+ (col_b, option_asc),+ ],+ true,+ ),+ (+ vec![+ (col_d, option_asc),+ (col_b, option_asc),+ (col_d, option_desc),+ (col_b, option_asc),+ ],+ true,+ ),+ (+ vec![+ (col_d, option_asc),+ (col_b, option_asc),+ (col_e, option_asc),+ (col_f, option_asc),+ ],+ false,+ ),+ (+ vec![+ (col_d, option_asc),+ (col_b, option_asc),+ (col_e, option_asc),+ (col_b, option_asc),+ ],+ false,+ ),+ (vec![(col_d, option_asc), (col_e, option_desc)], true),+ (+ vec![+ (col_d, option_asc),+ (col_c, option_asc),+ (col_b, option_asc),+ ],+ true,+ ),+ (+ vec![+ (col_d, option_asc),+ (col_e, option_desc),+ (col_f, option_asc),+ (col_b, option_asc),+ ],+ true,+ ),+ (+ vec![+ (col_d, option_asc),+ (col_e, option_desc),+ (col_c, option_asc),+ (col_b, option_asc),+ ],+ true,+ ),+ (+ vec![+ (col_d, option_asc),+ (col_e, option_desc),+ (col_b, option_asc),+ (col_f, option_asc),+ ],+ true,+ ),+ ];++ for (cols, expected) in requirements {+ let err_msg = format!("Error in test case:{cols:?}");+ let required = cols+ .into_iter()+ .map(|(expr, options)| PhysicalSortExpr {+ expr: expr.clone(),+ options,+ })+ .collect::<Vec<_>>();++ // Check expected result with experimental result.+ assert_eq!(+ is_table_same_after_sort(+ required.clone(),+ table_data_with_properties.clone()+ )?,+ expected+ );+ assert_eq!(+ eq_properties.ordering_satisfy(&required),+ expected,+ "{err_msg}"+ );+ }+ Ok(())+ }++ #[test]+ fn test_ordering_satisfy_with_equivalence_random() -> Result<()> {+ const N_RANDOM_SCHEMA: usize = 5;+ const N_ELEMENTS: usize = 125;+ const N_DISTINCT: usize = 5;+ const SORT_OPTIONS: SortOptions = SortOptions {+ descending: false,+ nulls_first: false,+ };++ for seed in 0..N_RANDOM_SCHEMA {+ // Create a random schema with random properties+ let (test_schema, eq_properties) = create_random_schema(seed as u64)?;+ // Generate a data that satisfies properties given+ let table_data_with_properties =+ generate_table_for_eq_properties(&eq_properties, N_ELEMENTS, N_DISTINCT)?;+ let col_exprs = vec![+ col("a", &test_schema)?,+ col("b", &test_schema)?,+ col("c", &test_schema)?,+ col("d", &test_schema)?,+ col("e", &test_schema)?,+ col("f", &test_schema)?,+ ];++ for n_req in 0..=col_exprs.len() {+ for exprs in col_exprs.iter().combinations(n_req) {+ let requirement = exprs+ .into_iter()+ .map(|expr| PhysicalSortExpr {+ expr: expr.clone(),+ options: SORT_OPTIONS,+ })+ .collect::<Vec<_>>();+ let expected = is_table_same_after_sort(+ requirement.clone(),+ table_data_with_properties.clone(),+ )?;+ let err_msg = format!(+ "Error in test case requirement:{:?}, expected: {:?}, eq_properties.oeq_class: {:?}, eq_properties.eq_group: {:?}, eq_properties.constants: {:?}",+ requirement, expected, eq_properties.oeq_class, eq_properties.eq_group, eq_properties.constants+ );+ // Check whether ordering_satisfy API result and+ // experimental result matches.+ assert_eq!(+ eq_properties.ordering_satisfy(&requirement),+ expected,+ "{}",+ err_msg+ );+ }+ }+ }++ Ok(())+ }++ #[test]+ fn test_ordering_satisfy_with_equivalence_complex_random() -> Result<()> {+ const N_RANDOM_SCHEMA: usize = 100;+ const N_ELEMENTS: usize = 125;+ const N_DISTINCT: usize = 5;+ const SORT_OPTIONS: SortOptions = SortOptions {+ descending: false,+ nulls_first: false,+ };++ for seed in 0..N_RANDOM_SCHEMA {+ // Create a random schema with random properties+ let (test_schema, eq_properties) = create_random_schema(seed as u64)?;+ // Generate a data that satisfies properties given+ let table_data_with_properties =+ generate_table_for_eq_properties(&eq_properties, N_ELEMENTS, N_DISTINCT)?;++ let floor_a = create_physical_expr(+ &BuiltinScalarFunction::Floor,+ &[col("a", &test_schema)?],+ &test_schema,+ &ExecutionProps::default(),+ )?;+ let a_plus_b = Arc::new(BinaryExpr::new(+ col("a", &test_schema)?,+ Operator::Plus,+ col("b", &test_schema)?,+ )) as Arc<dyn PhysicalExpr>;+ let exprs = vec![+ col("a", &test_schema)?,+ col("b", &test_schema)?,+ col("c", &test_schema)?,+ col("d", &test_schema)?,+ col("e", &test_schema)?,+ col("f", &test_schema)?,+ floor_a,+ a_plus_b,+ ];++ for n_req in 0..=exprs.len() {+ for exprs in exprs.iter().combinations(n_req) {+ let requirement = exprs+ .into_iter()+ .map(|expr| PhysicalSortExpr {+ expr: expr.clone(),+ options: SORT_OPTIONS,+ })+ .collect::<Vec<_>>();+ let expected = is_table_same_after_sort(+ requirement.clone(),+ table_data_with_properties.clone(),+ )?;+ let err_msg = format!(+ "Error in test case requirement:{:?}, expected: {:?}, eq_properties.oeq_class: {:?}, eq_properties.eq_group: {:?}, eq_properties.constants: {:?}",+ requirement, expected, eq_properties.oeq_class, eq_properties.eq_group, eq_properties.constants+ );+ // Check whether ordering_satisfy API result and+ // experimental result matches.++ assert_eq!(+ eq_properties.ordering_satisfy(&requirement),+ (expected | false),+ "{}",+ err_msg+ );+ }+ }+ }++ Ok(())+ }++ #[test]+ fn test_ordering_satisfy_different_lengths() -> Result<()> {+ let test_schema = create_test_schema()?;+ let col_a = &col("a", &test_schema)?;+ let col_b = &col("b", &test_schema)?;+ let col_c = &col("c", &test_schema)?;+ let col_d = &col("d", &test_schema)?;+ let col_e = &col("e", &test_schema)?;+ let col_f = &col("f", &test_schema)?;+ let options = SortOptions {+ descending: false,+ nulls_first: false,+ };+ // a=c (e.g they are aliases).+ let mut eq_properties = EquivalenceProperties::new(test_schema);+ eq_properties.add_equal_conditions(col_a, col_c);++ let orderings = vec![+ vec![(col_a, options)],+ vec![(col_e, options)],+ vec![(col_d, options), (col_f, options)],+ ];+ let orderings = convert_to_orderings(&orderings);++ // Column [a ASC], [e ASC], [d ASC, f ASC] are all valid orderings for the schema.+ eq_properties.add_new_orderings(orderings);++ // First entry in the tuple is required ordering, second entry is the expected flag+ // that indicates whether this required ordering is satisfied.+ // ([a ASC], true) indicate a ASC requirement is already satisfied by existing orderings.+ let test_cases = vec![+ // [c ASC, a ASC, e ASC], expected represents this requirement is satisfied+ (+ vec![(col_c, options), (col_a, options), (col_e, options)],+ true,+ ),+ (vec![(col_c, options), (col_b, options)], false),+ (vec![(col_c, options), (col_d, options)], true),+ (+ vec![(col_d, options), (col_f, options), (col_b, options)],+ false,+ ),+ (vec![(col_d, options), (col_f, options)], true),+ ];++ for (reqs, expected) in test_cases {+ let err_msg =+ format!("error in test reqs: {:?}, expected: {:?}", reqs, expected,);+ let reqs = convert_to_sort_exprs(&reqs);+ assert_eq!(+ eq_properties.ordering_satisfy(&reqs),+ expected,+ "{}",+ err_msg+ );+ }++ Ok(())+ }++ #[test]+ fn test_remove_redundant_entries_oeq_class() -> Result<()> {+ let schema = create_test_schema()?;+ let col_a = &col("a", &schema)?;+ let col_b = &col("b", &schema)?;+ let col_c = &col("c", &schema)?;+ let col_d = &col("d", &schema)?;+ let col_e = &col("e", &schema)?;++ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ let option_desc = SortOptions {+ descending: true,+ nulls_first: true,+ };++ // First entry in the tuple is the given orderings for the table+ // Second entry is the simplest version of the given orderings that is functionally equivalent.+ let test_cases = vec![+ // ------- TEST CASE 1 ---------+ (+ // ORDERINGS GIVEN+ vec![+ // [a ASC, b ASC]+ vec![(col_a, option_asc), (col_b, option_asc)],+ ],+ // EXPECTED orderings that is succinct.+ vec![+ // [a ASC, b ASC]+ vec![(col_a, option_asc), (col_b, option_asc)],+ ],+ ),+ // ------- TEST CASE 2 ---------+ (+ // ORDERINGS GIVEN+ vec![+ // [a ASC, b ASC]+ vec![(col_a, option_asc), (col_b, option_asc)],+ // [a ASC, b ASC, c ASC]+ vec![+ (col_a, option_asc),+ (col_b, option_asc),+ (col_c, option_asc),+ ],+ ],+ // EXPECTED orderings that is succinct.+ vec![+ // [a ASC, b ASC, c ASC]+ vec![+ (col_a, option_asc),+ (col_b, option_asc),+ (col_c, option_asc),+ ],+ ],+ ),+ // ------- TEST CASE 3 ---------+ (+ // ORDERINGS GIVEN+ vec![+ // [a ASC, b DESC]+ vec![(col_a, option_asc), (col_b, option_desc)],+ // [a ASC]+ vec![(col_a, option_asc)],+ // [a ASC, c ASC]+ vec![(col_a, option_asc), (col_c, option_asc)],+ ],+ // EXPECTED orderings that is succinct.+ vec![+ // [a ASC, b DESC]+ vec![(col_a, option_asc), (col_b, option_desc)],+ // [a ASC, c ASC]+ vec![(col_a, option_asc), (col_c, option_asc)],+ ],+ ),+ // ------- TEST CASE 4 ---------+ (+ // ORDERINGS GIVEN+ vec![+ // [a ASC, b ASC]+ vec![(col_a, option_asc), (col_b, option_asc)],+ // [a ASC, b ASC, c ASC]+ vec![+ (col_a, option_asc),+ (col_b, option_asc),+ (col_c, option_asc),+ ],+ // [a ASC]+ vec![(col_a, option_asc)],+ ],+ // EXPECTED orderings that is succinct.+ vec![+ // [a ASC, b ASC, c ASC]+ vec![+ (col_a, option_asc),+ (col_b, option_asc),+ (col_c, option_asc),+ ],+ ],+ ),+ // ------- TEST CASE 5 ---------+ // Empty ordering+ (+ vec![vec![]],+ // No ordering in the state (empty ordering is ignored).+ vec![],+ ),+ // ------- TEST CASE 6 ---------+ (+ // ORDERINGS GIVEN+ vec![+ // [a ASC, b ASC]+ vec![(col_a, option_asc), (col_b, option_asc)],+ // [b ASC]+ vec![(col_b, option_asc)],+ ],+ // EXPECTED orderings that is succinct.+ vec![+ // [a ASC]+ vec![(col_a, option_asc)],+ // [b ASC]+ vec![(col_b, option_asc)],+ ],+ ),+ // ------- TEST CASE 7 ---------+ // b, a+ // c, a+ // d, b, c+ (+ // ORDERINGS GIVEN+ vec![+ // [b ASC, a ASC]+ vec![(col_b, option_asc), (col_a, option_asc)],+ // [c ASC, a ASC]+ vec![(col_c, option_asc), (col_a, option_asc)],+ // [d ASC, b ASC, c ASC]+ vec![+ (col_d, option_asc),+ (col_b, option_asc),+ (col_c, option_asc),+ ],+ ],+ // EXPECTED orderings that is succinct.+ vec![+ // [b ASC, a ASC]+ vec![(col_b, option_asc), (col_a, option_asc)],+ // [c ASC, a ASC]+ vec![(col_c, option_asc), (col_a, option_asc)],+ // [d ASC]+ vec![(col_d, option_asc)],+ ],+ ),+ // ------- TEST CASE 8 ---------+ // b, e+ // c, a+ // d, b, e, c, a+ (+ // ORDERINGS GIVEN+ vec![+ // [b ASC, e ASC]+ vec![(col_b, option_asc), (col_e, option_asc)],+ // [c ASC, a ASC]+ vec![(col_c, option_asc), (col_a, option_asc)],+ // [d ASC, b ASC, e ASC, c ASC, a ASC]+ vec![+ (col_d, option_asc),+ (col_b, option_asc),+ (col_e, option_asc),+ (col_c, option_asc),+ (col_a, option_asc),+ ],+ ],+ // EXPECTED orderings that is succinct.+ vec![+ // [b ASC, e ASC]+ vec![(col_b, option_asc), (col_e, option_asc)],+ // [c ASC, a ASC]+ vec![(col_c, option_asc), (col_a, option_asc)],+ // [d ASC]+ vec![(col_d, option_asc)],+ ],+ ),+ // ------- TEST CASE 9 ---------+ // b+ // a, b, c+ // d, a, b+ (+ // ORDERINGS GIVEN+ vec![+ // [b ASC]+ vec![(col_b, option_asc)],+ // [a ASC, b ASC, c ASC]+ vec![+ (col_a, option_asc),+ (col_b, option_asc),+ (col_c, option_asc),+ ],+ // [d ASC, a ASC, b ASC]+ vec![+ (col_d, option_asc),+ (col_a, option_asc),+ (col_b, option_asc),+ ],+ ],+ // EXPECTED orderings that is succinct.+ vec![+ // [b ASC]+ vec![(col_b, option_asc)],+ // [a ASC, b ASC, c ASC]+ vec![+ (col_a, option_asc),+ (col_b, option_asc),+ (col_c, option_asc),+ ],+ // [d ASC]+ vec![(col_d, option_asc)],+ ],+ ),+ ];+ for (orderings, expected) in test_cases {+ let orderings = convert_to_orderings(&orderings);+ let expected = convert_to_orderings(&expected);+ let actual = OrderingEquivalenceClass::new(orderings.clone());+ let actual = actual.orderings;+ let err_msg = format!(+ "orderings: {:?}, expected: {:?}, actual :{:?}",+ orderings, expected, actual+ );+ assert_eq!(actual.len(), expected.len(), "{}", err_msg);+ for elem in actual {+ assert!(expected.contains(&elem), "{}", err_msg);+ }+ }++ Ok(())+ }+}diff --git a/datafusion/physical-expr/src/equivalence/projection.rs b/datafusion/physical-expr/src/equivalence/projection.rsnew file mode 100644index 0000000000..0f92b2c2f4--- /dev/null+++ b/datafusion/physical-expr/src/equivalence/projection.rs@@ -0,0 +1,1153 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// 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::expressions::Column;+use crate::PhysicalExpr;++use arrow::datatypes::SchemaRef;+use datafusion_common::tree_node::{Transformed, TreeNode};+use datafusion_common::Result;++/// Stores the mapping between source expressions and target expressions for a+/// projection.+#[derive(Debug, Clone)]+pub struct ProjectionMapping {+ /// Mapping between source expressions and target expressions.+ /// Vector indices correspond to the indices after projection.+ pub map: Vec<(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)>,+}++impl ProjectionMapping {+ /// Constructs the mapping between a projection's input and output+ /// expressions.+ ///+ /// For example, given the input projection expressions (`a + b`, `c + d`)+ /// and an output schema with two columns `"c + d"` and `"a + b"`, the+ /// projection mapping would be:+ ///+ /// ```text+ /// [0]: (c + d, col("c + d"))+ /// [1]: (a + b, col("a + b"))+ /// ```+ ///+ /// where `col("c + d")` means the column named `"c + d"`.+ pub fn try_new(+ expr: &[(Arc<dyn PhysicalExpr>, String)],+ input_schema: &SchemaRef,+ ) -> Result<Self> {+ // Construct a map from the input expressions to the output expression of the projection:+ expr.iter()+ .enumerate()+ .map(|(expr_idx, (expression, name))| {+ let target_expr = Arc::new(Column::new(name, expr_idx)) as _;+ expression+ .clone()+ .transform_down(&|e| match e.as_any().downcast_ref::<Column>() {+ Some(col) => {+ // Sometimes, an expression and its name in the input_schema+ // doesn't match. This can cause problems, so we make sure+ // that the expression name matches with the name in `input_schema`.+ // Conceptually, `source_expr` and `expression` should be the same.+ let idx = col.index();+ let matching_input_field = input_schema.field(idx);+ let matching_input_column =+ Column::new(matching_input_field.name(), idx);+ Ok(Transformed::Yes(Arc::new(matching_input_column)))+ }+ None => Ok(Transformed::No(e)),+ })+ .map(|source_expr| (source_expr, target_expr))+ })+ .collect::<Result<Vec<_>>>()+ .map(|map| Self { map })+ }++ /// Iterate over pairs of (source, target) expressions+ pub fn iter(+ &self,+ ) -> impl Iterator<Item = &(Arc<dyn PhysicalExpr>, Arc<dyn PhysicalExpr>)> + '_ {+ self.map.iter()+ }++ /// This function returns the target expression for a given source expression.+ ///+ /// # Arguments+ ///+ /// * `expr` - Source physical expression.+ ///+ /// # Returns+ ///+ /// An `Option` containing the target for the given source expression,+ /// where a `None` value means that `expr` is not inside the mapping.+ pub fn target_expr(+ &self,+ expr: &Arc<dyn PhysicalExpr>,+ ) -> Option<Arc<dyn PhysicalExpr>> {+ self.map+ .iter()+ .find(|(source, _)| source.eq(expr))+ .map(|(_, target)| target.clone())+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::equivalence::tests::{+ apply_projection, convert_to_orderings, convert_to_orderings_owned,+ create_random_schema, generate_table_for_eq_properties, is_table_same_after_sort,+ output_schema,+ };+ use crate::equivalence::EquivalenceProperties;+ use crate::execution_props::ExecutionProps;+ use crate::expressions::{col, BinaryExpr, Literal};+ use crate::functions::create_physical_expr;+ use crate::PhysicalSortExpr;+ use arrow::datatypes::{DataType, Field, Schema};+ use arrow_schema::{SortOptions, TimeUnit};+ use datafusion_common::{Result, ScalarValue};+ use datafusion_expr::{BuiltinScalarFunction, Operator};+ use itertools::Itertools;+ use std::sync::Arc;++ #[test]+ fn project_orderings() -> Result<()> {+ let schema = Arc::new(Schema::new(vec![+ Field::new("a", DataType::Int32, true),+ Field::new("b", DataType::Int32, true),+ Field::new("c", DataType::Int32, true),+ Field::new("d", DataType::Int32, true),+ Field::new("e", DataType::Int32, true),+ Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),+ ]));+ let col_a = &col("a", &schema)?;+ let col_b = &col("b", &schema)?;+ let col_c = &col("c", &schema)?;+ let col_d = &col("d", &schema)?;+ let col_e = &col("e", &schema)?;+ let col_ts = &col("ts", &schema)?;+ let interval = Arc::new(Literal::new(ScalarValue::IntervalDayTime(Some(2))))+ as Arc<dyn PhysicalExpr>;+ let date_bin_func = &create_physical_expr(+ &BuiltinScalarFunction::DateBin,+ &[interval, col_ts.clone()],+ &schema,+ &ExecutionProps::default(),+ )?;+ let a_plus_b = Arc::new(BinaryExpr::new(+ col_a.clone(),+ Operator::Plus,+ col_b.clone(),+ )) as Arc<dyn PhysicalExpr>;+ let b_plus_d = Arc::new(BinaryExpr::new(+ col_b.clone(),+ Operator::Plus,+ col_d.clone(),+ )) as Arc<dyn PhysicalExpr>;+ let b_plus_e = Arc::new(BinaryExpr::new(+ col_b.clone(),+ Operator::Plus,+ col_e.clone(),+ )) as Arc<dyn PhysicalExpr>;+ let c_plus_d = Arc::new(BinaryExpr::new(+ col_c.clone(),+ Operator::Plus,+ col_d.clone(),+ )) as Arc<dyn PhysicalExpr>;++ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ let option_desc = SortOptions {+ descending: true,+ nulls_first: true,+ };++ let test_cases = vec![+ // ---------- TEST CASE 1 ------------+ (+ // orderings+ vec![+ // [b ASC]+ vec![(col_b, option_asc)],+ ],+ // projection exprs+ vec![(col_b, "b_new".to_string()), (col_a, "a_new".to_string())],+ // expected+ vec![+ // [b_new ASC]+ vec![("b_new", option_asc)],+ ],+ ),+ // ---------- TEST CASE 2 ------------+ (+ // orderings+ vec![+ // empty ordering+ ],+ // projection exprs+ vec![(col_c, "c_new".to_string()), (col_b, "b_new".to_string())],+ // expected+ vec![+ // no ordering at the output+ ],+ ),+ // ---------- TEST CASE 3 ------------+ (+ // orderings+ vec![+ // [ts ASC]+ vec![(col_ts, option_asc)],+ ],+ // projection exprs+ vec![+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (col_ts, "ts_new".to_string()),+ (date_bin_func, "date_bin_res".to_string()),+ ],+ // expected+ vec![+ // [date_bin_res ASC]+ vec![("date_bin_res", option_asc)],+ // [ts_new ASC]+ vec![("ts_new", option_asc)],+ ],+ ),+ // ---------- TEST CASE 4 ------------+ (+ // orderings+ vec![+ // [a ASC, ts ASC]+ vec![(col_a, option_asc), (col_ts, option_asc)],+ // [b ASC, ts ASC]+ vec![(col_b, option_asc), (col_ts, option_asc)],+ ],+ // projection exprs+ vec![+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (col_ts, "ts_new".to_string()),+ (date_bin_func, "date_bin_res".to_string()),+ ],+ // expected+ vec![+ // [a_new ASC, ts_new ASC]+ vec![("a_new", option_asc), ("ts_new", option_asc)],+ // [a_new ASC, date_bin_res ASC]+ vec![("a_new", option_asc), ("date_bin_res", option_asc)],+ // [b_new ASC, ts_new ASC]+ vec![("b_new", option_asc), ("ts_new", option_asc)],+ // [b_new ASC, date_bin_res ASC]+ vec![("b_new", option_asc), ("date_bin_res", option_asc)],+ ],+ ),+ // ---------- TEST CASE 5 ------------+ (+ // orderings+ vec![+ // [a + b ASC]+ vec![(&a_plus_b, option_asc)],+ ],+ // projection exprs+ vec![+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (&a_plus_b, "a+b".to_string()),+ ],+ // expected+ vec![+ // [a + b ASC]+ vec![("a+b", option_asc)],+ ],+ ),+ // ---------- TEST CASE 6 ------------+ (+ // orderings+ vec![+ // [a + b ASC, c ASC]+ vec![(&a_plus_b, option_asc), (&col_c, option_asc)],+ ],+ // projection exprs+ vec![+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (col_c, "c_new".to_string()),+ (&a_plus_b, "a+b".to_string()),+ ],+ // expected+ vec![+ // [a + b ASC, c_new ASC]+ vec![("a+b", option_asc), ("c_new", option_asc)],+ ],+ ),+ // ------- TEST CASE 7 ----------+ (+ vec![+ // [a ASC, b ASC, c ASC]+ vec![(col_a, option_asc), (col_b, option_asc)],+ // [a ASC, d ASC]+ vec![(col_a, option_asc), (col_d, option_asc)],+ ],+ // b as b_new, a as a_new, d as d_new b+d+ vec![+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (col_d, "d_new".to_string()),+ (&b_plus_d, "b+d".to_string()),+ ],+ // expected+ vec![+ // [a_new ASC, b_new ASC]+ vec![("a_new", option_asc), ("b_new", option_asc)],+ // [a_new ASC, d_new ASC]+ vec![("a_new", option_asc), ("d_new", option_asc)],+ // [a_new ASC, b+d ASC]+ vec![("a_new", option_asc), ("b+d", option_asc)],+ ],+ ),+ // ------- TEST CASE 8 ----------+ (+ // orderings+ vec![+ // [b+d ASC]+ vec![(&b_plus_d, option_asc)],+ ],+ // proj exprs+ vec![+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (col_d, "d_new".to_string()),+ (&b_plus_d, "b+d".to_string()),+ ],+ // expected+ vec![+ // [b+d ASC]+ vec![("b+d", option_asc)],+ ],+ ),+ // ------- TEST CASE 9 ----------+ (+ // orderings+ vec![+ // [a ASC, d ASC, b ASC]+ vec![+ (col_a, option_asc),+ (col_d, option_asc),+ (col_b, option_asc),+ ],+ // [c ASC]+ vec![(col_c, option_asc)],+ ],+ // proj exprs+ vec![+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (col_d, "d_new".to_string()),+ (col_c, "c_new".to_string()),+ ],+ // expected+ vec![+ // [a_new ASC, d_new ASC, b_new ASC]+ vec![+ ("a_new", option_asc),+ ("d_new", option_asc),+ ("b_new", option_asc),+ ],+ // [c_new ASC],+ vec![("c_new", option_asc)],+ ],+ ),+ // ------- TEST CASE 10 ----------+ (+ vec![+ // [a ASC, b ASC, c ASC]+ vec![+ (col_a, option_asc),+ (col_b, option_asc),+ (col_c, option_asc),+ ],+ // [a ASC, d ASC]+ vec![(col_a, option_asc), (col_d, option_asc)],+ ],+ // proj exprs+ vec![+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (col_c, "c_new".to_string()),+ (&c_plus_d, "c+d".to_string()),+ ],+ // expected+ vec![+ // [a_new ASC, b_new ASC, c_new ASC]+ vec![+ ("a_new", option_asc),+ ("b_new", option_asc),+ ("c_new", option_asc),+ ],+ // [a_new ASC, b_new ASC, c+d ASC]+ vec![+ ("a_new", option_asc),+ ("b_new", option_asc),+ ("c+d", option_asc),+ ],+ ],+ ),+ // ------- TEST CASE 11 ----------+ (+ // orderings+ vec![+ // [a ASC, b ASC]+ vec![(col_a, option_asc), (col_b, option_asc)],+ // [a ASC, d ASC]+ vec![(col_a, option_asc), (col_d, option_asc)],+ ],+ // proj exprs+ vec![+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (&b_plus_d, "b+d".to_string()),+ ],+ // expected+ vec![+ // [a_new ASC, b_new ASC]+ vec![("a_new", option_asc), ("b_new", option_asc)],+ // [a_new ASC, b + d ASC]+ vec![("a_new", option_asc), ("b+d", option_asc)],+ ],+ ),+ // ------- TEST CASE 12 ----------+ (+ // orderings+ vec![+ // [a ASC, b ASC, c ASC]+ vec![+ (col_a, option_asc),+ (col_b, option_asc),+ (col_c, option_asc),+ ],+ ],+ // proj exprs+ vec![(col_c, "c_new".to_string()), (col_a, "a_new".to_string())],+ // expected+ vec![+ // [a_new ASC]+ vec![("a_new", option_asc)],+ ],+ ),+ // ------- TEST CASE 13 ----------+ (+ // orderings+ vec![+ // [a ASC, b ASC, c ASC]+ vec![+ (col_a, option_asc),+ (col_b, option_asc),+ (col_c, option_asc),+ ],+ // [a ASC, a + b ASC, c ASC]+ vec![+ (col_a, option_asc),+ (&a_plus_b, option_asc),+ (col_c, option_asc),+ ],+ ],+ // proj exprs+ vec![+ (col_c, "c_new".to_string()),+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (&a_plus_b, "a+b".to_string()),+ ],+ // expected+ vec![+ // [a_new ASC, b_new ASC, c_new ASC]+ vec![+ ("a_new", option_asc),+ ("b_new", option_asc),+ ("c_new", option_asc),+ ],+ // [a_new ASC, a+b ASC, c_new ASC]+ vec![+ ("a_new", option_asc),+ ("a+b", option_asc),+ ("c_new", option_asc),+ ],+ ],+ ),+ // ------- TEST CASE 14 ----------+ (+ // orderings+ vec![+ // [a ASC, b ASC]+ vec![(col_a, option_asc), (col_b, option_asc)],+ // [c ASC, b ASC]+ vec![(col_c, option_asc), (col_b, option_asc)],+ // [d ASC, e ASC]+ vec![(col_d, option_asc), (col_e, option_asc)],+ ],+ // proj exprs+ vec![+ (col_c, "c_new".to_string()),+ (col_d, "d_new".to_string()),+ (col_a, "a_new".to_string()),+ (&b_plus_e, "b+e".to_string()),+ ],+ // expected+ vec![+ // [a_new ASC, d_new ASC, b+e ASC]+ vec![+ ("a_new", option_asc),+ ("d_new", option_asc),+ ("b+e", option_asc),+ ],+ // [d_new ASC, a_new ASC, b+e ASC]+ vec![+ ("d_new", option_asc),+ ("a_new", option_asc),+ ("b+e", option_asc),+ ],+ // [c_new ASC, d_new ASC, b+e ASC]+ vec![+ ("c_new", option_asc),+ ("d_new", option_asc),+ ("b+e", option_asc),+ ],+ // [d_new ASC, c_new ASC, b+e ASC]+ vec![+ ("d_new", option_asc),+ ("c_new", option_asc),+ ("b+e", option_asc),+ ],+ ],+ ),+ // ------- TEST CASE 15 ----------+ (+ // orderings+ vec![+ // [a ASC, c ASC, b ASC]+ vec![+ (col_a, option_asc),+ (col_c, option_asc),+ (&col_b, option_asc),+ ],+ ],+ // proj exprs+ vec![+ (col_c, "c_new".to_string()),+ (col_a, "a_new".to_string()),+ (&a_plus_b, "a+b".to_string()),+ ],+ // expected+ vec![+ // [a_new ASC, d_new ASC, b+e ASC]+ vec![+ ("a_new", option_asc),+ ("c_new", option_asc),+ ("a+b", option_asc),+ ],+ ],+ ),+ // ------- TEST CASE 16 ----------+ (+ // orderings+ vec![+ // [a ASC, b ASC]+ vec![(col_a, option_asc), (col_b, option_asc)],+ // [c ASC, b DESC]+ vec![(col_c, option_asc), (col_b, option_desc)],+ // [e ASC]+ vec![(col_e, option_asc)],+ ],+ // proj exprs+ vec![+ (col_c, "c_new".to_string()),+ (col_a, "a_new".to_string()),+ (col_b, "b_new".to_string()),+ (&b_plus_e, "b+e".to_string()),+ ],+ // expected+ vec![+ // [a_new ASC, b_new ASC]+ vec![("a_new", option_asc), ("b_new", option_asc)],+ // [a_new ASC, b_new ASC]+ vec![("a_new", option_asc), ("b+e", option_asc)],+ // [c_new ASC, b_new DESC]+ vec![("c_new", option_asc), ("b_new", option_desc)],+ ],+ ),+ ];++ for (idx, (orderings, proj_exprs, expected)) in test_cases.into_iter().enumerate()+ {+ let mut eq_properties = EquivalenceProperties::new(schema.clone());++ let orderings = convert_to_orderings(&orderings);+ eq_properties.add_new_orderings(orderings);++ let proj_exprs = proj_exprs+ .into_iter()+ .map(|(expr, name)| (expr.clone(), name))+ .collect::<Vec<_>>();+ let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &schema)?;+ let output_schema = output_schema(&projection_mapping, &schema)?;++ let expected = expected+ .into_iter()+ .map(|ordering| {+ ordering+ .into_iter()+ .map(|(name, options)| {+ (col(name, &output_schema).unwrap(), options)+ })+ .collect::<Vec<_>>()+ })+ .collect::<Vec<_>>();+ let expected = convert_to_orderings_owned(&expected);++ let projected_eq = eq_properties.project(&projection_mapping, output_schema);+ let orderings = projected_eq.oeq_class();++ let err_msg = format!(+ "test_idx: {:?}, actual: {:?}, expected: {:?}, projection_mapping: {:?}",+ idx, orderings.orderings, expected, projection_mapping+ );++ assert_eq!(orderings.len(), expected.len(), "{}", err_msg);+ for expected_ordering in &expected {+ assert!(orderings.contains(expected_ordering), "{}", err_msg)+ }+ }++ Ok(())+ }++ #[test]+ fn project_orderings2() -> Result<()> {+ let schema = Arc::new(Schema::new(vec![+ Field::new("a", DataType::Int32, true),+ Field::new("b", DataType::Int32, true),+ Field::new("c", DataType::Int32, true),+ Field::new("d", DataType::Int32, true),+ Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),+ ]));+ let col_a = &col("a", &schema)?;+ let col_b = &col("b", &schema)?;+ let col_c = &col("c", &schema)?;+ let col_ts = &col("ts", &schema)?;+ let a_plus_b = Arc::new(BinaryExpr::new(+ col_a.clone(),+ Operator::Plus,+ col_b.clone(),+ )) as Arc<dyn PhysicalExpr>;+ let interval = Arc::new(Literal::new(ScalarValue::IntervalDayTime(Some(2))))+ as Arc<dyn PhysicalExpr>;+ let date_bin_ts = &create_physical_expr(+ &BuiltinScalarFunction::DateBin,+ &[interval, col_ts.clone()],+ &schema,+ &ExecutionProps::default(),+ )?;++ let round_c = &create_physical_expr(+ &BuiltinScalarFunction::Round,+ &[col_c.clone()],+ &schema,+ &ExecutionProps::default(),+ )?;++ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };++ let proj_exprs = vec![+ (col_b, "b_new".to_string()),+ (col_a, "a_new".to_string()),+ (col_c, "c_new".to_string()),+ (date_bin_ts, "date_bin_res".to_string()),+ (round_c, "round_c_res".to_string()),+ ];+ let proj_exprs = proj_exprs+ .into_iter()+ .map(|(expr, name)| (expr.clone(), name))+ .collect::<Vec<_>>();+ let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &schema)?;+ let output_schema = output_schema(&projection_mapping, &schema)?;++ let col_a_new = &col("a_new", &output_schema)?;+ let col_b_new = &col("b_new", &output_schema)?;+ let col_c_new = &col("c_new", &output_schema)?;+ let col_date_bin_res = &col("date_bin_res", &output_schema)?;+ let col_round_c_res = &col("round_c_res", &output_schema)?;+ let a_new_plus_b_new = Arc::new(BinaryExpr::new(+ col_a_new.clone(),+ Operator::Plus,+ col_b_new.clone(),+ )) as Arc<dyn PhysicalExpr>;++ let test_cases = vec![+ // ---------- TEST CASE 1 ------------+ (+ // orderings+ vec![+ // [a ASC]+ vec![(col_a, option_asc)],+ ],+ // expected+ vec![+ // [b_new ASC]+ vec![(col_a_new, option_asc)],+ ],+ ),+ // ---------- TEST CASE 2 ------------+ (+ // orderings+ vec![+ // [a+b ASC]+ vec![(&a_plus_b, option_asc)],+ ],+ // expected+ vec![+ // [b_new ASC]+ vec![(&a_new_plus_b_new, option_asc)],+ ],+ ),+ // ---------- TEST CASE 3 ------------+ (+ // orderings+ vec![+ // [a ASC, ts ASC]+ vec![(col_a, option_asc), (col_ts, option_asc)],+ ],+ // expected+ vec![+ // [a_new ASC, date_bin_res ASC]+ vec![(col_a_new, option_asc), (col_date_bin_res, option_asc)],+ ],+ ),+ // ---------- TEST CASE 4 ------------+ (+ // orderings+ vec![+ // [a ASC, ts ASC, b ASC]+ vec![+ (col_a, option_asc),+ (col_ts, option_asc),+ (col_b, option_asc),+ ],+ ],+ // expected+ vec![+ // [a_new ASC, date_bin_res ASC]+ // Please note that result is not [a_new ASC, date_bin_res ASC, b_new ASC]+ // because, datebin_res may not be 1-1 function. Hence without introducing ts+ // dependency we cannot guarantee any ordering after date_bin_res column.+ vec![(col_a_new, option_asc), (col_date_bin_res, option_asc)],+ ],+ ),+ // ---------- TEST CASE 5 ------------+ (+ // orderings+ vec![+ // [a ASC, c ASC]+ vec![(col_a, option_asc), (col_c, option_asc)],+ ],+ // expected+ vec![+ // [a_new ASC, round_c_res ASC, c_new ASC]+ vec![(col_a_new, option_asc), (col_round_c_res, option_asc)],+ // [a_new ASC, c_new ASC]+ vec![(col_a_new, option_asc), (col_c_new, option_asc)],+ ],+ ),+ // ---------- TEST CASE 6 ------------+ (+ // orderings+ vec![+ // [c ASC, b ASC]+ vec![(col_c, option_asc), (col_b, option_asc)],+ ],+ // expected+ vec![+ // [round_c_res ASC]+ vec![(col_round_c_res, option_asc)],+ // [c_new ASC, b_new ASC]+ vec![(col_c_new, option_asc), (col_b_new, option_asc)],+ ],+ ),+ // ---------- TEST CASE 7 ------------+ (+ // orderings+ vec![+ // [a+b ASC, c ASC]+ vec![(&a_plus_b, option_asc), (col_c, option_asc)],+ ],+ // expected+ vec![+ // [a+b ASC, round(c) ASC, c_new ASC]+ vec![+ (&a_new_plus_b_new, option_asc),+ (&col_round_c_res, option_asc),+ ],+ // [a+b ASC, c_new ASC]+ vec![(&a_new_plus_b_new, option_asc), (col_c_new, option_asc)],+ ],+ ),+ ];++ for (idx, (orderings, expected)) in test_cases.iter().enumerate() {+ let mut eq_properties = EquivalenceProperties::new(schema.clone());++ let orderings = convert_to_orderings(orderings);+ eq_properties.add_new_orderings(orderings);++ let expected = convert_to_orderings(expected);++ let projected_eq =+ eq_properties.project(&projection_mapping, output_schema.clone());+ let orderings = projected_eq.oeq_class();++ let err_msg = format!(+ "test idx: {:?}, actual: {:?}, expected: {:?}, projection_mapping: {:?}",+ idx, orderings.orderings, expected, projection_mapping+ );++ assert_eq!(orderings.len(), expected.len(), "{}", err_msg);+ for expected_ordering in &expected {+ assert!(orderings.contains(expected_ordering), "{}", err_msg)+ }+ }+ Ok(())+ }++ #[test]+ fn project_orderings3() -> Result<()> {+ let schema = Arc::new(Schema::new(vec![+ Field::new("a", DataType::Int32, true),+ Field::new("b", DataType::Int32, true),+ Field::new("c", DataType::Int32, true),+ Field::new("d", DataType::Int32, true),+ Field::new("e", DataType::Int32, true),+ Field::new("f", DataType::Int32, true),+ ]));+ let col_a = &col("a", &schema)?;+ let col_b = &col("b", &schema)?;+ let col_c = &col("c", &schema)?;+ let col_d = &col("d", &schema)?;+ let col_e = &col("e", &schema)?;+ let col_f = &col("f", &schema)?;+ let a_plus_b = Arc::new(BinaryExpr::new(+ col_a.clone(),+ Operator::Plus,+ col_b.clone(),+ )) as Arc<dyn PhysicalExpr>;++ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };++ let proj_exprs = vec![+ (col_c, "c_new".to_string()),+ (col_d, "d_new".to_string()),+ (&a_plus_b, "a+b".to_string()),+ ];+ let proj_exprs = proj_exprs+ .into_iter()+ .map(|(expr, name)| (expr.clone(), name))+ .collect::<Vec<_>>();+ let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &schema)?;+ let output_schema = output_schema(&projection_mapping, &schema)?;++ let col_a_plus_b_new = &col("a+b", &output_schema)?;+ let col_c_new = &col("c_new", &output_schema)?;+ let col_d_new = &col("d_new", &output_schema)?;++ let test_cases = vec![+ // ---------- TEST CASE 1 ------------+ (+ // orderings+ vec![+ // [d ASC, b ASC]+ vec![(col_d, option_asc), (col_b, option_asc)],+ // [c ASC, a ASC]+ vec![(col_c, option_asc), (col_a, option_asc)],+ ],+ // equal conditions+ vec![],+ // expected+ vec![+ // [d_new ASC, c_new ASC, a+b ASC]+ vec![+ (col_d_new, option_asc),+ (col_c_new, option_asc),+ (col_a_plus_b_new, option_asc),+ ],+ // [c_new ASC, d_new ASC, a+b ASC]+ vec![+ (col_c_new, option_asc),+ (col_d_new, option_asc),+ (col_a_plus_b_new, option_asc),+ ],+ ],+ ),+ // ---------- TEST CASE 2 ------------+ (+ // orderings+ vec![+ // [d ASC, b ASC]+ vec![(col_d, option_asc), (col_b, option_asc)],+ // [c ASC, e ASC], Please note that a=e+ vec![(col_c, option_asc), (col_e, option_asc)],+ ],+ // equal conditions+ vec![(col_e, col_a)],+ // expected+ vec![+ // [d_new ASC, c_new ASC, a+b ASC]+ vec![+ (col_d_new, option_asc),+ (col_c_new, option_asc),+ (col_a_plus_b_new, option_asc),+ ],+ // [c_new ASC, d_new ASC, a+b ASC]+ vec![+ (col_c_new, option_asc),+ (col_d_new, option_asc),+ (col_a_plus_b_new, option_asc),+ ],+ ],+ ),+ // ---------- TEST CASE 3 ------------+ (+ // orderings+ vec![+ // [d ASC, b ASC]+ vec![(col_d, option_asc), (col_b, option_asc)],+ // [c ASC, e ASC], Please note that a=f+ vec![(col_c, option_asc), (col_e, option_asc)],+ ],+ // equal conditions+ vec![(col_a, col_f)],+ // expected+ vec![+ // [d_new ASC]+ vec![(col_d_new, option_asc)],+ // [c_new ASC]+ vec![(col_c_new, option_asc)],+ ],+ ),+ ];+ for (orderings, equal_columns, expected) in test_cases {+ let mut eq_properties = EquivalenceProperties::new(schema.clone());+ for (lhs, rhs) in equal_columns {+ eq_properties.add_equal_conditions(lhs, rhs);+ }++ let orderings = convert_to_orderings(&orderings);+ eq_properties.add_new_orderings(orderings);++ let expected = convert_to_orderings(&expected);++ let projected_eq =+ eq_properties.project(&projection_mapping, output_schema.clone());+ let orderings = projected_eq.oeq_class();++ let err_msg = format!(+ "actual: {:?}, expected: {:?}, projection_mapping: {:?}",+ orderings.orderings, expected, projection_mapping+ );++ assert_eq!(orderings.len(), expected.len(), "{}", err_msg);+ for expected_ordering in &expected {+ assert!(orderings.contains(expected_ordering), "{}", err_msg)+ }+ }++ Ok(())+ }++ #[test]+ fn project_orderings_random() -> Result<()> {+ const N_RANDOM_SCHEMA: usize = 20;+ const N_ELEMENTS: usize = 125;+ const N_DISTINCT: usize = 5;++ for seed in 0..N_RANDOM_SCHEMA {+ // Create a random schema with random properties+ let (test_schema, eq_properties) = create_random_schema(seed as u64)?;+ // Generate a data that satisfies properties given+ let table_data_with_properties =+ generate_table_for_eq_properties(&eq_properties, N_ELEMENTS, N_DISTINCT)?;+ // Floor(a)+ let floor_a = create_physical_expr(+ &BuiltinScalarFunction::Floor,+ &[col("a", &test_schema)?],+ &test_schema,+ &ExecutionProps::default(),+ )?;+ // a + b+ let a_plus_b = Arc::new(BinaryExpr::new(+ col("a", &test_schema)?,+ Operator::Plus,+ col("b", &test_schema)?,+ )) as Arc<dyn PhysicalExpr>;+ let proj_exprs = vec![+ (col("a", &test_schema)?, "a_new"),+ (col("b", &test_schema)?, "b_new"),+ (col("c", &test_schema)?, "c_new"),+ (col("d", &test_schema)?, "d_new"),+ (col("e", &test_schema)?, "e_new"),+ (col("f", &test_schema)?, "f_new"),+ (floor_a, "floor(a)"),+ (a_plus_b, "a+b"),+ ];++ for n_req in 0..=proj_exprs.len() {+ for proj_exprs in proj_exprs.iter().combinations(n_req) {+ let proj_exprs = proj_exprs+ .into_iter()+ .map(|(expr, name)| (expr.clone(), name.to_string()))+ .collect::<Vec<_>>();+ let (projected_batch, projected_eq) = apply_projection(+ proj_exprs.clone(),+ &table_data_with_properties,+ &eq_properties,+ )?;++ // Make sure each ordering after projection is valid.+ for ordering in projected_eq.oeq_class().iter() {+ let err_msg = format!(+ "Error in test case ordering:{:?}, eq_properties.oeq_class: {:?}, eq_properties.eq_group: {:?}, eq_properties.constants: {:?}, proj_exprs: {:?}",+ ordering, eq_properties.oeq_class, eq_properties.eq_group, eq_properties.constants, proj_exprs+ );+ // Since ordered section satisfies schema, we expect+ // that result will be same after sort (e.g sort was unnecessary).+ assert!(+ is_table_same_after_sort(+ ordering.clone(),+ projected_batch.clone(),+ )?,+ "{}",+ err_msg+ );+ }+ }+ }+ }++ Ok(())+ }++ #[test]+ fn ordering_satisfy_after_projection_random() -> Result<()> {+ const N_RANDOM_SCHEMA: usize = 20;+ const N_ELEMENTS: usize = 125;+ const N_DISTINCT: usize = 5;+ const SORT_OPTIONS: SortOptions = SortOptions {+ descending: false,+ nulls_first: false,+ };++ for seed in 0..N_RANDOM_SCHEMA {+ // Create a random schema with random properties+ let (test_schema, eq_properties) = create_random_schema(seed as u64)?;+ // Generate a data that satisfies properties given+ let table_data_with_properties =+ generate_table_for_eq_properties(&eq_properties, N_ELEMENTS, N_DISTINCT)?;+ // Floor(a)+ let floor_a = create_physical_expr(+ &BuiltinScalarFunction::Floor,+ &[col("a", &test_schema)?],+ &test_schema,+ &ExecutionProps::default(),+ )?;+ // a + b+ let a_plus_b = Arc::new(BinaryExpr::new(+ col("a", &test_schema)?,+ Operator::Plus,+ col("b", &test_schema)?,+ )) as Arc<dyn PhysicalExpr>;+ let proj_exprs = vec![+ (col("a", &test_schema)?, "a_new"),+ (col("b", &test_schema)?, "b_new"),+ (col("c", &test_schema)?, "c_new"),+ (col("d", &test_schema)?, "d_new"),+ (col("e", &test_schema)?, "e_new"),+ (col("f", &test_schema)?, "f_new"),+ (floor_a, "floor(a)"),+ (a_plus_b, "a+b"),+ ];++ for n_req in 0..=proj_exprs.len() {+ for proj_exprs in proj_exprs.iter().combinations(n_req) {+ let proj_exprs = proj_exprs+ .into_iter()+ .map(|(expr, name)| (expr.clone(), name.to_string()))+ .collect::<Vec<_>>();+ let (projected_batch, projected_eq) = apply_projection(+ proj_exprs.clone(),+ &table_data_with_properties,+ &eq_properties,+ )?;++ let projection_mapping =+ ProjectionMapping::try_new(&proj_exprs, &test_schema)?;++ let projected_exprs = projection_mapping+ .iter()+ .map(|(_source, target)| target.clone())+ .collect::<Vec<_>>();++ for n_req in 0..=projected_exprs.len() {+ for exprs in projected_exprs.iter().combinations(n_req) {+ let requirement = exprs+ .into_iter()+ .map(|expr| PhysicalSortExpr {+ expr: expr.clone(),+ options: SORT_OPTIONS,+ })+ .collect::<Vec<_>>();+ let expected = is_table_same_after_sort(+ requirement.clone(),+ projected_batch.clone(),+ )?;+ let err_msg = format!(+ "Error in test case requirement:{:?}, expected: {:?}, eq_properties.oeq_class: {:?}, eq_properties.eq_group: {:?}, eq_properties.constants: {:?}, projected_eq.oeq_class: {:?}, projected_eq.eq_group: {:?}, projected_eq.constants: {:?}, projection_mapping: {:?}",+ requirement, expected, eq_properties.oeq_class, eq_properties.eq_group, eq_properties.constants, projected_eq.oeq_class, projected_eq.eq_group, projected_eq.constants, projection_mapping+ );+ // Check whether ordering_satisfy API result and+ // experimental result matches.+ assert_eq!(+ projected_eq.ordering_satisfy(&requirement),+ expected,+ "{}",+ err_msg+ );+ }+ }+ }+ }+ }++ Ok(())+ }+}diff --git a/datafusion/physical-expr/src/equivalence/properties.rs b/datafusion/physical-expr/src/equivalence/properties.rsnew file mode 100644index 0000000000..31c1cf6119--- /dev/null+++ b/datafusion/physical-expr/src/equivalence/properties.rs@@ -0,0 +1,2062 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++use crate::expressions::Column;+use arrow_schema::SchemaRef;+use datafusion_common::{JoinSide, JoinType};+use indexmap::IndexSet;+use itertools::Itertools;+use std::collections::{HashMap, HashSet};+use std::hash::{Hash, Hasher};+use std::sync::Arc;++use crate::equivalence::{+ collapse_lex_req, EquivalenceGroup, OrderingEquivalenceClass, ProjectionMapping,+};++use crate::expressions::Literal;+use crate::sort_properties::{ExprOrdering, SortProperties};+use crate::{+ physical_exprs_contains, LexOrdering, LexOrderingRef, LexRequirement,+ LexRequirementRef, PhysicalExpr, PhysicalSortExpr, PhysicalSortRequirement,+};+use datafusion_common::tree_node::{Transformed, TreeNode};++use super::ordering::collapse_lex_ordering;++/// A `EquivalenceProperties` object stores useful information related to a schema.+/// Currently, it keeps track of:+/// - Equivalent expressions, e.g expressions that have same value.+/// - Valid sort expressions (orderings) for the schema.+/// - Constants expressions (e.g expressions that are known to have constant values).+///+/// Consider table below:+///+/// ```text+/// ┌-------┐+/// | a | b |+/// |---|---|+/// | 1 | 9 |+/// | 2 | 8 |+/// | 3 | 7 |+/// | 5 | 5 |+/// └---┴---┘+/// ```+///+/// where both `a ASC` and `b DESC` can describe the table ordering. With+/// `EquivalenceProperties`, we can keep track of these different valid sort+/// expressions and treat `a ASC` and `b DESC` on an equal footing.+///+/// Similarly, consider the table below:+///+/// ```text+/// ┌-------┐+/// | a | b |+/// |---|---|+/// | 1 | 1 |+/// | 2 | 2 |+/// | 3 | 3 |+/// | 5 | 5 |+/// └---┴---┘+/// ```+///+/// where columns `a` and `b` always have the same value. We keep track of such+/// equivalences inside this object. With this information, we can optimize+/// things like partitioning. For example, if the partition requirement is+/// `Hash(a)` and output partitioning is `Hash(b)`, then we can deduce that+/// the existing partitioning satisfies the requirement.+#[derive(Debug, Clone)]+pub struct EquivalenceProperties {+ /// Collection of equivalence classes that store expressions with the same+ /// value.+ pub eq_group: EquivalenceGroup,+ /// Equivalent sort expressions for this table.+ pub oeq_class: OrderingEquivalenceClass,+ /// Expressions whose values are constant throughout the table.+ /// TODO: We do not need to track constants separately, they can be tracked+ /// inside `eq_groups` as `Literal` expressions.+ pub constants: Vec<Arc<dyn PhysicalExpr>>,+ /// Schema associated with this object.+ schema: SchemaRef,+}++impl EquivalenceProperties {+ /// Creates an empty `EquivalenceProperties` object.+ pub fn new(schema: SchemaRef) -> Self {+ Self {+ eq_group: EquivalenceGroup::empty(),+ oeq_class: OrderingEquivalenceClass::empty(),+ constants: vec![],+ schema,+ }+ }++ /// Creates a new `EquivalenceProperties` object with the given orderings.+ pub fn new_with_orderings(schema: SchemaRef, orderings: &[LexOrdering]) -> Self {+ Self {+ eq_group: EquivalenceGroup::empty(),+ oeq_class: OrderingEquivalenceClass::new(orderings.to_vec()),+ constants: vec![],+ schema,+ }+ }++ /// Returns the associated schema.+ pub fn schema(&self) -> &SchemaRef {+ &self.schema+ }++ /// Returns a reference to the ordering equivalence class within.+ pub fn oeq_class(&self) -> &OrderingEquivalenceClass {+ &self.oeq_class+ }++ /// Returns a reference to the equivalence group within.+ pub fn eq_group(&self) -> &EquivalenceGroup {+ &self.eq_group+ }++ /// Returns a reference to the constant expressions+ pub fn constants(&self) -> &[Arc<dyn PhysicalExpr>] {+ &self.constants+ }++ /// Returns the normalized version of the ordering equivalence class within.+ /// Normalization removes constants and duplicates as well as standardizing+ /// expressions according to the equivalence group within.+ pub fn normalized_oeq_class(&self) -> OrderingEquivalenceClass {+ OrderingEquivalenceClass::new(+ self.oeq_class+ .iter()+ .map(|ordering| self.normalize_sort_exprs(ordering))+ .collect(),+ )+ }++ /// Extends this `EquivalenceProperties` with the `other` object.+ pub fn extend(mut self, other: Self) -> Self {+ self.eq_group.extend(other.eq_group);+ self.oeq_class.extend(other.oeq_class);+ self.add_constants(other.constants)+ }++ /// Clears (empties) the ordering equivalence class within this object.+ /// Call this method when existing orderings are invalidated.+ pub fn clear_orderings(&mut self) {+ self.oeq_class.clear();+ }++ /// Extends this `EquivalenceProperties` by adding the orderings inside the+ /// ordering equivalence class `other`.+ pub fn add_ordering_equivalence_class(&mut self, other: OrderingEquivalenceClass) {+ self.oeq_class.extend(other);+ }++ /// Adds new orderings into the existing ordering equivalence class.+ pub fn add_new_orderings(+ &mut self,+ orderings: impl IntoIterator<Item = LexOrdering>,+ ) {+ self.oeq_class.add_new_orderings(orderings);+ }++ /// Incorporates the given equivalence group to into the existing+ /// equivalence group within.+ pub fn add_equivalence_group(&mut self, other_eq_group: EquivalenceGroup) {+ self.eq_group.extend(other_eq_group);+ }++ /// Adds a new equality condition into the existing equivalence group.+ /// If the given equality defines a new equivalence class, adds this new+ /// equivalence class to the equivalence group.+ pub fn add_equal_conditions(+ &mut self,+ left: &Arc<dyn PhysicalExpr>,+ right: &Arc<dyn PhysicalExpr>,+ ) {+ self.eq_group.add_equal_conditions(left, right);+ }++ /// Track/register physical expressions with constant values.+ pub fn add_constants(+ mut self,+ constants: impl IntoIterator<Item = Arc<dyn PhysicalExpr>>,+ ) -> Self {+ for expr in self.eq_group.normalize_exprs(constants) {+ if !physical_exprs_contains(&self.constants, &expr) {+ self.constants.push(expr);+ }+ }+ self+ }++ /// Updates the ordering equivalence group within assuming that the table+ /// is re-sorted according to the argument `sort_exprs`. Note that constants+ /// and equivalence classes are unchanged as they are unaffected by a re-sort.+ pub fn with_reorder(mut self, sort_exprs: Vec<PhysicalSortExpr>) -> Self {+ // TODO: In some cases, existing ordering equivalences may still be valid add this analysis.+ self.oeq_class = OrderingEquivalenceClass::new(vec![sort_exprs]);+ self+ }++ /// Normalizes the given sort expressions (i.e. `sort_exprs`) using the+ /// equivalence group and the ordering equivalence class within.+ ///+ /// Assume that `self.eq_group` states column `a` and `b` are aliases.+ /// Also assume that `self.oeq_class` states orderings `d ASC` and `a ASC, c ASC`+ /// are equivalent (in the sense that both describe the ordering of the table).+ /// If the `sort_exprs` argument were `vec![b ASC, c ASC, a ASC]`, then this+ /// function would return `vec![a ASC, c ASC]`. Internally, it would first+ /// normalize to `vec![a ASC, c ASC, a ASC]` and end up with the final result+ /// after deduplication.+ fn normalize_sort_exprs(&self, sort_exprs: LexOrderingRef) -> LexOrdering {+ // Convert sort expressions to sort requirements:+ let sort_reqs = PhysicalSortRequirement::from_sort_exprs(sort_exprs.iter());+ // Normalize the requirements:+ let normalized_sort_reqs = self.normalize_sort_requirements(&sort_reqs);+ // Convert sort requirements back to sort expressions:+ PhysicalSortRequirement::to_sort_exprs(normalized_sort_reqs)+ }++ /// Normalizes the given sort requirements (i.e. `sort_reqs`) using the+ /// equivalence group and the ordering equivalence class within. It works by:+ /// - Removing expressions that have a constant value from the given requirement.+ /// - Replacing sections that belong to some equivalence class in the equivalence+ /// group with the first entry in the matching equivalence class.+ ///+ /// Assume that `self.eq_group` states column `a` and `b` are aliases.+ /// Also assume that `self.oeq_class` states orderings `d ASC` and `a ASC, c ASC`+ /// are equivalent (in the sense that both describe the ordering of the table).+ /// If the `sort_reqs` argument were `vec![b ASC, c ASC, a ASC]`, then this+ /// function would return `vec![a ASC, c ASC]`. Internally, it would first+ /// normalize to `vec![a ASC, c ASC, a ASC]` and end up with the final result+ /// after deduplication.+ fn normalize_sort_requirements(+ &self,+ sort_reqs: LexRequirementRef,+ ) -> LexRequirement {+ let normalized_sort_reqs = self.eq_group.normalize_sort_requirements(sort_reqs);+ let constants_normalized = self.eq_group.normalize_exprs(self.constants.clone());+ // Prune redundant sections in the requirement:+ collapse_lex_req(+ normalized_sort_reqs+ .iter()+ .filter(|&order| {+ !physical_exprs_contains(&constants_normalized, &order.expr)+ })+ .cloned()+ .collect(),+ )+ }++ /// Checks whether the given ordering is satisfied by any of the existing+ /// orderings.+ pub fn ordering_satisfy(&self, given: LexOrderingRef) -> bool {+ // Convert the given sort expressions to sort requirements:+ let sort_requirements = PhysicalSortRequirement::from_sort_exprs(given.iter());+ self.ordering_satisfy_requirement(&sort_requirements)+ }++ /// Checks whether the given sort requirements are satisfied by any of the+ /// existing orderings.+ pub fn ordering_satisfy_requirement(&self, reqs: LexRequirementRef) -> bool {+ let mut eq_properties = self.clone();+ // First, standardize the given requirement:+ let normalized_reqs = eq_properties.normalize_sort_requirements(reqs);+ for normalized_req in normalized_reqs {+ // Check whether given ordering is satisfied+ if !eq_properties.ordering_satisfy_single(&normalized_req) {+ return false;+ }+ // Treat satisfied keys as constants in subsequent iterations. We+ // can do this because the "next" key only matters in a lexicographical+ // ordering when the keys to its left have the same values.+ //+ // Note that these expressions are not properly "constants". This is just+ // an implementation strategy confined to this function.+ //+ // For example, assume that the requirement is `[a ASC, (b + c) ASC]`,+ // and existing equivalent orderings are `[a ASC, b ASC]` and `[c ASC]`.+ // From the analysis above, we know that `[a ASC]` is satisfied. Then,+ // we add column `a` as constant to the algorithm state. This enables us+ // to deduce that `(b + c) ASC` is satisfied, given `a` is constant.+ eq_properties =+ eq_properties.add_constants(std::iter::once(normalized_req.expr));+ }+ true+ }++ /// Determines whether the ordering specified by the given sort requirement+ /// is satisfied based on the orderings within, equivalence classes, and+ /// constant expressions.+ ///+ /// # Arguments+ ///+ /// - `req`: A reference to a `PhysicalSortRequirement` for which the ordering+ /// satisfaction check will be done.+ ///+ /// # Returns+ ///+ /// Returns `true` if the specified ordering is satisfied, `false` otherwise.+ fn ordering_satisfy_single(&self, req: &PhysicalSortRequirement) -> bool {+ let expr_ordering = self.get_expr_ordering(req.expr.clone());+ let ExprOrdering { expr, state, .. } = expr_ordering;+ match state {+ SortProperties::Ordered(options) => {+ let sort_expr = PhysicalSortExpr { expr, options };+ sort_expr.satisfy(req, self.schema())+ }+ // Singleton expressions satisfies any ordering.+ SortProperties::Singleton => true,+ SortProperties::Unordered => false,+ }+ }++ /// Checks whether the `given`` sort requirements are equal or more specific+ /// than the `reference` sort requirements.+ pub fn requirements_compatible(+ &self,+ given: LexRequirementRef,+ reference: LexRequirementRef,+ ) -> bool {+ let normalized_given = self.normalize_sort_requirements(given);+ let normalized_reference = self.normalize_sort_requirements(reference);++ (normalized_reference.len() <= normalized_given.len())+ && normalized_reference+ .into_iter()+ .zip(normalized_given)+ .all(|(reference, given)| given.compatible(&reference))+ }++ /// Returns the finer ordering among the orderings `lhs` and `rhs`, breaking+ /// any ties by choosing `lhs`.+ ///+ /// The finer ordering is the ordering that satisfies both of the orderings.+ /// If the orderings are incomparable, returns `None`.+ ///+ /// For example, the finer ordering among `[a ASC]` and `[a ASC, b ASC]` is+ /// the latter.+ pub fn get_finer_ordering(+ &self,+ lhs: LexOrderingRef,+ rhs: LexOrderingRef,+ ) -> Option<LexOrdering> {+ // Convert the given sort expressions to sort requirements:+ let lhs = PhysicalSortRequirement::from_sort_exprs(lhs);+ let rhs = PhysicalSortRequirement::from_sort_exprs(rhs);+ let finer = self.get_finer_requirement(&lhs, &rhs);+ // Convert the chosen sort requirements back to sort expressions:+ finer.map(PhysicalSortRequirement::to_sort_exprs)+ }++ /// Returns the finer ordering among the requirements `lhs` and `rhs`,+ /// breaking any ties by choosing `lhs`.+ ///+ /// The finer requirements are the ones that satisfy both of the given+ /// requirements. If the requirements are incomparable, returns `None`.+ ///+ /// For example, the finer requirements among `[a ASC]` and `[a ASC, b ASC]`+ /// is the latter.+ pub fn get_finer_requirement(+ &self,+ req1: LexRequirementRef,+ req2: LexRequirementRef,+ ) -> Option<LexRequirement> {+ let mut lhs = self.normalize_sort_requirements(req1);+ let mut rhs = self.normalize_sort_requirements(req2);+ lhs.iter_mut()+ .zip(rhs.iter_mut())+ .all(|(lhs, rhs)| {+ lhs.expr.eq(&rhs.expr)+ && match (lhs.options, rhs.options) {+ (Some(lhs_opt), Some(rhs_opt)) => lhs_opt == rhs_opt,+ (Some(options), None) => {+ rhs.options = Some(options);+ true+ }+ (None, Some(options)) => {+ lhs.options = Some(options);+ true+ }+ (None, None) => true,+ }+ })+ .then_some(if lhs.len() >= rhs.len() { lhs } else { rhs })+ }++ /// Calculates the "meet" of the given orderings (`lhs` and `rhs`).+ /// The meet of a set of orderings is the finest ordering that is satisfied+ /// by all the orderings in that set. For details, see:+ ///+ /// <https://en.wikipedia.org/wiki/Join_and_meet>+ ///+ /// If there is no ordering that satisfies both `lhs` and `rhs`, returns+ /// `None`. As an example, the meet of orderings `[a ASC]` and `[a ASC, b ASC]`+ /// is `[a ASC]`.+ pub fn get_meet_ordering(+ &self,+ lhs: LexOrderingRef,+ rhs: LexOrderingRef,+ ) -> Option<LexOrdering> {+ let lhs = self.normalize_sort_exprs(lhs);+ let rhs = self.normalize_sort_exprs(rhs);+ let mut meet = vec![];+ for (lhs, rhs) in lhs.into_iter().zip(rhs.into_iter()) {+ if lhs.eq(&rhs) {+ meet.push(lhs);+ } else {+ break;+ }+ }+ (!meet.is_empty()).then_some(meet)+ }++ /// Projects argument `expr` according to `projection_mapping`, taking+ /// equivalences into account.+ ///+ /// For example, assume that columns `a` and `c` are always equal, and that+ /// `projection_mapping` encodes following mapping:+ ///+ /// ```text+ /// a -> a1+ /// b -> b1+ /// ```+ ///+ /// Then, this function projects `a + b` to `Some(a1 + b1)`, `c + b` to+ /// `Some(a1 + b1)` and `d` to `None`, meaning that it cannot be projected.+ pub fn project_expr(+ &self,+ expr: &Arc<dyn PhysicalExpr>,+ projection_mapping: &ProjectionMapping,+ ) -> Option<Arc<dyn PhysicalExpr>> {+ self.eq_group.project_expr(projection_mapping, expr)+ }++ /// Constructs a dependency map based on existing orderings referred to in+ /// the projection.+ ///+ /// This function analyzes the orderings in the normalized order-equivalence+ /// class and builds a dependency map. The dependency map captures relationships+ /// between expressions within the orderings, helping to identify dependencies+ /// and construct valid projected orderings during projection operations.+ ///+ /// # Parameters+ ///+ /// - `mapping`: A reference to the `ProjectionMapping` that defines the+ /// relationship between source and target expressions.+ ///+ /// # Returns+ ///+ /// A [`DependencyMap`] representing the dependency map, where each+ /// [`DependencyNode`] contains dependencies for the key [`PhysicalSortExpr`].+ ///+ /// # Example+ ///+ /// Assume we have two equivalent orderings: `[a ASC, b ASC]` and `[a ASC, c ASC]`,+ /// and the projection mapping is `[a -> a_new, b -> b_new, b + c -> b + c]`.+ /// Then, the dependency map will be:+ ///+ /// ```text+ /// a ASC: Node {Some(a_new ASC), HashSet{}}+ /// b ASC: Node {Some(b_new ASC), HashSet{a ASC}}+ /// c ASC: Node {None, HashSet{a ASC}}+ /// ```+ fn construct_dependency_map(&self, mapping: &ProjectionMapping) -> DependencyMap {+ let mut dependency_map = HashMap::new();+ for ordering in self.normalized_oeq_class().iter() {+ for (idx, sort_expr) in ordering.iter().enumerate() {+ let target_sort_expr =+ self.project_expr(&sort_expr.expr, mapping).map(|expr| {+ PhysicalSortExpr {+ expr,+ options: sort_expr.options,+ }+ });+ let is_projected = target_sort_expr.is_some();+ if is_projected+ || mapping+ .iter()+ .any(|(source, _)| expr_refers(source, &sort_expr.expr))+ {+ // Previous ordering is a dependency. Note that there is no,+ // dependency for a leading ordering (i.e. the first sort+ // expression).+ let dependency = idx.checked_sub(1).map(|a| &ordering[a]);+ // Add sort expressions that can be projected or referred to+ // by any of the projection expressions to the dependency map:+ dependency_map+ .entry(sort_expr.clone())+ .or_insert_with(|| DependencyNode {+ target_sort_expr: target_sort_expr.clone(),+ dependencies: HashSet::new(),+ })+ .insert_dependency(dependency);+ }+ if !is_projected {+ // If we can not project, stop constructing the dependency+ // map as remaining dependencies will be invalid after projection.+ break;+ }+ }+ }+ dependency_map+ }++ /// Returns a new `ProjectionMapping` where source expressions are normalized.+ ///+ /// This normalization ensures that source expressions are transformed into a+ /// consistent representation. This is beneficial for algorithms that rely on+ /// exact equalities, as it allows for more precise and reliable comparisons.+ ///+ /// # Parameters+ ///+ /// - `mapping`: A reference to the original `ProjectionMapping` to be normalized.+ ///+ /// # Returns+ ///+ /// A new `ProjectionMapping` with normalized source expressions.+ fn normalized_mapping(&self, mapping: &ProjectionMapping) -> ProjectionMapping {+ // Construct the mapping where source expressions are normalized. In this way+ // In the algorithms below we can work on exact equalities+ ProjectionMapping {+ map: mapping+ .iter()+ .map(|(source, target)| {+ let normalized_source = self.eq_group.normalize_expr(source.clone());+ (normalized_source, target.clone())+ })+ .collect(),+ }+ }++ /// Computes projected orderings based on a given projection mapping.+ ///+ /// This function takes a `ProjectionMapping` and computes the possible+ /// orderings for the projected expressions. It considers dependencies+ /// between expressions and generates valid orderings according to the+ /// specified sort properties.+ ///+ /// # Parameters+ ///+ /// - `mapping`: A reference to the `ProjectionMapping` that defines the+ /// relationship between source and target expressions.+ ///+ /// # Returns+ ///+ /// A vector of `LexOrdering` containing all valid orderings after projection.+ fn projected_orderings(&self, mapping: &ProjectionMapping) -> Vec<LexOrdering> {+ let mapping = self.normalized_mapping(mapping);++ // Get dependency map for existing orderings:+ let dependency_map = self.construct_dependency_map(&mapping);++ let orderings = mapping.iter().flat_map(|(source, target)| {+ referred_dependencies(&dependency_map, source)+ .into_iter()+ .filter_map(|relevant_deps| {+ if let SortProperties::Ordered(options) =+ get_expr_ordering(source, &relevant_deps)+ {+ Some((options, relevant_deps))+ } else {+ // Do not consider unordered cases+ None+ }+ })+ .flat_map(|(options, relevant_deps)| {+ let sort_expr = PhysicalSortExpr {+ expr: target.clone(),+ options,+ };+ // Generate dependent orderings (i.e. prefixes for `sort_expr`):+ let mut dependency_orderings =+ generate_dependency_orderings(&relevant_deps, &dependency_map);+ // Append `sort_expr` to the dependent orderings:+ for ordering in dependency_orderings.iter_mut() {+ ordering.push(sort_expr.clone());+ }+ dependency_orderings+ })+ });++ // Add valid projected orderings. For example, if existing ordering is+ // `a + b` and projection is `[a -> a_new, b -> b_new]`, we need to+ // preserve `a_new + b_new` as ordered. Please note that `a_new` and+ // `b_new` themselves need not be ordered. Such dependencies cannot be+ // deduced via the pass above.+ let projected_orderings = dependency_map.iter().flat_map(|(sort_expr, node)| {+ let mut prefixes = construct_prefix_orderings(sort_expr, &dependency_map);+ if prefixes.is_empty() {+ // If prefix is empty, there is no dependency. Insert+ // empty ordering:+ prefixes = vec![vec![]];+ }+ // Append current ordering on top its dependencies:+ for ordering in prefixes.iter_mut() {+ if let Some(target) = &node.target_sort_expr {+ ordering.push(target.clone())+ }+ }+ prefixes+ });++ // Simplify each ordering by removing redundant sections:+ orderings+ .chain(projected_orderings)+ .map(collapse_lex_ordering)+ .collect()+ }++ /// Projects constants based on the provided `ProjectionMapping`.+ ///+ /// This function takes a `ProjectionMapping` and identifies/projects+ /// constants based on the existing constants and the mapping. It ensures+ /// that constants are appropriately propagated through the projection.+ ///+ /// # Arguments+ ///+ /// - `mapping`: A reference to a `ProjectionMapping` representing the+ /// mapping of source expressions to target expressions in the projection.+ ///+ /// # Returns+ ///+ /// Returns a `Vec<Arc<dyn PhysicalExpr>>` containing the projected constants.+ fn projected_constants(+ &self,+ mapping: &ProjectionMapping,+ ) -> Vec<Arc<dyn PhysicalExpr>> {+ // First, project existing constants. For example, assume that `a + b`+ // is known to be constant. If the projection were `a as a_new`, `b as b_new`,+ // then we would project constant `a + b` as `a_new + b_new`.+ let mut projected_constants = self+ .constants+ .iter()+ .flat_map(|expr| self.eq_group.project_expr(mapping, expr))+ .collect::<Vec<_>>();+ // Add projection expressions that are known to be constant:+ for (source, target) in mapping.iter() {+ if self.is_expr_constant(source)+ && !physical_exprs_contains(&projected_constants, target)+ {+ projected_constants.push(target.clone());+ }+ }+ projected_constants+ }++ /// Projects the equivalences within according to `projection_mapping`+ /// and `output_schema`.+ pub fn project(+ &self,+ projection_mapping: &ProjectionMapping,+ output_schema: SchemaRef,+ ) -> Self {+ let projected_constants = self.projected_constants(projection_mapping);+ let projected_eq_group = self.eq_group.project(projection_mapping);+ let projected_orderings = self.projected_orderings(projection_mapping);+ Self {+ eq_group: projected_eq_group,+ oeq_class: OrderingEquivalenceClass::new(projected_orderings),+ constants: projected_constants,+ schema: output_schema,+ }+ }++ /// Returns the longest (potentially partial) permutation satisfying the+ /// existing ordering. For example, if we have the equivalent orderings+ /// `[a ASC, b ASC]` and `[c DESC]`, with `exprs` containing `[c, b, a, d]`,+ /// then this function returns `([a ASC, b ASC, c DESC], [2, 1, 0])`.+ /// This means that the specification `[a ASC, b ASC, c DESC]` is satisfied+ /// by the existing ordering, and `[a, b, c]` resides at indices: `2, 1, 0`+ /// inside the argument `exprs` (respectively). For the mathematical+ /// definition of "partial permutation", see:+ ///+ /// <https://en.wikipedia.org/wiki/Permutation#k-permutations_of_n>+ pub fn find_longest_permutation(+ &self,+ exprs: &[Arc<dyn PhysicalExpr>],+ ) -> (LexOrdering, Vec<usize>) {+ let mut eq_properties = self.clone();+ let mut result = vec![];+ // The algorithm is as follows:+ // - Iterate over all the expressions and insert ordered expressions+ // into the result.+ // - Treat inserted expressions as constants (i.e. add them as constants+ // to the state).+ // - Continue the above procedure until no expression is inserted; i.e.+ // the algorithm reaches a fixed point.+ // This algorithm should reach a fixed point in at most `exprs.len()`+ // iterations.+ let mut search_indices = (0..exprs.len()).collect::<IndexSet<_>>();+ for _idx in 0..exprs.len() {+ // Get ordered expressions with their indices.+ let ordered_exprs = search_indices+ .iter()+ .flat_map(|&idx| {+ let ExprOrdering { expr, state, .. } =+ eq_properties.get_expr_ordering(exprs[idx].clone());+ if let SortProperties::Ordered(options) = state {+ Some((PhysicalSortExpr { expr, options }, idx))+ } else {+ None+ }+ })+ .collect::<Vec<_>>();+ // We reached a fixed point, exit.+ if ordered_exprs.is_empty() {+ break;+ }+ // Remove indices that have an ordering from `search_indices`, and+ // treat ordered expressions as constants in subsequent iterations.+ // We can do this because the "next" key only matters in a lexicographical+ // ordering when the keys to its left have the same values.+ //+ // Note that these expressions are not properly "constants". This is just+ // an implementation strategy confined to this function.+ for (PhysicalSortExpr { expr, .. }, idx) in &ordered_exprs {+ eq_properties =+ eq_properties.add_constants(std::iter::once(expr.clone()));+ search_indices.remove(idx);+ }+ // Add new ordered section to the state.+ result.extend(ordered_exprs);+ }+ result.into_iter().unzip()+ }++ /// This function determines whether the provided expression is constant+ /// based on the known constants.+ ///+ /// # Arguments+ ///+ /// - `expr`: A reference to a `Arc<dyn PhysicalExpr>` representing the+ /// expression to be checked.+ ///+ /// # Returns+ ///+ /// Returns `true` if the expression is constant according to equivalence+ /// group, `false` otherwise.+ fn is_expr_constant(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {+ // As an example, assume that we know columns `a` and `b` are constant.+ // Then, `a`, `b` and `a + b` will all return `true` whereas `c` will+ // return `false`.+ let normalized_constants = self.eq_group.normalize_exprs(self.constants.to_vec());+ let normalized_expr = self.eq_group.normalize_expr(expr.clone());+ is_constant_recurse(&normalized_constants, &normalized_expr)+ }++ /// Retrieves the ordering information for a given physical expression.+ ///+ /// This function constructs an `ExprOrdering` object for the provided+ /// expression, which encapsulates information about the expression's+ /// ordering, including its [`SortProperties`].+ ///+ /// # Arguments+ ///+ /// - `expr`: An `Arc<dyn PhysicalExpr>` representing the physical expression+ /// for which ordering information is sought.+ ///+ /// # Returns+ ///+ /// Returns an `ExprOrdering` object containing the ordering information for+ /// the given expression.+ pub fn get_expr_ordering(&self, expr: Arc<dyn PhysicalExpr>) -> ExprOrdering {+ ExprOrdering::new(expr.clone())+ .transform_up(&|expr| Ok(update_ordering(expr, self)))+ // Guaranteed to always return `Ok`.+ .unwrap()+ }+}++/// Calculates the [`SortProperties`] of a given [`ExprOrdering`] node.+/// The node can either be a leaf node, or an intermediate node:+/// - If it is a leaf node, we directly find the order of the node by looking+/// at the given sort expression and equivalence properties if it is a `Column`+/// leaf, or we mark it as unordered. In the case of a `Literal` leaf, we mark+/// it as singleton so that it can cooperate with all ordered columns.+/// - If it is an intermediate node, the children states matter. Each `PhysicalExpr`+/// and operator has its own rules on how to propagate the children orderings.+/// However, before we engage in recursion, we check whether this intermediate+/// node directly matches with the sort expression. If there is a match, the+/// sort expression emerges at that node immediately, discarding the recursive+/// result coming from its children.+fn update_ordering(+ mut node: ExprOrdering,+ eq_properties: &EquivalenceProperties,+) -> Transformed<ExprOrdering> {+ // We have a Column, which is one of the two possible leaf node types:+ let normalized_expr = eq_properties.eq_group.normalize_expr(node.expr.clone());+ if eq_properties.is_expr_constant(&normalized_expr) {+ node.state = SortProperties::Singleton;+ } else if let Some(options) = eq_properties+ .normalized_oeq_class()+ .get_options(&normalized_expr)+ {+ node.state = SortProperties::Ordered(options);+ } else if !node.expr.children().is_empty() {+ // We have an intermediate (non-leaf) node, account for its children:+ node.state = node.expr.get_ordering(&node.children_state());+ } else if node.expr.as_any().is::<Literal>() {+ // We have a Literal, which is the other possible leaf node type:+ node.state = node.expr.get_ordering(&[]);+ } else {+ return Transformed::No(node);+ }+ Transformed::Yes(node)+}++/// This function determines whether the provided expression is constant+/// based on the known constants.+///+/// # Arguments+///+/// - `constants`: A `&[Arc<dyn PhysicalExpr>]` containing expressions known to+/// be a constant.+/// - `expr`: A reference to a `Arc<dyn PhysicalExpr>` representing the expression+/// to check.+///+/// # Returns+///+/// Returns `true` if the expression is constant according to equivalence+/// group, `false` otherwise.+fn is_constant_recurse(+ constants: &[Arc<dyn PhysicalExpr>],+ expr: &Arc<dyn PhysicalExpr>,+) -> bool {+ if physical_exprs_contains(constants, expr) {+ return true;+ }+ let children = expr.children();+ !children.is_empty() && children.iter().all(|c| is_constant_recurse(constants, c))+}++/// This function examines whether a referring expression directly refers to a+/// given referred expression or if any of its children in the expression tree+/// refer to the specified expression.+///+/// # Parameters+///+/// - `referring_expr`: A reference to the referring expression (`Arc<dyn PhysicalExpr>`).+/// - `referred_expr`: A reference to the referred expression (`Arc<dyn PhysicalExpr>`)+///+/// # Returns+///+/// A boolean value indicating whether `referring_expr` refers (needs it to evaluate its result)+/// `referred_expr` or not.+fn expr_refers(+ referring_expr: &Arc<dyn PhysicalExpr>,+ referred_expr: &Arc<dyn PhysicalExpr>,+) -> bool {+ referring_expr.eq(referred_expr)+ || referring_expr+ .children()+ .iter()+ .any(|child| expr_refers(child, referred_expr))+}++/// This function analyzes the dependency map to collect referred dependencies for+/// a given source expression.+///+/// # Parameters+///+/// - `dependency_map`: A reference to the `DependencyMap` where each+/// `PhysicalSortExpr` is associated with a `DependencyNode`.+/// - `source`: A reference to the source expression (`Arc<dyn PhysicalExpr>`)+/// for which relevant dependencies need to be identified.+///+/// # Returns+///+/// A `Vec<Dependencies>` containing the dependencies for the given source+/// expression. These dependencies are expressions that are referred to by+/// the source expression based on the provided dependency map.+fn referred_dependencies(+ dependency_map: &DependencyMap,+ source: &Arc<dyn PhysicalExpr>,+) -> Vec<Dependencies> {+ // Associate `PhysicalExpr`s with `PhysicalSortExpr`s that contain them:+ let mut expr_to_sort_exprs = HashMap::<ExprWrapper, Dependencies>::new();+ for sort_expr in dependency_map+ .keys()+ .filter(|sort_expr| expr_refers(source, &sort_expr.expr))+ {+ let key = ExprWrapper(sort_expr.expr.clone());+ expr_to_sort_exprs+ .entry(key)+ .or_default()+ .insert(sort_expr.clone());+ }++ // Generate all valid dependencies for the source. For example, if the source+ // is `a + b` and the map is `[a -> (a ASC, a DESC), b -> (b ASC)]`, we get+ // `vec![HashSet(a ASC, b ASC), HashSet(a DESC, b ASC)]`.+ expr_to_sort_exprs+ .values()+ .multi_cartesian_product()+ .map(|referred_deps| referred_deps.into_iter().cloned().collect())+ .collect()+}++/// This function retrieves the dependencies of the given relevant sort expression+/// from the given dependency map. It then constructs prefix orderings by recursively+/// analyzing the dependencies and include them in the orderings.+///+/// # Parameters+///+/// - `relevant_sort_expr`: A reference to the relevant sort expression+/// (`PhysicalSortExpr`) for which prefix orderings are to be constructed.+/// - `dependency_map`: A reference to the `DependencyMap` containing dependencies.+///+/// # Returns+///+/// A vector of prefix orderings (`Vec<LexOrdering>`) based on the given relevant+/// sort expression and its dependencies.+fn construct_prefix_orderings(+ relevant_sort_expr: &PhysicalSortExpr,+ dependency_map: &DependencyMap,+) -> Vec<LexOrdering> {+ dependency_map[relevant_sort_expr]+ .dependencies+ .iter()+ .flat_map(|dep| construct_orderings(dep, dependency_map))+ .collect()+}++/// Given a set of relevant dependencies (`relevant_deps`) and a map of dependencies+/// (`dependency_map`), this function generates all possible prefix orderings+/// based on the given dependencies.+///+/// # Parameters+///+/// * `dependencies` - A reference to the dependencies.+/// * `dependency_map` - A reference to the map of dependencies for expressions.+///+/// # Returns+///+/// A vector of lexical orderings (`Vec<LexOrdering>`) representing all valid orderings+/// based on the given dependencies.+fn generate_dependency_orderings(+ dependencies: &Dependencies,+ dependency_map: &DependencyMap,+) -> Vec<LexOrdering> {+ // Construct all the valid prefix orderings for each expression appearing+ // in the projection:+ let relevant_prefixes = dependencies+ .iter()+ .flat_map(|dep| {+ let prefixes = construct_prefix_orderings(dep, dependency_map);+ (!prefixes.is_empty()).then_some(prefixes)+ })+ .collect::<Vec<_>>();++ // No dependency, dependent is a leading ordering.+ if relevant_prefixes.is_empty() {+ // Return an empty ordering:+ return vec![vec![]];+ }++ // Generate all possible orderings where dependencies are satisfied for the+ // current projection expression. For example, if expression is `a + b ASC`,+ // and the dependency for `a ASC` is `[c ASC]`, the dependency for `b ASC`+ // is `[d DESC]`, then we generate `[c ASC, d DESC, a + b ASC]` and+ // `[d DESC, c ASC, a + b ASC]`.+ relevant_prefixes+ .into_iter()+ .multi_cartesian_product()+ .flat_map(|prefix_orderings| {+ prefix_orderings+ .iter()+ .permutations(prefix_orderings.len())+ .map(|prefixes| prefixes.into_iter().flatten().cloned().collect())+ .collect::<Vec<_>>()+ })+ .collect()+}++/// This function examines the given expression and the sort expressions it+/// refers to determine the ordering properties of the expression.+///+/// # Parameters+///+/// - `expr`: A reference to the source expression (`Arc<dyn PhysicalExpr>`) for+/// which ordering properties need to be determined.+/// - `dependencies`: A reference to `Dependencies`, containing sort expressions+/// referred to by `expr`.+///+/// # Returns+///+/// A `SortProperties` indicating the ordering information of the given expression.+fn get_expr_ordering(+ expr: &Arc<dyn PhysicalExpr>,+ dependencies: &Dependencies,+) -> SortProperties {+ if let Some(column_order) = dependencies.iter().find(|&order| expr.eq(&order.expr)) {+ // If exact match is found, return its ordering.+ SortProperties::Ordered(column_order.options)+ } else {+ // Find orderings of its children+ let child_states = expr+ .children()+ .iter()+ .map(|child| get_expr_ordering(child, dependencies))+ .collect::<Vec<_>>();+ // Calculate expression ordering using ordering of its children.+ expr.get_ordering(&child_states)+ }+}++/// Represents a node in the dependency map used to construct projected orderings.+///+/// A `DependencyNode` contains information about a particular sort expression,+/// including its target sort expression and a set of dependencies on other sort+/// expressions.+///+/// # Fields+///+/// - `target_sort_expr`: An optional `PhysicalSortExpr` representing the target+/// sort expression associated with the node. It is `None` if the sort expression+/// cannot be projected.+/// - `dependencies`: A [`Dependencies`] containing dependencies on other sort+/// expressions that are referred to by the target sort expression.+#[derive(Debug, Clone, PartialEq, Eq)]+struct DependencyNode {+ target_sort_expr: Option<PhysicalSortExpr>,+ dependencies: Dependencies,+}++impl DependencyNode {+ // Insert dependency to the state (if exists).+ fn insert_dependency(&mut self, dependency: Option<&PhysicalSortExpr>) {+ if let Some(dep) = dependency {+ self.dependencies.insert(dep.clone());+ }+ }+}++type DependencyMap = HashMap<PhysicalSortExpr, DependencyNode>;+type Dependencies = HashSet<PhysicalSortExpr>;++/// This function recursively analyzes the dependencies of the given sort+/// expression within the given dependency map to construct lexicographical+/// orderings that include the sort expression and its dependencies.+///+/// # Parameters+///+/// - `referred_sort_expr`: A reference to the sort expression (`PhysicalSortExpr`)+/// for which lexicographical orderings satisfying its dependencies are to be+/// constructed.+/// - `dependency_map`: A reference to the `DependencyMap` that contains+/// dependencies for different `PhysicalSortExpr`s.+///+/// # Returns+///+/// A vector of lexicographical orderings (`Vec<LexOrdering>`) based on the given+/// sort expression and its dependencies.+fn construct_orderings(+ referred_sort_expr: &PhysicalSortExpr,+ dependency_map: &DependencyMap,+) -> Vec<LexOrdering> {+ // We are sure that `referred_sort_expr` is inside `dependency_map`.+ let node = &dependency_map[referred_sort_expr];+ // Since we work on intermediate nodes, we are sure `val.target_sort_expr`+ // exists.+ let target_sort_expr = node.target_sort_expr.clone().unwrap();+ if node.dependencies.is_empty() {+ vec![vec![target_sort_expr]]+ } else {+ node.dependencies+ .iter()+ .flat_map(|dep| {+ let mut orderings = construct_orderings(dep, dependency_map);+ for ordering in orderings.iter_mut() {+ ordering.push(target_sort_expr.clone())+ }+ orderings+ })+ .collect()+ }+}++/// Calculate ordering equivalence properties for the given join operation.+pub fn join_equivalence_properties(+ left: EquivalenceProperties,+ right: EquivalenceProperties,+ join_type: &JoinType,+ join_schema: SchemaRef,+ maintains_input_order: &[bool],+ probe_side: Option<JoinSide>,+ on: &[(Column, Column)],+) -> EquivalenceProperties {+ let left_size = left.schema.fields.len();+ let mut result = EquivalenceProperties::new(join_schema);+ result.add_equivalence_group(left.eq_group().join(+ right.eq_group(),+ join_type,+ left_size,+ on,+ ));++ let left_oeq_class = left.oeq_class;+ let mut right_oeq_class = right.oeq_class;+ match maintains_input_order {+ [true, false] => {+ // In this special case, right side ordering can be prefixed with+ // the left side ordering.+ if let (Some(JoinSide::Left), JoinType::Inner) = (probe_side, join_type) {+ updated_right_ordering_equivalence_class(+ &mut right_oeq_class,+ join_type,+ left_size,+ );++ // 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.+ //+ // For example, if the right side ordering equivalences contain+ // `b ASC`, and the left side ordering equivalences contain `a ASC`,+ // then we should add `a ASC, b ASC` to the ordering equivalences+ // of the join output.+ let out_oeq_class = left_oeq_class.join_suffix(&right_oeq_class);+ result.add_ordering_equivalence_class(out_oeq_class);+ } else {+ result.add_ordering_equivalence_class(left_oeq_class);+ }+ }+ [false, true] => {+ updated_right_ordering_equivalence_class(+ &mut right_oeq_class,+ join_type,+ left_size,+ );+ // In this special case, left side ordering can be prefixed with+ // the right side ordering.+ if let (Some(JoinSide::Right), JoinType::Inner) = (probe_side, join_type) {+ // 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.+ //+ // For example, if the left side ordering equivalences contain+ // `a ASC`, and the right side ordering equivalences contain `b ASC`,+ // then we should add `b ASC, a ASC` to the ordering equivalences+ // of the join output.+ let out_oeq_class = right_oeq_class.join_suffix(&left_oeq_class);+ result.add_ordering_equivalence_class(out_oeq_class);+ } else {+ result.add_ordering_equivalence_class(right_oeq_class);+ }+ }+ [false, false] => {}+ [true, true] => unreachable!("Cannot maintain ordering of both sides"),+ _ => unreachable!("Join operators can not have more than two children"),+ }+ result+}++/// In the context of a join, update the right side `OrderingEquivalenceClass`+/// so that they point to valid indices in the join output schema.+///+/// To do so, we increment column indices by the size of the left table when+/// join schema consists of a combination of the left and right schemas. This+/// is the case for `Inner`, `Left`, `Full` and `Right` joins. For other cases,+/// indices do not change.+fn updated_right_ordering_equivalence_class(+ right_oeq_class: &mut OrderingEquivalenceClass,+ join_type: &JoinType,+ left_size: usize,+) {+ if matches!(+ join_type,+ JoinType::Inner | JoinType::Left | JoinType::Full | JoinType::Right+ ) {+ right_oeq_class.add_offset(left_size);+ }+}++/// Wrapper struct for `Arc<dyn PhysicalExpr>` to use them as keys in a hash map.+#[derive(Debug, Clone)]+struct ExprWrapper(Arc<dyn PhysicalExpr>);++impl PartialEq<Self> for ExprWrapper {+ fn eq(&self, other: &Self) -> bool {+ self.0.eq(&other.0)+ }+}++impl Eq for ExprWrapper {}++impl Hash for ExprWrapper {+ fn hash<H: Hasher>(&self, state: &mut H) {+ self.0.hash(state);+ }+}++#[cfg(test)]+mod tests {+ use std::ops::Not;+ use std::sync::Arc;++ use super::*;+ use crate::equivalence::add_offset_to_expr;+ use crate::equivalence::tests::{+ convert_to_orderings, convert_to_sort_exprs, convert_to_sort_reqs,+ create_random_schema, create_test_params, create_test_schema,+ generate_table_for_eq_properties, is_table_same_after_sort, output_schema,+ };+ use crate::execution_props::ExecutionProps;+ use crate::expressions::{col, BinaryExpr, Column};+ use crate::functions::create_physical_expr;+ use crate::PhysicalSortExpr;+ use arrow::datatypes::{DataType, Field, Schema};+ use arrow_schema::{Fields, SortOptions, TimeUnit};+ use datafusion_common::Result;+ use datafusion_expr::{BuiltinScalarFunction, Operator};+ use itertools::Itertools;++ #[test]+ fn project_equivalence_properties_test() -> Result<()> {+ let input_schema = Arc::new(Schema::new(vec![+ Field::new("a", DataType::Int64, true),+ Field::new("b", DataType::Int64, true),+ Field::new("c", DataType::Int64, true),+ ]));++ let input_properties = EquivalenceProperties::new(input_schema.clone());+ let col_a = col("a", &input_schema)?;++ // a as a1, a as a2, a as a3, a as a3+ let proj_exprs = vec![+ (col_a.clone(), "a1".to_string()),+ (col_a.clone(), "a2".to_string()),+ (col_a.clone(), "a3".to_string()),+ (col_a.clone(), "a4".to_string()),+ ];+ let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &input_schema)?;++ let out_schema = output_schema(&projection_mapping, &input_schema)?;+ // a as a1, a as a2, a as a3, a as a3+ let proj_exprs = vec![+ (col_a.clone(), "a1".to_string()),+ (col_a.clone(), "a2".to_string()),+ (col_a.clone(), "a3".to_string()),+ (col_a.clone(), "a4".to_string()),+ ];+ let projection_mapping = ProjectionMapping::try_new(&proj_exprs, &input_schema)?;++ // a as a1, a as a2, a as a3, a as a3+ let col_a1 = &col("a1", &out_schema)?;+ let col_a2 = &col("a2", &out_schema)?;+ let col_a3 = &col("a3", &out_schema)?;+ let col_a4 = &col("a4", &out_schema)?;+ let out_properties = input_properties.project(&projection_mapping, out_schema);++ // At the output a1=a2=a3=a4+ assert_eq!(out_properties.eq_group().len(), 1);+ let eq_class = &out_properties.eq_group().classes[0];+ assert_eq!(eq_class.len(), 4);+ assert!(eq_class.contains(col_a1));+ assert!(eq_class.contains(col_a2));+ assert!(eq_class.contains(col_a3));+ assert!(eq_class.contains(col_a4));++ Ok(())+ }++ #[test]+ fn test_join_equivalence_properties() -> Result<()> {+ let schema = create_test_schema()?;+ let col_a = &col("a", &schema)?;+ let col_b = &col("b", &schema)?;+ let col_c = &col("c", &schema)?;+ let offset = schema.fields.len();+ let col_a2 = &add_offset_to_expr(col_a.clone(), offset);+ let col_b2 = &add_offset_to_expr(col_b.clone(), offset);+ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ let test_cases = vec![+ // ------- TEST CASE 1 --------+ // [a ASC], [b ASC]+ (+ // [a ASC], [b ASC]+ vec![vec![(col_a, option_asc)], vec![(col_b, option_asc)]],+ // [a ASC], [b ASC]+ vec![vec![(col_a, option_asc)], vec![(col_b, option_asc)]],+ // expected [a ASC, a2 ASC], [a ASC, b2 ASC], [b ASC, a2 ASC], [b ASC, b2 ASC]+ vec![+ vec![(col_a, option_asc), (col_a2, option_asc)],+ vec![(col_a, option_asc), (col_b2, option_asc)],+ vec![(col_b, option_asc), (col_a2, option_asc)],+ vec![(col_b, option_asc), (col_b2, option_asc)],+ ],+ ),+ // ------- TEST CASE 2 --------+ // [a ASC], [b ASC]+ (+ // [a ASC], [b ASC], [c ASC]+ vec![+ vec![(col_a, option_asc)],+ vec![(col_b, option_asc)],+ vec![(col_c, option_asc)],+ ],+ // [a ASC], [b ASC]+ vec![vec![(col_a, option_asc)], vec![(col_b, option_asc)]],+ // expected [a ASC, a2 ASC], [a ASC, b2 ASC], [b ASC, a2 ASC], [b ASC, b2 ASC], [c ASC, a2 ASC], [c ASC, b2 ASC]+ vec![+ vec![(col_a, option_asc), (col_a2, option_asc)],+ vec![(col_a, option_asc), (col_b2, option_asc)],+ vec![(col_b, option_asc), (col_a2, option_asc)],+ vec![(col_b, option_asc), (col_b2, option_asc)],+ vec![(col_c, option_asc), (col_a2, option_asc)],+ vec![(col_c, option_asc), (col_b2, option_asc)],+ ],+ ),+ ];+ for (left_orderings, right_orderings, expected) in test_cases {+ let mut left_eq_properties = EquivalenceProperties::new(schema.clone());+ let mut right_eq_properties = EquivalenceProperties::new(schema.clone());+ let left_orderings = convert_to_orderings(&left_orderings);+ let right_orderings = convert_to_orderings(&right_orderings);+ let expected = convert_to_orderings(&expected);+ left_eq_properties.add_new_orderings(left_orderings);+ right_eq_properties.add_new_orderings(right_orderings);+ let join_eq = join_equivalence_properties(+ left_eq_properties,+ right_eq_properties,+ &JoinType::Inner,+ Arc::new(Schema::empty()),+ &[true, false],+ Some(JoinSide::Left),+ &[],+ );+ let orderings = &join_eq.oeq_class.orderings;+ let err_msg = format!("expected: {:?}, actual:{:?}", expected, orderings);+ assert_eq!(+ join_eq.oeq_class.orderings.len(),+ expected.len(),+ "{}",+ err_msg+ );+ for ordering in orderings {+ assert!(+ expected.contains(ordering),+ "{}, ordering: {:?}",+ err_msg,+ ordering+ );+ }+ }+ Ok(())+ }++ #[test]+ fn test_expr_consists_of_constants() -> Result<()> {+ let schema = Arc::new(Schema::new(vec![+ Field::new("a", DataType::Int32, true),+ Field::new("b", DataType::Int32, true),+ Field::new("c", DataType::Int32, true),+ Field::new("d", DataType::Int32, true),+ Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),+ ]));+ let col_a = col("a", &schema)?;+ let col_b = col("b", &schema)?;+ let col_d = col("d", &schema)?;+ let b_plus_d = Arc::new(BinaryExpr::new(+ col_b.clone(),+ Operator::Plus,+ col_d.clone(),+ )) as Arc<dyn PhysicalExpr>;++ let constants = vec![col_a.clone(), col_b.clone()];+ let expr = b_plus_d.clone();+ assert!(!is_constant_recurse(&constants, &expr));++ let constants = vec![col_a.clone(), col_b.clone(), col_d.clone()];+ let expr = b_plus_d.clone();+ assert!(is_constant_recurse(&constants, &expr));+ Ok(())+ }++ #[test]+ fn test_get_updated_right_ordering_equivalence_properties() -> Result<()> {+ let join_type = JoinType::Inner;+ // Join right child schema+ let child_fields: Fields = ["x", "y", "z", "w"]+ .into_iter()+ .map(|name| Field::new(name, DataType::Int32, true))+ .collect();+ let child_schema = Schema::new(child_fields);+ let col_x = &col("x", &child_schema)?;+ let col_y = &col("y", &child_schema)?;+ let col_z = &col("z", &child_schema)?;+ let col_w = &col("w", &child_schema)?;+ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ // [x ASC, y ASC], [z ASC, w ASC]+ let orderings = vec![+ vec![(col_x, option_asc), (col_y, option_asc)],+ vec![(col_z, option_asc), (col_w, option_asc)],+ ];+ let orderings = convert_to_orderings(&orderings);+ // Right child ordering equivalences+ let mut right_oeq_class = OrderingEquivalenceClass::new(orderings);++ let left_columns_len = 4;++ let fields: Fields = ["a", "b", "c", "d", "x", "y", "z", "w"]+ .into_iter()+ .map(|name| Field::new(name, DataType::Int32, true))+ .collect();++ // Join Schema+ let schema = Schema::new(fields);+ let col_a = &col("a", &schema)?;+ let col_d = &col("d", &schema)?;+ let col_x = &col("x", &schema)?;+ let col_y = &col("y", &schema)?;+ let col_z = &col("z", &schema)?;+ let col_w = &col("w", &schema)?;++ let mut join_eq_properties = EquivalenceProperties::new(Arc::new(schema));+ // a=x and d=w+ join_eq_properties.add_equal_conditions(col_a, col_x);+ join_eq_properties.add_equal_conditions(col_d, col_w);++ updated_right_ordering_equivalence_class(+ &mut right_oeq_class,+ &join_type,+ left_columns_len,+ );+ join_eq_properties.add_ordering_equivalence_class(right_oeq_class);+ let result = join_eq_properties.oeq_class().clone();++ // [x ASC, y ASC], [z ASC, w ASC]+ let orderings = vec![+ vec![(col_x, option_asc), (col_y, option_asc)],+ vec![(col_z, option_asc), (col_w, option_asc)],+ ];+ let orderings = convert_to_orderings(&orderings);+ let expected = OrderingEquivalenceClass::new(orderings);++ assert_eq!(result, expected);++ Ok(())+ }++ #[test]+ fn test_normalize_ordering_equivalence_classes() -> Result<()> {+ let sort_options = SortOptions::default();++ let schema = Schema::new(vec![+ Field::new("a", DataType::Int32, true),+ Field::new("b", DataType::Int32, true),+ Field::new("c", DataType::Int32, true),+ ]);+ let col_a_expr = col("a", &schema)?;+ let col_b_expr = col("b", &schema)?;+ let col_c_expr = col("c", &schema)?;+ let mut eq_properties = EquivalenceProperties::new(Arc::new(schema.clone()));++ eq_properties.add_equal_conditions(&col_a_expr, &col_c_expr);+ let others = vec![+ vec![PhysicalSortExpr {+ expr: col_b_expr.clone(),+ options: sort_options,+ }],+ vec![PhysicalSortExpr {+ expr: col_c_expr.clone(),+ options: sort_options,+ }],+ ];+ eq_properties.add_new_orderings(others);++ let mut expected_eqs = EquivalenceProperties::new(Arc::new(schema));+ expected_eqs.add_new_orderings([+ vec![PhysicalSortExpr {+ expr: col_b_expr.clone(),+ options: sort_options,+ }],+ vec![PhysicalSortExpr {+ expr: col_c_expr.clone(),+ options: sort_options,+ }],+ ]);++ let oeq_class = eq_properties.oeq_class().clone();+ let expected = expected_eqs.oeq_class();+ assert!(oeq_class.eq(expected));++ Ok(())+ }++ #[test]+ fn test_get_indices_of_matching_sort_exprs_with_order_eq() -> Result<()> {+ let sort_options = SortOptions::default();+ let sort_options_not = SortOptions::default().not();++ let schema = Schema::new(vec![+ Field::new("a", DataType::Int32, true),+ Field::new("b", DataType::Int32, true),+ ]);+ let col_a = &col("a", &schema)?;+ let col_b = &col("b", &schema)?;+ let required_columns = [col_b.clone(), col_a.clone()];+ let mut eq_properties = EquivalenceProperties::new(Arc::new(schema));+ eq_properties.add_new_orderings([vec![+ PhysicalSortExpr {+ expr: Arc::new(Column::new("b", 1)),+ options: sort_options_not,+ },+ PhysicalSortExpr {+ expr: Arc::new(Column::new("a", 0)),+ options: sort_options,+ },+ ]]);+ let (result, idxs) = eq_properties.find_longest_permutation(&required_columns);+ assert_eq!(idxs, vec![0, 1]);+ assert_eq!(+ result,+ vec![+ PhysicalSortExpr {+ expr: col_b.clone(),+ options: sort_options_not+ },+ PhysicalSortExpr {+ expr: col_a.clone(),+ options: sort_options+ }+ ]+ );++ let schema = Schema::new(vec![+ Field::new("a", DataType::Int32, true),+ Field::new("b", DataType::Int32, true),+ Field::new("c", DataType::Int32, true),+ ]);+ let col_a = &col("a", &schema)?;+ let col_b = &col("b", &schema)?;+ let required_columns = [col_b.clone(), col_a.clone()];+ let mut eq_properties = EquivalenceProperties::new(Arc::new(schema));+ eq_properties.add_new_orderings([+ vec![PhysicalSortExpr {+ expr: Arc::new(Column::new("c", 2)),+ options: sort_options,+ }],+ vec![+ PhysicalSortExpr {+ expr: Arc::new(Column::new("b", 1)),+ options: sort_options_not,+ },+ PhysicalSortExpr {+ expr: Arc::new(Column::new("a", 0)),+ options: sort_options,+ },+ ],+ ]);+ let (result, idxs) = eq_properties.find_longest_permutation(&required_columns);+ assert_eq!(idxs, vec![0, 1]);+ assert_eq!(+ result,+ vec![+ PhysicalSortExpr {+ expr: col_b.clone(),+ options: sort_options_not+ },+ PhysicalSortExpr {+ expr: col_a.clone(),+ options: sort_options+ }+ ]+ );++ let required_columns = [+ Arc::new(Column::new("b", 1)) as _,+ Arc::new(Column::new("a", 0)) as _,+ ];+ let schema = Schema::new(vec![+ Field::new("a", DataType::Int32, true),+ Field::new("b", DataType::Int32, true),+ Field::new("c", DataType::Int32, true),+ ]);+ let mut eq_properties = EquivalenceProperties::new(Arc::new(schema));++ // not satisfied orders+ eq_properties.add_new_orderings([vec![+ PhysicalSortExpr {+ expr: Arc::new(Column::new("b", 1)),+ options: sort_options_not,+ },+ PhysicalSortExpr {+ expr: Arc::new(Column::new("c", 2)),+ options: sort_options,+ },+ PhysicalSortExpr {+ expr: Arc::new(Column::new("a", 0)),+ options: sort_options,+ },+ ]]);+ let (_, idxs) = eq_properties.find_longest_permutation(&required_columns);+ assert_eq!(idxs, vec![0]);++ Ok(())+ }++ #[test]+ fn test_update_ordering() -> Result<()> {+ let schema = Schema::new(vec![+ Field::new("a", DataType::Int32, true),+ Field::new("b", DataType::Int32, true),+ Field::new("c", DataType::Int32, true),+ Field::new("d", DataType::Int32, true),+ ]);++ let mut eq_properties = EquivalenceProperties::new(Arc::new(schema.clone()));+ let col_a = &col("a", &schema)?;+ let col_b = &col("b", &schema)?;+ let col_c = &col("c", &schema)?;+ let col_d = &col("d", &schema)?;+ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ // b=a (e.g they are aliases)+ eq_properties.add_equal_conditions(col_b, col_a);+ // [b ASC], [d ASC]+ eq_properties.add_new_orderings(vec![+ vec![PhysicalSortExpr {+ expr: col_b.clone(),+ options: option_asc,+ }],+ vec![PhysicalSortExpr {+ expr: col_d.clone(),+ options: option_asc,+ }],+ ]);++ let test_cases = vec![+ // d + b+ (+ Arc::new(BinaryExpr::new(+ col_d.clone(),+ Operator::Plus,+ col_b.clone(),+ )) as Arc<dyn PhysicalExpr>,+ SortProperties::Ordered(option_asc),+ ),+ // b+ (col_b.clone(), SortProperties::Ordered(option_asc)),+ // a+ (col_a.clone(), SortProperties::Ordered(option_asc)),+ // a + c+ (+ Arc::new(BinaryExpr::new(+ col_a.clone(),+ Operator::Plus,+ col_c.clone(),+ )),+ SortProperties::Unordered,+ ),+ ];+ for (expr, expected) in test_cases {+ let leading_orderings = eq_properties+ .oeq_class()+ .iter()+ .flat_map(|ordering| ordering.first().cloned())+ .collect::<Vec<_>>();+ let expr_ordering = eq_properties.get_expr_ordering(expr.clone());+ let err_msg = format!(+ "expr:{:?}, expected: {:?}, actual: {:?}, leading_orderings: {leading_orderings:?}",+ expr, expected, expr_ordering.state+ );+ assert_eq!(expr_ordering.state, expected, "{}", err_msg);+ }++ Ok(())+ }++ #[test]+ fn test_find_longest_permutation_random() -> Result<()> {+ const N_RANDOM_SCHEMA: usize = 100;+ const N_ELEMENTS: usize = 125;+ const N_DISTINCT: usize = 5;++ for seed in 0..N_RANDOM_SCHEMA {+ // Create a random schema with random properties+ let (test_schema, eq_properties) = create_random_schema(seed as u64)?;+ // Generate a data that satisfies properties given+ let table_data_with_properties =+ generate_table_for_eq_properties(&eq_properties, N_ELEMENTS, N_DISTINCT)?;++ let floor_a = create_physical_expr(+ &BuiltinScalarFunction::Floor,+ &[col("a", &test_schema)?],+ &test_schema,+ &ExecutionProps::default(),+ )?;+ let a_plus_b = Arc::new(BinaryExpr::new(+ col("a", &test_schema)?,+ Operator::Plus,+ col("b", &test_schema)?,+ )) as Arc<dyn PhysicalExpr>;+ let exprs = vec![+ col("a", &test_schema)?,+ col("b", &test_schema)?,+ col("c", &test_schema)?,+ col("d", &test_schema)?,+ col("e", &test_schema)?,+ col("f", &test_schema)?,+ floor_a,+ a_plus_b,+ ];++ for n_req in 0..=exprs.len() {+ for exprs in exprs.iter().combinations(n_req) {+ let exprs = exprs.into_iter().cloned().collect::<Vec<_>>();+ let (ordering, indices) =+ eq_properties.find_longest_permutation(&exprs);+ // Make sure that find_longest_permutation return values are consistent+ let ordering2 = indices+ .iter()+ .zip(ordering.iter())+ .map(|(&idx, sort_expr)| PhysicalSortExpr {+ expr: exprs[idx].clone(),+ options: sort_expr.options,+ })+ .collect::<Vec<_>>();+ assert_eq!(+ ordering, ordering2,+ "indices and lexicographical ordering do not match"+ );++ let err_msg = format!(+ "Error in test case ordering:{:?}, eq_properties.oeq_class: {:?}, eq_properties.eq_group: {:?}, eq_properties.constants: {:?}",+ ordering, eq_properties.oeq_class, eq_properties.eq_group, eq_properties.constants+ );+ assert_eq!(ordering.len(), indices.len(), "{}", err_msg);+ // Since ordered section satisfies schema, we expect+ // that result will be same after sort (e.g sort was unnecessary).+ assert!(+ is_table_same_after_sort(+ ordering.clone(),+ table_data_with_properties.clone(),+ )?,+ "{}",+ err_msg+ );+ }+ }+ }++ Ok(())+ }+ #[test]+ fn test_find_longest_permutation() -> Result<()> {+ // Schema satisfies following orderings:+ // [a ASC], [d ASC, b ASC], [e DESC, f ASC, g ASC]+ // and+ // Column [a=c] (e.g they are aliases).+ // At below we add [d ASC, h DESC] also, for test purposes+ let (test_schema, mut eq_properties) = create_test_params()?;+ let col_a = &col("a", &test_schema)?;+ let col_b = &col("b", &test_schema)?;+ let col_c = &col("c", &test_schema)?;+ let col_d = &col("d", &test_schema)?;+ let col_e = &col("e", &test_schema)?;+ let col_h = &col("h", &test_schema)?;+ // a + d+ let a_plus_d = Arc::new(BinaryExpr::new(+ col_a.clone(),+ Operator::Plus,+ col_d.clone(),+ )) as Arc<dyn PhysicalExpr>;++ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ let option_desc = SortOptions {+ descending: true,+ nulls_first: true,+ };+ // [d ASC, h ASC] also satisfies schema.+ eq_properties.add_new_orderings([vec![+ PhysicalSortExpr {+ expr: col_d.clone(),+ options: option_asc,+ },+ PhysicalSortExpr {+ expr: col_h.clone(),+ options: option_desc,+ },+ ]]);+ let test_cases = vec![+ // TEST CASE 1+ (vec![col_a], vec![(col_a, option_asc)]),+ // TEST CASE 2+ (vec![col_c], vec![(col_c, option_asc)]),+ // TEST CASE 3+ (+ vec![col_d, col_e, col_b],+ vec![+ (col_d, option_asc),+ (col_e, option_desc),+ (col_b, option_asc),+ ],+ ),+ // TEST CASE 4+ (vec![col_b], vec![]),+ // TEST CASE 5+ (vec![col_d], vec![(col_d, option_asc)]),+ // TEST CASE 5+ (vec![&a_plus_d], vec![(&a_plus_d, option_asc)]),+ // TEST CASE 6+ (+ vec![col_b, col_d],+ vec![(col_d, option_asc), (col_b, option_asc)],+ ),+ // TEST CASE 6+ (+ vec![col_c, col_e],+ vec![(col_c, option_asc), (col_e, option_desc)],+ ),+ ];+ for (exprs, expected) in test_cases {+ let exprs = exprs.into_iter().cloned().collect::<Vec<_>>();+ let expected = convert_to_sort_exprs(&expected);+ let (actual, _) = eq_properties.find_longest_permutation(&exprs);+ assert_eq!(actual, expected);+ }++ Ok(())+ }+ #[test]+ fn test_get_meet_ordering() -> Result<()> {+ let schema = create_test_schema()?;+ let col_a = &col("a", &schema)?;+ let col_b = &col("b", &schema)?;+ let eq_properties = EquivalenceProperties::new(schema);+ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ let option_desc = SortOptions {+ descending: true,+ nulls_first: true,+ };+ let tests_cases = vec![+ // Get meet ordering between [a ASC] and [a ASC, b ASC]+ // result should be [a ASC]+ (+ vec![(col_a, option_asc)],+ vec![(col_a, option_asc), (col_b, option_asc)],+ Some(vec![(col_a, option_asc)]),+ ),+ // Get meet ordering between [a ASC] and [a DESC]+ // result should be None.+ (vec![(col_a, option_asc)], vec![(col_a, option_desc)], None),+ // Get meet ordering between [a ASC, b ASC] and [a ASC, b DESC]+ // result should be [a ASC].+ (+ vec![(col_a, option_asc), (col_b, option_asc)],+ vec![(col_a, option_asc), (col_b, option_desc)],+ Some(vec![(col_a, option_asc)]),+ ),+ ];+ for (lhs, rhs, expected) in tests_cases {+ let lhs = convert_to_sort_exprs(&lhs);+ let rhs = convert_to_sort_exprs(&rhs);+ let expected = expected.map(|expected| convert_to_sort_exprs(&expected));+ let finer = eq_properties.get_meet_ordering(&lhs, &rhs);+ assert_eq!(finer, expected)+ }++ Ok(())+ }++ #[test]+ fn test_get_finer() -> Result<()> {+ let schema = create_test_schema()?;+ let col_a = &col("a", &schema)?;+ let col_b = &col("b", &schema)?;+ let col_c = &col("c", &schema)?;+ let eq_properties = EquivalenceProperties::new(schema);+ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ let option_desc = SortOptions {+ descending: true,+ nulls_first: true,+ };+ // First entry, and second entry are the physical sort requirement that are argument for get_finer_requirement.+ // Third entry is the expected result.+ let tests_cases = vec![+ // Get finer requirement between [a Some(ASC)] and [a None, b Some(ASC)]+ // result should be [a Some(ASC), b Some(ASC)]+ (+ vec![(col_a, Some(option_asc))],+ vec![(col_a, None), (col_b, Some(option_asc))],+ Some(vec![(col_a, Some(option_asc)), (col_b, Some(option_asc))]),+ ),+ // Get finer requirement between [a Some(ASC), b Some(ASC), c Some(ASC)] and [a Some(ASC), b Some(ASC)]+ // result should be [a Some(ASC), b Some(ASC), c Some(ASC)]+ (+ vec![+ (col_a, Some(option_asc)),+ (col_b, Some(option_asc)),+ (col_c, Some(option_asc)),+ ],+ vec![(col_a, Some(option_asc)), (col_b, Some(option_asc))],+ Some(vec![+ (col_a, Some(option_asc)),+ (col_b, Some(option_asc)),+ (col_c, Some(option_asc)),+ ]),+ ),+ // Get finer requirement between [a Some(ASC), b Some(ASC)] and [a Some(ASC), b Some(DESC)]+ // result should be None+ (+ vec![(col_a, Some(option_asc)), (col_b, Some(option_asc))],+ vec![(col_a, Some(option_asc)), (col_b, Some(option_desc))],+ None,+ ),+ ];+ for (lhs, rhs, expected) in tests_cases {+ let lhs = convert_to_sort_reqs(&lhs);+ let rhs = convert_to_sort_reqs(&rhs);+ let expected = expected.map(|expected| convert_to_sort_reqs(&expected));+ let finer = eq_properties.get_finer_requirement(&lhs, &rhs);+ assert_eq!(finer, expected)+ }++ Ok(())+ }++ #[test]+ fn test_normalize_sort_reqs() -> Result<()> {+ // Schema satisfies following properties+ // a=c+ // and following orderings are valid+ // [a ASC], [d ASC, b ASC], [e DESC, f ASC, g ASC]+ let (test_schema, eq_properties) = create_test_params()?;+ let col_a = &col("a", &test_schema)?;+ let col_b = &col("b", &test_schema)?;+ let col_c = &col("c", &test_schema)?;+ let col_d = &col("d", &test_schema)?;+ let col_e = &col("e", &test_schema)?;+ let col_f = &col("f", &test_schema)?;+ let option_asc = SortOptions {+ descending: false,+ nulls_first: false,+ };+ let option_desc = SortOptions {+ descending: true,+ nulls_first: true,+ };+ // First element in the tuple stores vector of requirement, second element is the expected return value for ordering_satisfy function+ let requirements = vec![+ (+ vec![(col_a, Some(option_asc))],+ vec![(col_a, Some(option_asc))],+ ),+ (+ vec![(col_a, Some(option_desc))],+ vec![(col_a, Some(option_desc))],+ ),+ (vec![(col_a, None)], vec![(col_a, None)]),+ // Test whether equivalence works as expected+ (+ vec![(col_c, Some(option_asc))],+ vec![(col_a, Some(option_asc))],+ ),+ (vec![(col_c, None)], vec![(col_a, None)]),+ // Test whether ordering equivalence works as expected+ (+ vec![(col_d, Some(option_asc)), (col_b, Some(option_asc))],+ vec![(col_d, Some(option_asc)), (col_b, Some(option_asc))],+ ),+ (+ vec![(col_d, None), (col_b, None)],+ vec![(col_d, None), (col_b, None)],+ ),+ (+ vec![(col_e, Some(option_desc)), (col_f, Some(option_asc))],+ vec![(col_e, Some(option_desc)), (col_f, Some(option_asc))],+ ),+ // We should be able to normalize in compatible requirements also (not exactly equal)+ (+ vec![(col_e, Some(option_desc)), (col_f, None)],+ vec![(col_e, Some(option_desc)), (col_f, None)],+ ),+ (+ vec![(col_e, None), (col_f, None)],+ vec![(col_e, None), (col_f, None)],+ ),+ ];++ for (reqs, expected_normalized) in requirements.into_iter() {+ let req = convert_to_sort_reqs(&reqs);+ let expected_normalized = convert_to_sort_reqs(&expected_normalized);++ assert_eq!(+ eq_properties.normalize_sort_requirements(&req),+ expected_normalized+ );+ }++ Ok(())+ }++ #[test]+ fn test_schema_normalize_sort_requirement_with_equivalence() -> Result<()> {+ let option1 = SortOptions {+ descending: false,+ nulls_first: false,+ };+ // Assume that column a and c are aliases.+ let (test_schema, eq_properties) = create_test_params()?;+ let col_a = &col("a", &test_schema)?;+ let col_c = &col("c", &test_schema)?;+ let col_d = &col("d", &test_schema)?;++ // Test cases for equivalence normalization+ // First entry in the tuple is PhysicalSortRequirement, second entry in the tuple is+ // expected PhysicalSortRequirement after normalization.+ let test_cases = vec![+ (vec![(col_a, Some(option1))], vec![(col_a, Some(option1))]),+ // In the normalized version column c should be replace with column a+ (vec![(col_c, Some(option1))], vec![(col_a, Some(option1))]),+ (vec![(col_c, None)], vec![(col_a, None)]),+ (vec![(col_d, Some(option1))], vec![(col_d, Some(option1))]),+ ];+ for (reqs, expected) in test_cases.into_iter() {+ let reqs = convert_to_sort_reqs(&reqs);+ let expected = convert_to_sort_reqs(&expected);++ let normalized = eq_properties.normalize_sort_requirements(&reqs);+ assert!(+ expected.eq(&normalized),+ "error in test: reqs: {reqs:?}, expected: {expected:?}, normalized: {normalized:?}"+ );+ }++ Ok(())+ }+}