Skip to main content

datafusion_physical_expr/equivalence/
ordering.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::fmt::Display;
6use std::ops::Deref;
7use std::sync::Arc;
8use std::vec::IntoIter;
9
10use crate::expressions::with_new_schema;
11use crate::{LexOrdering, PhysicalExpr, add_offset_to_physical_sort_exprs};
12
13use arrow::compute::SortOptions;
14use arrow::datatypes::SchemaRef;
15use datafusion_common::Result;
16use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
17
18/// An `OrderingEquivalenceClass` keeps track of distinct alternative orderings
19/// than can describe a table. For example, consider the following table:
20///
21/// ```text
22/// ┌───┬───┬───┬───┐
23/// │ a │ b │ c │ d │
24/// ├───┼───┼───┼───┤
25/// │ 1 │ 4 │ 3 │ 1 │
26/// │ 2 │ 3 │ 3 │ 2 │
27/// │ 3 │ 1 │ 2 │ 2 │
28/// │ 3 │ 2 │ 1 │ 3 │
29/// └───┴───┴───┴───┘
30/// ```
31///
32/// Here, both `[a ASC, b ASC]` and `[c DESC, d ASC]` describe the table
33/// ordering. In this case, we say that these orderings are equivalent.
34///
35/// An `OrderingEquivalenceClass` is a set of such equivalent orderings, which
36/// is represented by a vector of `LexOrdering`s. The set does not store any
37/// redundant information by enforcing the invariant that no suffix of an
38/// ordering in the equivalence class is a prefix of another ordering in the
39/// equivalence class. The set can be empty, which means that there are no
40/// orderings that describe the table.
41#[derive(Clone, Debug, Default, Eq, PartialEq)]
42pub struct OrderingEquivalenceClass {
43    orderings: Vec<LexOrdering>,
44}
45
46impl OrderingEquivalenceClass {
47    /// Clears (empties) this ordering equivalence class.
48    pub fn clear(&mut self) {
49        self.orderings.clear();
50    }
51
52    /// Creates a new ordering equivalence class from the given orderings
53    /// and removes any redundant entries (if given).
54    pub fn new(
55        orderings: impl IntoIterator<Item = impl IntoIterator<Item = PhysicalSortExpr>>,
56    ) -> Self {
57        let mut result = Self {
58            orderings: orderings.into_iter().filter_map(LexOrdering::new).collect(),
59        };
60        result.remove_redundant_entries();
61        result
62    }
63
64    /// Extend this ordering equivalence class with the given orderings.
65    pub fn extend(&mut self, orderings: impl IntoIterator<Item = LexOrdering>) {
66        self.orderings.extend(orderings);
67        // Make sure that there are no redundant orderings:
68        self.remove_redundant_entries();
69    }
70
71    /// Adds new orderings into this ordering equivalence class.
72    pub fn add_orderings(
73        &mut self,
74        sort_exprs: impl IntoIterator<Item = impl IntoIterator<Item = PhysicalSortExpr>>,
75    ) {
76        self.orderings
77            .extend(sort_exprs.into_iter().filter_map(LexOrdering::new));
78        // Make sure that there are no redundant orderings:
79        self.remove_redundant_entries();
80    }
81
82    /// Removes redundant orderings from this ordering equivalence class.
83    ///
84    /// For instance, if we already have the ordering `[a ASC, b ASC, c DESC]`,
85    /// then there is no need to keep ordering `[a ASC, b ASC]` in the state.
86    fn remove_redundant_entries(&mut self) {
87        let mut work = true;
88        while work {
89            work = false;
90            let mut idx = 0;
91            'outer: while idx < self.orderings.len() {
92                let mut ordering_idx = idx + 1;
93                while ordering_idx < self.orderings.len() {
94                    if let Some(remove) = self.resolve_overlap(idx, ordering_idx) {
95                        work = true;
96                        if remove {
97                            self.orderings.swap_remove(idx);
98                            continue 'outer;
99                        }
100                    }
101                    if let Some(remove) = self.resolve_overlap(ordering_idx, idx) {
102                        work = true;
103                        if remove {
104                            self.orderings.swap_remove(ordering_idx);
105                            continue;
106                        }
107                    }
108                    ordering_idx += 1;
109                }
110                idx += 1;
111            }
112        }
113    }
114
115    /// Trims `orderings[idx]` if some suffix of it overlaps with a prefix of
116    /// `orderings[pre_idx]`. If there is any overlap, returns a `Some(true)`
117    /// if any trimming took place, and `Some(false)` otherwise. If there is
118    /// no overlap, returns `None`.
119    ///
120    /// For example, if `orderings[idx]` is `[a ASC, b ASC, c DESC]` and
121    /// `orderings[pre_idx]` is `[b ASC, c DESC]`, then the function will trim
122    /// `orderings[idx]` to `[a ASC]`.
123    fn resolve_overlap(&mut self, idx: usize, pre_idx: usize) -> Option<bool> {
124        let length = self.orderings[idx].len();
125        let other_length = self.orderings[pre_idx].len();
126        for overlap in 1..=length.min(other_length) {
127            if self.orderings[idx][length - overlap..]
128                == self.orderings[pre_idx][..overlap]
129            {
130                return Some(!self.orderings[idx].truncate(length - overlap));
131            }
132        }
133        None
134    }
135
136    /// Returns the concatenation of all the orderings. This enables merge
137    /// operations to preserve all equivalent orderings simultaneously.
138    pub fn output_ordering(&self) -> Option<LexOrdering> {
139        self.orderings.iter().cloned().reduce(|mut cat, o| {
140            cat.extend(o);
141            cat
142        })
143    }
144
145    // Append orderings in `other` to all existing orderings in this ordering
146    // equivalence class.
147    pub fn join_suffix(mut self, other: &Self) -> Self {
148        let n_ordering = self.orderings.len();
149        // Replicate entries before cross product:
150        let n_cross = std::cmp::max(n_ordering, other.len() * n_ordering);
151        self.orderings = self.orderings.into_iter().cycle().take(n_cross).collect();
152        // Append sort expressions of `other` to the current orderings:
153        for (outer_idx, ordering) in other.iter().enumerate() {
154            let base = outer_idx * n_ordering;
155            // Use the cross product index:
156            for idx in base..(base + n_ordering) {
157                self.orderings[idx].extend(ordering.iter().cloned());
158            }
159        }
160        self
161    }
162
163    /// Adds `offset` value to the index of each expression inside this
164    /// ordering equivalence class.
165    pub fn add_offset(&mut self, offset: isize) -> Result<()> {
166        let orderings = std::mem::take(&mut self.orderings);
167        for ordering_result in orderings
168            .into_iter()
169            .map(|o| add_offset_to_physical_sort_exprs(o, offset))
170        {
171            self.orderings.extend(LexOrdering::new(ordering_result?));
172        }
173        Ok(())
174    }
175
176    /// Transforms this `OrderingEquivalenceClass` by mapping columns in the
177    /// original schema to columns in the new schema by index. The new schema
178    /// and the original schema needs to be aligned; i.e. they should have the
179    /// same number of columns, and fields at the same index have the same type
180    /// in both schemas.
181    pub fn with_new_schema(mut self, schema: &SchemaRef) -> Result<Self> {
182        self.orderings = self
183            .orderings
184            .into_iter()
185            .map(|ordering| {
186                ordering
187                    .into_iter()
188                    .map(|mut sort_expr| {
189                        sort_expr.expr = with_new_schema(sort_expr.expr, schema)?;
190                        Ok(sort_expr)
191                    })
192                    .collect::<Result<Vec<_>>>()
193                    // The following `unwrap` is safe because the vector will always
194                    // be non-empty.
195                    .map(|v| LexOrdering::new(v).unwrap())
196            })
197            .collect::<Result<_>>()?;
198        Ok(self)
199    }
200
201    /// Gets sort options associated with this expression if it is a leading
202    /// ordering expression. Otherwise, returns `None`.
203    pub fn get_options(&self, expr: &Arc<dyn PhysicalExpr>) -> Option<SortOptions> {
204        for ordering in self.iter() {
205            let leading_ordering = &ordering[0];
206            if leading_ordering.expr.eq(expr) {
207                return Some(leading_ordering.options);
208            }
209        }
210        None
211    }
212
213    /// Checks whether `expr` has a single value according to this ordering
214    /// equivalence class: whether one ordering starts with `expr` in some
215    /// direction and another starts with it in the exact reverse, such as
216    /// `ASC NULLS LAST` and `DESC NULLS FIRST`. Rows sorted both ways all have
217    /// the same value (or are all null).
218    ///
219    /// This is how a value that is constant only within groups of rows is
220    /// recorded, since a `ConstExpr` is constant across all rows. For example,
221    /// `SUM(x) OVER (PARTITION BY k)` has one value per `k`, so the window adds
222    /// `[k, w]` once for each of the four directions of `w`.
223    ///
224    /// ### Future Improvements
225    ///
226    /// This function may become unnecessary if any of the following improvements
227    /// are implemented:
228    /// 1. `SortOptions` supports encoding constantness information.
229    /// 2. `EquivalenceProperties` gains `FunctionalDependency` awareness, eliminating
230    ///    the need for `Constant` and `Constraints`.
231    pub fn is_expr_partial_const(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {
232        is_partial_const(self.iter().map(|ordering| ordering.first()), expr)
233    }
234}
235
236/// Checks whether `expr` has a single value according to the leading sort
237/// expressions of some orderings: whether `expr` leads one of them in some
238/// direction and another in the exact reverse. See
239/// [`OrderingEquivalenceClass::is_expr_partial_const`].
240pub(crate) fn is_partial_const<'a>(
241    leading: impl Iterator<Item = &'a PhysicalSortExpr> + Clone,
242    expr: &Arc<dyn PhysicalExpr>,
243) -> bool {
244    let leads_in = move |options: SortOptions| {
245        leading
246            .clone()
247            .any(|sort_expr| sort_expr.options == options && sort_expr.expr.eq(expr))
248    };
249    // `!` gives the exact reverse, e.g. `DESC NULLS FIRST` for `ASC NULLS LAST`.
250    let asc_nulls_first = SortOptions::default().asc().nulls_first();
251    let asc_nulls_last = SortOptions::default().asc().nulls_last();
252    (leads_in(asc_nulls_first) && leads_in(!asc_nulls_first))
253        || (leads_in(asc_nulls_last) && leads_in(!asc_nulls_last))
254}
255
256impl Deref for OrderingEquivalenceClass {
257    type Target = [LexOrdering];
258
259    fn deref(&self) -> &Self::Target {
260        self.orderings.as_slice()
261    }
262}
263
264impl From<Vec<LexOrdering>> for OrderingEquivalenceClass {
265    fn from(orderings: Vec<LexOrdering>) -> Self {
266        let mut result = Self { orderings };
267        result.remove_redundant_entries();
268        result
269    }
270}
271
272/// Convert the `OrderingEquivalenceClass` into an iterator of `LexOrdering`s.
273impl IntoIterator for OrderingEquivalenceClass {
274    type Item = LexOrdering;
275    type IntoIter = IntoIter<Self::Item>;
276
277    fn into_iter(self) -> Self::IntoIter {
278        self.orderings.into_iter()
279    }
280}
281
282impl Display for OrderingEquivalenceClass {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        write!(f, "[")?;
285        let mut iter = self.orderings.iter();
286        if let Some(ordering) = iter.next() {
287            write!(f, "[{ordering}]")?;
288        }
289        for ordering in iter {
290            write!(f, ", [{ordering}]")?;
291        }
292        write!(f, "]")
293    }
294}
295
296impl From<OrderingEquivalenceClass> for Vec<LexOrdering> {
297    fn from(oeq_class: OrderingEquivalenceClass) -> Self {
298        oeq_class.orderings
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use std::sync::Arc;
305
306    use crate::equivalence::tests::create_test_schema;
307    use crate::equivalence::{
308        EquivalenceClass, EquivalenceGroup, EquivalenceProperties,
309        OrderingEquivalenceClass, convert_to_orderings, convert_to_sort_exprs,
310    };
311    use crate::expressions::{BinaryExpr, CastExpr, Column, col};
312    use crate::utils::tests::TestScalarUDF;
313    use crate::{
314        AcrossPartitions, ConstExpr, PhysicalExpr, PhysicalExprRef, PhysicalSortExpr,
315        ScalarFunctionExpr,
316    };
317
318    use arrow::compute::SortOptions;
319    use arrow::datatypes::{DataType, Field, Schema};
320    use datafusion_common::Result;
321    use datafusion_common::config::ConfigOptions;
322    use datafusion_expr::{Operator, ScalarUDF};
323
324    #[test]
325    fn test_ordering_satisfy() -> Result<()> {
326        let input_schema = Arc::new(Schema::new(vec![
327            Field::new("a", DataType::Int64, true),
328            Field::new("b", DataType::Int64, true),
329        ]));
330        let crude = vec![PhysicalSortExpr {
331            expr: Arc::new(Column::new("a", 0)),
332            options: SortOptions::default(),
333        }];
334        let finer = vec![
335            PhysicalSortExpr {
336                expr: Arc::new(Column::new("a", 0)),
337                options: SortOptions::default(),
338            },
339            PhysicalSortExpr {
340                expr: Arc::new(Column::new("b", 1)),
341                options: SortOptions::default(),
342            },
343        ];
344        // finer ordering satisfies, crude ordering should return true
345        let eq_properties_finer = EquivalenceProperties::new_with_orderings(
346            Arc::clone(&input_schema),
347            [finer.clone()],
348        );
349        assert!(eq_properties_finer.ordering_satisfy(crude.clone())?);
350
351        // Crude ordering doesn't satisfy finer ordering. should return false
352        let eq_properties_crude =
353            EquivalenceProperties::new_with_orderings(Arc::clone(&input_schema), [crude]);
354        assert!(!eq_properties_crude.ordering_satisfy(finer)?);
355        Ok(())
356    }
357
358    #[test]
359    fn test_ordering_satisfy_strictly_order_preserving() -> Result<()> {
360        let schema = Arc::new(Schema::new(vec![
361            Field::new("a", DataType::Int32, true),
362            Field::new("b", DataType::Int64, true),
363        ]));
364        let col_a = col("a", &schema)?;
365        let col_b = col("b", &schema)?;
366        let asc = SortOptions::default();
367        let sort_a = PhysicalSortExpr::new(Arc::clone(&col_a), asc);
368        let sort_b = PhysicalSortExpr::new(Arc::clone(&col_b), asc);
369        let eq_properties = EquivalenceProperties::new_with_orderings(
370            Arc::clone(&schema),
371            [vec![sort_a.clone(), sort_b.clone()]],
372        );
373
374        assert!(eq_properties.ordering_satisfy(vec![sort_a.clone(), sort_b.clone()])?);
375        assert!(eq_properties.ordering_satisfy(vec![sort_a.clone()])?);
376
377        // A widening cast is strictly order-preserving: `a` is constant
378        // within each group of equal `CAST(a AS BIGINT)` values, so `b`
379        // remains sorted within those groups.
380        let widening = Arc::new(CastExpr::new(Arc::clone(&col_a), DataType::Int64, None))
381            as PhysicalExprRef;
382        let sort_widening = PhysicalSortExpr::new(widening, asc);
383        assert!(eq_properties.ordering_satisfy(vec![sort_widening, sort_b.clone()])?);
384
385        // A narrowing cast is only monotonic: it satisfies as a leading key,
386        // but it may collapse distinct `a` values, so `b` is not guaranteed
387        // to be sorted within its tie groups.
388        let narrowing = Arc::new(CastExpr::new(Arc::clone(&col_a), DataType::Int16, None))
389            as PhysicalExprRef;
390        let sort_narrowing = PhysicalSortExpr::new(narrowing, asc);
391        assert!(eq_properties.ordering_satisfy(vec![sort_narrowing.clone()])?);
392        assert!(!eq_properties.ordering_satisfy(vec![sort_narrowing, sort_b.clone()])?);
393
394        Ok(())
395    }
396
397    #[test]
398    fn test_ordering_satisfy_with_equivalence2() -> Result<()> {
399        let test_schema = create_test_schema()?;
400        let col_a = &col("a", &test_schema)?;
401        let col_b = &col("b", &test_schema)?;
402        let col_c = &col("c", &test_schema)?;
403        let col_d = &col("d", &test_schema)?;
404        let col_e = &col("e", &test_schema)?;
405        let col_f = &col("f", &test_schema)?;
406        let test_fun = Arc::new(ScalarUDF::new_from_impl(TestScalarUDF::new()));
407
408        let floor_a = Arc::new(ScalarFunctionExpr::try_new(
409            Arc::clone(&test_fun),
410            vec![Arc::clone(col_a)],
411            &test_schema,
412            Arc::new(ConfigOptions::default()),
413        )?) as PhysicalExprRef;
414        let floor_f = Arc::new(ScalarFunctionExpr::try_new(
415            Arc::clone(&test_fun),
416            vec![Arc::clone(col_f)],
417            &test_schema,
418            Arc::new(ConfigOptions::default()),
419        )?) as PhysicalExprRef;
420        let exp_a = Arc::new(ScalarFunctionExpr::try_new(
421            Arc::clone(&test_fun),
422            vec![Arc::clone(col_a)],
423            &test_schema,
424            Arc::new(ConfigOptions::default()),
425        )?) as PhysicalExprRef;
426
427        let a_plus_b = Arc::new(BinaryExpr::new(
428            Arc::clone(col_a),
429            Operator::Plus,
430            Arc::clone(col_b),
431        )) as Arc<dyn PhysicalExpr>;
432        let options = SortOptions {
433            descending: false,
434            nulls_first: false,
435        };
436
437        let test_cases = vec![
438            // ------------ TEST CASE 1 ------------
439            (
440                // orderings
441                vec![
442                    // [a ASC, d ASC, b ASC]
443                    vec![(col_a, options), (col_d, options), (col_b, options)],
444                    // [c ASC]
445                    vec![(col_c, options)],
446                ],
447                // equivalence classes
448                vec![vec![col_a, col_f]],
449                // constants
450                vec![col_e],
451                // requirement [a ASC, b ASC], requirement is not satisfied.
452                vec![(col_a, options), (col_b, options)],
453                // expected: requirement is not satisfied.
454                false,
455            ),
456            // ------------ TEST CASE 2 ------------
457            (
458                // orderings
459                vec![
460                    // [a ASC, c ASC, b ASC]
461                    vec![(col_a, options), (col_c, options), (col_b, options)],
462                    // [d ASC]
463                    vec![(col_d, options)],
464                ],
465                // equivalence classes
466                vec![vec![col_a, col_f]],
467                // constants
468                vec![col_e],
469                // requirement [floor(a) ASC],
470                vec![(&floor_a, options)],
471                // expected: requirement is satisfied.
472                true,
473            ),
474            // ------------ TEST CASE 2.1 ------------
475            (
476                // orderings
477                vec![
478                    // [a ASC, c ASC, b ASC]
479                    vec![(col_a, options), (col_c, options), (col_b, options)],
480                    // [d ASC]
481                    vec![(col_d, options)],
482                ],
483                // equivalence classes
484                vec![vec![col_a, col_f]],
485                // constants
486                vec![col_e],
487                // requirement [floor(f) ASC], (Please note that a=f)
488                vec![(&floor_f, options)],
489                // expected: requirement is satisfied.
490                true,
491            ),
492            // ------------ TEST CASE 3 ------------
493            (
494                // orderings
495                vec![
496                    // [a ASC, c ASC, b ASC]
497                    vec![(col_a, options), (col_c, options), (col_b, options)],
498                    // [d ASC]
499                    vec![(col_d, options)],
500                ],
501                // equivalence classes
502                vec![vec![col_a, col_f]],
503                // constants
504                vec![col_e],
505                // requirement [a ASC, c ASC, a+b ASC],
506                vec![(col_a, options), (col_c, options), (&a_plus_b, options)],
507                // expected: requirement is not satisfied because addition can wrap.
508                false,
509            ),
510            // ------------ TEST CASE 4 ------------
511            (
512                // orderings
513                vec![
514                    // [a ASC, b ASC, c ASC, d ASC]
515                    vec![
516                        (col_a, options),
517                        (col_b, options),
518                        (col_c, options),
519                        (col_d, options),
520                    ],
521                ],
522                // equivalence classes
523                vec![vec![col_a, col_f]],
524                // constants
525                vec![col_e],
526                // requirement [floor(a) ASC, a+b ASC],
527                vec![(&floor_a, options), (&a_plus_b, options)],
528                // expected: requirement is satisfied.
529                false,
530            ),
531            // ------------ TEST CASE 5 ------------
532            (
533                // orderings
534                vec![
535                    // [a ASC, b ASC, c ASC, d ASC]
536                    vec![
537                        (col_a, options),
538                        (col_b, options),
539                        (col_c, options),
540                        (col_d, options),
541                    ],
542                ],
543                // equivalence classes
544                vec![vec![col_a, col_f]],
545                // constants
546                vec![col_e],
547                // requirement [exp(a) ASC, a+b ASC],
548                vec![(&exp_a, options), (&a_plus_b, options)],
549                // expected: requirement is not satisfied.
550                // TODO: If we know that exp function is 1-to-1 function.
551                //  we could have deduced that above requirement is satisfied.
552                false,
553            ),
554            // ------------ TEST CASE 6 ------------
555            (
556                // orderings
557                vec![
558                    // [a ASC, d ASC, b ASC]
559                    vec![(col_a, options), (col_d, options), (col_b, options)],
560                    // [c ASC]
561                    vec![(col_c, options)],
562                ],
563                // equivalence classes
564                vec![vec![col_a, col_f]],
565                // constants
566                vec![col_e],
567                // requirement [a ASC, d ASC, floor(a) ASC],
568                vec![(col_a, options), (col_d, options), (&floor_a, options)],
569                // expected: requirement is satisfied.
570                true,
571            ),
572            // ------------ TEST CASE 7 ------------
573            (
574                // orderings
575                vec![
576                    // [a ASC, c ASC, b ASC]
577                    vec![(col_a, options), (col_c, options), (col_b, options)],
578                    // [d ASC]
579                    vec![(col_d, options)],
580                ],
581                // equivalence classes
582                vec![vec![col_a, col_f]],
583                // constants
584                vec![col_e],
585                // requirement [a ASC, floor(a) ASC, a + b ASC],
586                vec![(col_a, options), (&floor_a, options), (&a_plus_b, options)],
587                // expected: requirement is not satisfied.
588                false,
589            ),
590            // ------------ TEST CASE 8 ------------
591            (
592                // orderings
593                vec![
594                    // [a ASC, b ASC, c ASC]
595                    vec![(col_a, options), (col_b, options), (col_c, options)],
596                    // [d ASC]
597                    vec![(col_d, options)],
598                ],
599                // equivalence classes
600                vec![vec![col_a, col_f]],
601                // constants
602                vec![col_e],
603                // requirement [a ASC, c ASC, floor(a) ASC, a + b ASC],
604                vec![
605                    (col_a, options),
606                    (col_c, options),
607                    (&floor_a, options),
608                    (&a_plus_b, options),
609                ],
610                // expected: requirement is not satisfied.
611                false,
612            ),
613            // ------------ TEST CASE 9 ------------
614            (
615                // orderings
616                vec![
617                    // [a ASC, b ASC, c ASC, d ASC]
618                    vec![
619                        (col_a, options),
620                        (col_b, options),
621                        (col_c, options),
622                        (col_d, options),
623                    ],
624                ],
625                // equivalence classes
626                vec![vec![col_a, col_f]],
627                // constants
628                vec![col_e],
629                // requirement [a ASC, b ASC, c ASC, floor(a) ASC],
630                vec![
631                    (col_a, options),
632                    (col_b, options),
633                    (col_c, options),
634                    (&floor_a, options),
635                ],
636                // expected: requirement is satisfied.
637                true,
638            ),
639            // ------------ TEST CASE 10 ------------
640            (
641                // orderings
642                vec![
643                    // [d ASC, b ASC]
644                    vec![(col_d, options), (col_b, options)],
645                    // [c ASC, a ASC]
646                    vec![(col_c, options), (col_a, options)],
647                ],
648                // equivalence classes
649                vec![vec![col_a, col_f]],
650                // constants
651                vec![col_e],
652                // requirement [c ASC, d ASC, a + b ASC],
653                vec![(col_c, options), (col_d, options), (&a_plus_b, options)],
654                // expected: requirement is not satisfied because addition can wrap.
655                false,
656            ),
657        ];
658
659        for (orderings, eq_group, constants, reqs, expected) in test_cases {
660            let err_msg = format!(
661                "error in test orderings: {orderings:?}, eq_group: {eq_group:?}, constants: {constants:?}, reqs: {reqs:?}, expected: {expected:?}"
662            );
663            let mut eq_properties = EquivalenceProperties::new(Arc::clone(&test_schema));
664            let orderings = convert_to_orderings(&orderings);
665            eq_properties.add_orderings(orderings);
666            let classes = eq_group
667                .into_iter()
668                .map(|eq_class| EquivalenceClass::new(eq_class.into_iter().cloned()));
669            let eq_group = EquivalenceGroup::new(classes);
670            eq_properties.add_equivalence_group(eq_group)?;
671
672            let constants = constants.into_iter().map(|expr| {
673                ConstExpr::new(Arc::clone(expr), AcrossPartitions::Uniform(None))
674            });
675            eq_properties.add_constants(constants)?;
676
677            let reqs = convert_to_sort_exprs(&reqs);
678            assert_eq!(eq_properties.ordering_satisfy(reqs)?, expected, "{err_msg}");
679        }
680
681        Ok(())
682    }
683
684    #[test]
685    fn test_ordering_satisfy_different_lengths() -> Result<()> {
686        let test_schema = create_test_schema()?;
687        let col_a = &col("a", &test_schema)?;
688        let col_b = &col("b", &test_schema)?;
689        let col_c = &col("c", &test_schema)?;
690        let col_d = &col("d", &test_schema)?;
691        let col_e = &col("e", &test_schema)?;
692        let col_f = &col("f", &test_schema)?;
693        let options = SortOptions {
694            descending: false,
695            nulls_first: false,
696        };
697        // a=c (e.g they are aliases).
698        let mut eq_properties = EquivalenceProperties::new(test_schema);
699        eq_properties.add_equal_conditions(Arc::clone(col_a), Arc::clone(col_c))?;
700
701        let orderings = vec![
702            vec![(col_a, options)],
703            vec![(col_e, options)],
704            vec![(col_d, options), (col_f, options)],
705        ];
706        let orderings = convert_to_orderings(&orderings);
707
708        // Column [a ASC], [e ASC], [d ASC, f ASC] are all valid orderings for the schema.
709        eq_properties.add_orderings(orderings);
710
711        // First entry in the tuple is required ordering, second entry is the expected flag
712        // that indicates whether this required ordering is satisfied.
713        // ([a ASC], true) indicate a ASC requirement is already satisfied by existing orderings.
714        let test_cases = vec![
715            // [c ASC, a ASC, e ASC], expected represents this requirement is satisfied
716            (
717                vec![(col_c, options), (col_a, options), (col_e, options)],
718                true,
719            ),
720            (vec![(col_c, options), (col_b, options)], false),
721            (vec![(col_c, options), (col_d, options)], true),
722            (
723                vec![(col_d, options), (col_f, options), (col_b, options)],
724                false,
725            ),
726            (vec![(col_d, options), (col_f, options)], true),
727        ];
728
729        for (reqs, expected) in test_cases {
730            let err_msg = format!("error in test reqs: {reqs:?}, expected: {expected:?}");
731            let reqs = convert_to_sort_exprs(&reqs);
732            assert_eq!(eq_properties.ordering_satisfy(reqs)?, expected, "{err_msg}");
733        }
734
735        Ok(())
736    }
737
738    #[test]
739    fn test_remove_redundant_entries_oeq_class() -> Result<()> {
740        let schema = create_test_schema()?;
741        let col_a = &col("a", &schema)?;
742        let col_b = &col("b", &schema)?;
743        let col_c = &col("c", &schema)?;
744        let col_d = &col("d", &schema)?;
745        let col_e = &col("e", &schema)?;
746
747        let option_asc = SortOptions {
748            descending: false,
749            nulls_first: false,
750        };
751        let option_desc = SortOptions {
752            descending: true,
753            nulls_first: true,
754        };
755
756        // First entry in the tuple is the given orderings for the table
757        // Second entry is the simplest version of the given orderings that is functionally equivalent.
758        let test_cases = vec![
759            // ------- TEST CASE 1 ---------
760            (
761                // ORDERINGS GIVEN
762                vec![
763                    // [a ASC, b ASC]
764                    vec![(col_a, option_asc), (col_b, option_asc)],
765                ],
766                // EXPECTED orderings that is succinct.
767                vec![
768                    // [a ASC, b ASC]
769                    vec![(col_a, option_asc), (col_b, option_asc)],
770                ],
771            ),
772            // ------- TEST CASE 2 ---------
773            (
774                // ORDERINGS GIVEN
775                vec![
776                    // [a ASC, b ASC]
777                    vec![(col_a, option_asc), (col_b, option_asc)],
778                    // [a ASC, b ASC, c ASC]
779                    vec![
780                        (col_a, option_asc),
781                        (col_b, option_asc),
782                        (col_c, option_asc),
783                    ],
784                ],
785                // EXPECTED orderings that is succinct.
786                vec![
787                    // [a ASC, b ASC, c ASC]
788                    vec![
789                        (col_a, option_asc),
790                        (col_b, option_asc),
791                        (col_c, option_asc),
792                    ],
793                ],
794            ),
795            // ------- TEST CASE 3 ---------
796            (
797                // ORDERINGS GIVEN
798                vec![
799                    // [a ASC, b DESC]
800                    vec![(col_a, option_asc), (col_b, option_desc)],
801                    // [a ASC]
802                    vec![(col_a, option_asc)],
803                    // [a ASC, c ASC]
804                    vec![(col_a, option_asc), (col_c, option_asc)],
805                ],
806                // EXPECTED orderings that is succinct.
807                vec![
808                    // [a ASC, b DESC]
809                    vec![(col_a, option_asc), (col_b, option_desc)],
810                    // [a ASC, c ASC]
811                    vec![(col_a, option_asc), (col_c, option_asc)],
812                ],
813            ),
814            // ------- TEST CASE 4 ---------
815            (
816                // ORDERINGS GIVEN
817                vec![
818                    // [a ASC, b ASC]
819                    vec![(col_a, option_asc), (col_b, option_asc)],
820                    // [a ASC, b ASC, c ASC]
821                    vec![
822                        (col_a, option_asc),
823                        (col_b, option_asc),
824                        (col_c, option_asc),
825                    ],
826                    // [a ASC]
827                    vec![(col_a, option_asc)],
828                ],
829                // EXPECTED orderings that is succinct.
830                vec![
831                    // [a ASC, b ASC, c ASC]
832                    vec![
833                        (col_a, option_asc),
834                        (col_b, option_asc),
835                        (col_c, option_asc),
836                    ],
837                ],
838            ),
839            // ------- TEST CASE 5 ---------
840            // Empty ordering
841            (
842                vec![],
843                // No ordering in the state (empty ordering is ignored).
844                vec![],
845            ),
846            // ------- TEST CASE 6 ---------
847            (
848                // ORDERINGS GIVEN
849                vec![
850                    // [a ASC, b ASC]
851                    vec![(col_a, option_asc), (col_b, option_asc)],
852                    // [b ASC]
853                    vec![(col_b, option_asc)],
854                ],
855                // EXPECTED orderings that is succinct.
856                vec![
857                    // [a ASC]
858                    vec![(col_a, option_asc)],
859                    // [b ASC]
860                    vec![(col_b, option_asc)],
861                ],
862            ),
863            // ------- TEST CASE 7 ---------
864            // b, a
865            // c, a
866            // d, b, c
867            (
868                // ORDERINGS GIVEN
869                vec![
870                    // [b ASC, a ASC]
871                    vec![(col_b, option_asc), (col_a, option_asc)],
872                    // [c ASC, a ASC]
873                    vec![(col_c, option_asc), (col_a, option_asc)],
874                    // [d ASC, b ASC, c ASC]
875                    vec![
876                        (col_d, option_asc),
877                        (col_b, option_asc),
878                        (col_c, option_asc),
879                    ],
880                ],
881                // EXPECTED orderings that is succinct.
882                vec![
883                    // [b ASC, a ASC]
884                    vec![(col_b, option_asc), (col_a, option_asc)],
885                    // [c ASC, a ASC]
886                    vec![(col_c, option_asc), (col_a, option_asc)],
887                    // [d ASC]
888                    vec![(col_d, option_asc)],
889                ],
890            ),
891            // ------- TEST CASE 8 ---------
892            // b, e
893            // c, a
894            // d, b, e, c, a
895            (
896                // ORDERINGS GIVEN
897                vec![
898                    // [b ASC, e ASC]
899                    vec![(col_b, option_asc), (col_e, option_asc)],
900                    // [c ASC, a ASC]
901                    vec![(col_c, option_asc), (col_a, option_asc)],
902                    // [d ASC, b ASC, e ASC, c ASC, a ASC]
903                    vec![
904                        (col_d, option_asc),
905                        (col_b, option_asc),
906                        (col_e, option_asc),
907                        (col_c, option_asc),
908                        (col_a, option_asc),
909                    ],
910                ],
911                // EXPECTED orderings that is succinct.
912                vec![
913                    // [b ASC, e ASC]
914                    vec![(col_b, option_asc), (col_e, option_asc)],
915                    // [c ASC, a ASC]
916                    vec![(col_c, option_asc), (col_a, option_asc)],
917                    // [d ASC]
918                    vec![(col_d, option_asc)],
919                ],
920            ),
921            // ------- TEST CASE 9 ---------
922            // b
923            // a, b, c
924            // d, a, b
925            (
926                // ORDERINGS GIVEN
927                vec![
928                    // [b ASC]
929                    vec![(col_b, option_asc)],
930                    // [a ASC, b ASC, c ASC]
931                    vec![
932                        (col_a, option_asc),
933                        (col_b, option_asc),
934                        (col_c, option_asc),
935                    ],
936                    // [d ASC, a ASC, b ASC]
937                    vec![
938                        (col_d, option_asc),
939                        (col_a, option_asc),
940                        (col_b, option_asc),
941                    ],
942                ],
943                // EXPECTED orderings that is succinct.
944                vec![
945                    // [b ASC]
946                    vec![(col_b, option_asc)],
947                    // [a ASC, b ASC, c ASC]
948                    vec![
949                        (col_a, option_asc),
950                        (col_b, option_asc),
951                        (col_c, option_asc),
952                    ],
953                    // [d ASC]
954                    vec![(col_d, option_asc)],
955                ],
956            ),
957        ];
958        for (orderings, expected) in test_cases {
959            let orderings = convert_to_orderings(&orderings);
960            let expected = convert_to_orderings(&expected);
961            let actual = OrderingEquivalenceClass::from(orderings.clone());
962            let err_msg = format!(
963                "orderings: {orderings:?}, expected: {expected:?}, actual :{actual:?}"
964            );
965            assert_eq!(actual.len(), expected.len(), "{err_msg}");
966            for elem in actual {
967                assert!(expected.contains(&elem), "{}", err_msg);
968            }
969        }
970
971        Ok(())
972    }
973
974    #[test]
975    fn test_is_expr_partial_const() -> Result<()> {
976        let schema = create_test_schema()?;
977        let col_a = &col("a", &schema)?;
978        let col_b = &col("b", &schema)?;
979        let [
980            asc_nulls_last,
981            asc_nulls_first,
982            desc_nulls_last,
983            desc_nulls_first,
984        ] = [(false, false), (false, true), (true, false), (true, true)].map(
985            |(descending, nulls_first)| SortOptions {
986                descending,
987                nulls_first,
988            },
989        );
990
991        // The leading sort expression of each ordering, and whether `a` has a
992        // single value according to them.
993        let test_cases = vec![
994            // A direction and its exact reverse:
995            (
996                vec![(col_a, asc_nulls_last), (col_a, desc_nulls_first)],
997                true,
998            ),
999            (
1000                vec![(col_a, asc_nulls_first), (col_a, desc_nulls_last)],
1001                true,
1002            ),
1003            // Nulls first both ways, e.g. `NULL, NULL, 5, 5`:
1004            (
1005                vec![(col_a, asc_nulls_first), (col_a, desc_nulls_first)],
1006                false,
1007            ),
1008            // Nulls last both ways, e.g. `5, 5, NULL, NULL`:
1009            (
1010                vec![(col_a, asc_nulls_last), (col_a, desc_nulls_last)],
1011                false,
1012            ),
1013            (vec![(col_a, asc_nulls_last)], false),
1014            // The reverse direction belongs to another expression:
1015            (
1016                vec![(col_a, asc_nulls_last), (col_b, desc_nulls_first)],
1017                false,
1018            ),
1019        ];
1020        for (leading, expected) in test_cases {
1021            let oeq_class = OrderingEquivalenceClass::new(leading.into_iter().map(
1022                |(expr, options)| [PhysicalSortExpr::new(Arc::clone(expr), options)],
1023            ));
1024            assert_eq!(
1025                oeq_class.is_expr_partial_const(col_a),
1026                expected,
1027                "{oeq_class}"
1028            );
1029        }
1030
1031        Ok(())
1032    }
1033}