datafusion_physical_expr/equivalence/properties/mod.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
5mod dependency; // Submodule containing DependencyMap and Dependencies
6mod joins; // Submodule containing join_equivalence_properties
7mod union; // Submodule containing calculate_union
8mod walk; // Submodule containing SortKeyWalk
9
10pub use joins::*;
11pub use union::*;
12
13use std::fmt::{self, Display};
14use std::mem;
15use std::sync::Arc;
16
17use self::dependency::{
18 Dependencies, DependencyMap, construct_prefix_orderings,
19 generate_dependency_orderings, referred_dependencies,
20};
21use self::walk::SortKeyWalk;
22use crate::equivalence::{
23 AcrossPartitions, EquivalenceGroup, OrderingEquivalenceClass, ProjectionMapping,
24};
25use crate::expressions::{Column, Literal, with_new_schema};
26use crate::{
27 ConstExpr, LexOrdering, LexRequirement, PhysicalExpr, PhysicalSortExpr,
28 PhysicalSortRequirement,
29};
30
31use arrow::compute::SortOptions;
32use arrow::datatypes::SchemaRef;
33use datafusion_common::{Constraint, Constraints, HashMap, Result, plan_err};
34use datafusion_expr::interval_arithmetic::Interval;
35use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
36
37use indexmap::IndexSet;
38use itertools::{Either, Itertools};
39
40/// `EquivalenceProperties` stores information about the output of a plan node
41/// that can be used to optimize the plan. Currently, it keeps track of:
42/// - Sort expressions (orderings),
43/// - Equivalent expressions; i.e. expressions known to have the same value.
44/// - Constants expressions; i.e. expressions known to contain a single constant
45/// value.
46///
47/// Please see the [Using Ordering for Better Plans] blog for more details.
48///
49/// [Using Ordering for Better Plans]: https://datafusion.apache.org/blog/2025/03/11/ordering-analysis/
50///
51/// # Example equivalent sort expressions
52///
53/// Consider table below:
54///
55/// ```text
56/// ┌-------┐
57/// | a | b |
58/// |---|---|
59/// | 1 | 9 |
60/// | 2 | 8 |
61/// | 3 | 7 |
62/// | 5 | 5 |
63/// └---┴---┘
64/// ```
65///
66/// In this case, both `a ASC` and `b DESC` can describe the table ordering.
67/// `EquivalenceProperties` tracks these different valid sort expressions and
68/// treat `a ASC` and `b DESC` on an equal footing. For example, if the query
69/// specifies the output sorted by EITHER `a ASC` or `b DESC`, the sort can be
70/// avoided.
71///
72/// # Example equivalent expressions
73///
74/// Similarly, consider the table below:
75///
76/// ```text
77/// ┌-------┐
78/// | a | b |
79/// |---|---|
80/// | 1 | 1 |
81/// | 2 | 2 |
82/// | 3 | 3 |
83/// | 5 | 5 |
84/// └---┴---┘
85/// ```
86///
87/// In this case, columns `a` and `b` always have the same value. With this
88/// information, Datafusion can optimize various operations. For example, if
89/// the partition requirement is `Hash(a)` and output partitioning is
90/// `Hash(b)`, then DataFusion avoids repartitioning the data as the existing
91/// partitioning satisfies the requirement.
92///
93/// # Code Example
94/// ```
95/// # use std::sync::Arc;
96/// # use arrow::datatypes::{Schema, Field, DataType, SchemaRef};
97/// # use datafusion_physical_expr::{ConstExpr, EquivalenceProperties};
98/// # use datafusion_physical_expr::expressions::col;
99/// use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
100/// # let schema: SchemaRef = Arc::new(Schema::new(vec![
101/// # Field::new("a", DataType::Int32, false),
102/// # Field::new("b", DataType::Int32, false),
103/// # Field::new("c", DataType::Int32, false),
104/// # ]));
105/// # let col_a = col("a", &schema).unwrap();
106/// # let col_b = col("b", &schema).unwrap();
107/// # let col_c = col("c", &schema).unwrap();
108/// // This object represents data that is sorted by a ASC, c DESC
109/// // with a single constant value of b
110/// let mut eq_properties = EquivalenceProperties::new(schema);
111/// eq_properties.add_constants(vec![ConstExpr::from(col_b)]);
112/// eq_properties.add_ordering([
113/// PhysicalSortExpr::new_default(col_a).asc(),
114/// PhysicalSortExpr::new_default(col_c).desc(),
115/// ]);
116///
117/// assert_eq!(
118/// eq_properties.to_string(),
119/// "order: [[a@0 ASC, c@2 DESC]], eq: [{members: [b@1], constant: (heterogeneous)}]"
120/// );
121/// ```
122#[derive(Clone, Debug)]
123pub struct EquivalenceProperties {
124 /// Distinct equivalence classes (i.e. expressions with the same value).
125 eq_group: EquivalenceGroup,
126 /// Equivalent sort expressions (i.e. those define the same ordering).
127 oeq_class: OrderingEquivalenceClass,
128 /// Cache storing equivalent sort expressions in normal form (i.e. without
129 /// constants/duplicates and in standard form) and a map associating leading
130 /// terms with full sort expressions.
131 oeq_cache: OrderingEquivalenceCache,
132 /// Table constraints that factor in equivalence calculations. Unlike
133 /// constants, constraints have no per-partition form: each one must hold
134 /// across all output partitions, since operators that merge partitions
135 /// keep them.
136 constraints: Constraints,
137 /// Schema associated with this object.
138 schema: SchemaRef,
139}
140
141/// This object serves as a cache for storing equivalent sort expressions
142/// in normal form, and a map associating leading sort expressions with
143/// full lexicographical orderings. With this information, DataFusion can
144/// efficiently determine whether a given ordering is satisfied by the
145/// existing orderings, and discover new orderings based on the existing
146/// equivalence properties.
147#[derive(Clone, Debug, Default)]
148struct OrderingEquivalenceCache {
149 /// Equivalent sort expressions in normal form.
150 normal_cls: OrderingEquivalenceClass,
151 /// Map associating leading sort expressions with full lexicographical
152 /// orderings. Values are indices into `normal_cls`.
153 leading_map: HashMap<Arc<dyn PhysicalExpr>, Vec<usize>>,
154}
155
156impl OrderingEquivalenceCache {
157 /// Creates a new `OrderingEquivalenceCache` object with the given
158 /// equivalent orderings, which should be in normal form.
159 pub fn new(
160 orderings: impl IntoIterator<Item = impl IntoIterator<Item = PhysicalSortExpr>>,
161 ) -> Self {
162 let normal_cls = OrderingEquivalenceClass::new(orderings);
163 let mut cache = Self {
164 leading_map: HashMap::with_capacity(normal_cls.len()),
165 normal_cls,
166 };
167 cache.update_map();
168 cache
169 }
170
171 /// Updates/reconstructs the leading expression map according to the normal
172 /// ordering equivalence class within.
173 pub fn update_map(&mut self) {
174 self.leading_map.clear();
175 for (idx, ordering) in self.normal_cls.iter().enumerate() {
176 let expr = Arc::clone(&ordering.first().expr);
177 self.leading_map.entry(expr).or_default().push(idx);
178 }
179 }
180
181 /// Clears the cache, removing all orderings and leading expressions.
182 pub fn clear(&mut self) {
183 self.normal_cls.clear();
184 self.leading_map.clear();
185 }
186}
187
188/// Counts how often [`EquivalenceProperties::project_reusing`] reused a cached
189/// equivalence group instead of reprojecting it.
190///
191/// Thread local rather than a global counter: the test binary runs tests in
192/// parallel, and a shared count would let one test observe another's hits.
193#[cfg(test)]
194mod eq_group_reuse_probe {
195 use std::cell::Cell;
196
197 thread_local! {
198 static HITS: Cell<usize> = const { Cell::new(0) };
199 }
200
201 pub(super) fn record_hit() {
202 HITS.with(|h| h.set(h.get() + 1));
203 }
204
205 /// Runs `f` and reports how many reuses happened while it did.
206 pub(super) fn count<T>(f: impl FnOnce() -> T) -> (T, usize) {
207 let before = HITS.with(Cell::get);
208 let value = f();
209 (value, HITS.with(Cell::get) - before)
210 }
211}
212
213impl EquivalenceProperties {
214 /// Helper used by the ordering equivalence rule when considering whether
215 /// an expression can replace an existing sort key without invalidating
216 /// the ordering.
217 ///
218 /// The substitution is only allowed when, treating the sort key as the
219 /// only ordered input, the expression reports the same ordering *and*
220 /// that it is a one-to-one, order-preserving function of it (see
221 /// [`ExprProperties::strictly_order_preserving`]). For example, a
222 /// widening `CAST` of the sort key qualifies, while a narrowing one does
223 /// not, as it could collapse distinct values and violate the existing
224 /// sort order.
225 fn substitute_order_preserving_ordering(
226 r_expr: Arc<dyn PhysicalExpr>,
227 sort_expr: &PhysicalSortExpr,
228 schema: &SchemaRef,
229 column_ranges: &ColumnRanges,
230 ) -> Option<PhysicalSortExpr> {
231 if r_expr.eq(&sort_expr.expr) {
232 // No point in substituting an expression with itself.
233 return None;
234 }
235 let dependencies = Dependencies::new(std::iter::once(sort_expr.clone()));
236 let properties =
237 get_expr_properties(&r_expr, &dependencies, schema, column_ranges).ok()?;
238 (properties.strictly_order_preserving
239 && properties.sort_properties == SortProperties::Ordered(sort_expr.options))
240 .then(|| PhysicalSortExpr::new(r_expr, sort_expr.options))
241 }
242
243 /// Creates an empty `EquivalenceProperties` object.
244 pub fn new(schema: SchemaRef) -> Self {
245 Self {
246 eq_group: EquivalenceGroup::default(),
247 oeq_class: OrderingEquivalenceClass::default(),
248 oeq_cache: OrderingEquivalenceCache::default(),
249 constraints: Constraints::default(),
250 schema,
251 }
252 }
253
254 /// Adds constraints to the properties.
255 pub fn set_constraints(&mut self, constraints: Constraints) {
256 self.constraints = constraints;
257 }
258
259 /// Adds constraints to the properties.
260 pub fn with_constraints(mut self, constraints: Constraints) -> Self {
261 self.set_constraints(constraints);
262 self
263 }
264
265 /// Creates a new `EquivalenceProperties` object with the given orderings.
266 pub fn new_with_orderings(
267 schema: SchemaRef,
268 orderings: impl IntoIterator<Item = impl IntoIterator<Item = PhysicalSortExpr>>,
269 ) -> Self {
270 let eq_group = EquivalenceGroup::default();
271 let oeq_class = OrderingEquivalenceClass::new(orderings);
272 // Here, we can avoid performing a full normalization, and get by with
273 // only removing constants because the equivalence group is empty.
274 let normal_orderings = oeq_class.iter().cloned().map(|o| {
275 o.into_iter()
276 .filter(|sort_expr| eq_group.is_expr_constant(&sort_expr.expr).is_none())
277 });
278 Self {
279 oeq_cache: OrderingEquivalenceCache::new(normal_orderings),
280 oeq_class,
281 eq_group,
282 constraints: Constraints::default(),
283 schema,
284 }
285 }
286
287 /// Returns the associated schema.
288 pub fn schema(&self) -> &SchemaRef {
289 &self.schema
290 }
291
292 /// Returns a reference to the ordering equivalence class within.
293 pub fn oeq_class(&self) -> &OrderingEquivalenceClass {
294 &self.oeq_class
295 }
296
297 /// Returns a reference to the equivalence group within.
298 pub fn eq_group(&self) -> &EquivalenceGroup {
299 &self.eq_group
300 }
301
302 /// Returns a reference to the constraints within.
303 pub fn constraints(&self) -> &Constraints {
304 &self.constraints
305 }
306
307 /// Returns all the known constants expressions.
308 pub fn constants(&self) -> Vec<ConstExpr> {
309 self.eq_group
310 .iter()
311 .flat_map(|c| {
312 c.iter().filter_map(|expr| {
313 c.constant
314 .as_ref()
315 .map(|across| ConstExpr::new(Arc::clone(expr), across.clone()))
316 })
317 })
318 .collect()
319 }
320
321 /// Returns the output ordering of the properties.
322 pub fn output_ordering(&self) -> Option<LexOrdering> {
323 let concat = self.oeq_class.iter().flat_map(|o| o.iter().cloned());
324 self.normalize_sort_exprs(concat)
325 }
326
327 /// Extends this `EquivalenceProperties` with the `other` object.
328 pub fn extend(mut self, other: Self) -> Result<Self> {
329 self.constraints.extend(other.constraints);
330 self.add_equivalence_group(other.eq_group)?;
331 self.add_orderings(other.oeq_class);
332 Ok(self)
333 }
334
335 /// Clears (empties) the ordering equivalence class within this object.
336 /// Call this method when existing orderings are invalidated.
337 pub fn clear_orderings(&mut self) {
338 self.oeq_class.clear();
339 self.oeq_cache.clear();
340 }
341
342 /// Removes constant expressions that may change across partitions.
343 /// This method should be used when merging data from different partitions.
344 pub fn clear_per_partition_constants(&mut self) {
345 if self.eq_group.clear_per_partition_constants() {
346 // Renormalize orderings if the equivalence group changes:
347 let normal_orderings = self
348 .oeq_class
349 .iter()
350 .cloned()
351 .map(|o| self.eq_group.normalize_sort_exprs(o));
352 self.oeq_cache = OrderingEquivalenceCache::new(normal_orderings);
353 }
354 }
355
356 /// Adds new orderings into the existing ordering equivalence class, along
357 /// with the orderings they imply through known equalities.
358 pub fn add_orderings(
359 &mut self,
360 orderings: impl IntoIterator<Item = impl IntoIterator<Item = PhysicalSortExpr>>,
361 ) {
362 let orderings: Vec<_> =
363 orderings.into_iter().filter_map(LexOrdering::new).collect();
364 let normal_orderings: Vec<_> = orderings
365 .iter()
366 .cloned()
367 .filter_map(|o| self.normalize_sort_exprs(o))
368 .collect();
369 if normal_orderings.is_empty() {
370 return;
371 }
372 // `add_constants` and `add_equal_conditions` discover implied orderings
373 // too, and whether an ordering is satisfied must not depend on which of
374 // them ran last. Deriving one fails only on an expression that does not
375 // match the schema; that ordering is then not implied, which can cost a
376 // sort but not a wrong result.
377 let mut implied: Vec<LexOrdering> = vec![];
378 for ordering in &normal_orderings {
379 // Two orderings can imply the same one; expand it only once:
380 for ordering in self.implied_by(ordering).unwrap_or_default() {
381 if !implied.contains(&ordering) {
382 implied.push(ordering);
383 }
384 }
385 }
386 self.oeq_class.extend(orderings);
387 // Normalize given orderings to update the cache:
388 self.oeq_cache.normal_cls.extend(normal_orderings);
389 // TODO: If no ordering is found to be redundant during extension, we
390 // can use a shortcut algorithm to update the leading map.
391 self.oeq_cache.update_map();
392 // Each implied ordering is shorter than the one implying it, so this
393 // terminates:
394 self.add_orderings(implied);
395 }
396
397 /// Adds a single ordering to the existing ordering equivalence class.
398 pub fn add_ordering(&mut self, ordering: impl IntoIterator<Item = PhysicalSortExpr>) {
399 self.add_orderings(std::iter::once(ordering));
400 }
401
402 fn update_oeq_cache(&mut self) -> Result<()> {
403 // Renormalize orderings if the equivalence group changes:
404 let normal_cls = mem::take(&mut self.oeq_cache.normal_cls);
405 let normal_orderings = normal_cls
406 .into_iter()
407 .map(|o| self.eq_group.normalize_sort_exprs(o));
408 self.oeq_cache.normal_cls = OrderingEquivalenceClass::new(normal_orderings);
409 self.oeq_cache.update_map();
410 // Discover any new orderings based on the new equivalence classes:
411 let leading_exprs: Vec<_> = self.oeq_cache.leading_map.keys().cloned().collect();
412 for expr in leading_exprs {
413 self.discover_new_orderings(&expr)?;
414 }
415 Ok(())
416 }
417
418 /// Incorporates the given equivalence group to into the existing
419 /// equivalence group within.
420 pub fn add_equivalence_group(
421 &mut self,
422 other_eq_group: EquivalenceGroup,
423 ) -> Result<()> {
424 if !other_eq_group.is_empty() {
425 self.eq_group.extend(other_eq_group);
426 self.update_oeq_cache()?;
427 }
428 Ok(())
429 }
430
431 /// Returns the ordering equivalence class within in normal form.
432 /// Normalization standardizes expressions according to the equivalence
433 /// group within, and removes constants/duplicates.
434 pub fn normalized_oeq_class(&self) -> OrderingEquivalenceClass {
435 self.oeq_class
436 .iter()
437 .cloned()
438 .filter_map(|ordering| self.normalize_sort_exprs(ordering))
439 .collect::<Vec<_>>()
440 .into()
441 }
442
443 /// Adds a new equality condition into the existing equivalence group.
444 /// If the given equality defines a new equivalence class, adds this new
445 /// equivalence class to the equivalence group.
446 pub fn add_equal_conditions(
447 &mut self,
448 left: Arc<dyn PhysicalExpr>,
449 right: Arc<dyn PhysicalExpr>,
450 ) -> Result<()> {
451 // Add equal expressions to the state:
452 if self.eq_group.add_equal_conditions(left, right) {
453 self.update_oeq_cache()?;
454 }
455 self.update_oeq_cache()?;
456 Ok(())
457 }
458
459 /// Track/register physical expressions with constant values.
460 pub fn add_constants(
461 &mut self,
462 constants: impl IntoIterator<Item = ConstExpr>,
463 ) -> Result<()> {
464 // Add the new constant to the equivalence group:
465 for constant in constants {
466 self.eq_group.add_constant(constant);
467 }
468 // Renormalize the orderings after adding new constants by removing
469 // the constants from existing orderings:
470 let normal_cls = mem::take(&mut self.oeq_cache.normal_cls);
471 let normal_orderings = normal_cls.into_iter().map(|ordering| {
472 ordering.into_iter().filter(|sort_expr| {
473 self.eq_group.is_expr_constant(&sort_expr.expr).is_none()
474 })
475 });
476 self.oeq_cache.normal_cls = OrderingEquivalenceClass::new(normal_orderings);
477 self.oeq_cache.update_map();
478 // Discover any new orderings based on the constants:
479 let leading_exprs: Vec<_> = self.oeq_cache.leading_map.keys().cloned().collect();
480 for expr in leading_exprs {
481 self.discover_new_orderings(&expr)?;
482 }
483 Ok(())
484 }
485
486 /// Discover new valid orderings in light of a new equality. Accepts a single
487 /// argument (`normal_expr`) which is used to determine the orderings to update.
488 /// When constants or equivalence classes change, there may be new orderings
489 /// that can be discovered with the new equivalence properties.
490 /// For a discussion, see: <https://github.com/apache/datafusion/issues/9812>
491 fn discover_new_orderings(
492 &mut self,
493 normal_expr: &Arc<dyn PhysicalExpr>,
494 ) -> Result<()> {
495 let Some(ordering_idxs) = self.oeq_cache.leading_map.get(normal_expr) else {
496 return Ok(());
497 };
498 let mut new_orderings = vec![];
499 for idx in ordering_idxs {
500 let ordering = &self.oeq_cache.normal_cls[*idx];
501 // As in `add_orderings`, an ordering that cannot be derived is
502 // not implied, so the result does not depend on the call order:
503 new_orderings.extend(self.implied_by(ordering).unwrap_or_default());
504 }
505 self.add_orderings(new_orderings);
506 Ok(())
507 }
508
509 /// Returns the orderings that the normal ordering `ordering` implies
510 /// through known equalities: for each key that is a function of the keys
511 /// after it (see [`Self::implied_ordering`]), `ordering` without that key.
512 ///
513 /// # Example: a key that is a function of the keys after it
514 ///
515 /// * Ordering: `[k ASC, a ASC, c ASC]`
516 /// * Equality: `a = CAST(c AS DATE)`
517 /// * Returns: `[k ASC, c ASC]`
518 ///
519 /// Among the rows that tie on `k`, the rows are sorted by `a`, and the
520 /// rows that also tie on `a` are sorted by `c`. `a` is the date of `c`, so
521 /// a row with an earlier `a` also has an earlier `c`, and the rows that
522 /// tie on `k` are sorted by `c` alone:
523 ///
524 /// ```text
525 /// ┌───┬────────────┬──────────────────┐
526 /// │ k │ a │ c │
527 /// ├───┼────────────┼──────────────────┤
528 /// │ x │ 2026-01-01 │ 2026-01-01 09:00 │
529 /// │ x │ 2026-01-02 │ 2026-01-02 01:00 │
530 /// │ x │ 2026-01-02 │ 2026-01-02 05:00 │
531 /// │ y │ 2026-01-01 │ 2026-01-01 03:00 │
532 /// └───┴────────────┴──────────────────┘
533 /// ```
534 ///
535 /// # Example: a constant that differs between partitions
536 ///
537 /// * Ordering: `[k ASC, a ASC, c ASC]`, where `k` is a constant whose value
538 /// differs between partitions
539 /// * Equality: `a = CAST(c AS DATE)`
540 /// * Returns: `[c ASC]`
541 ///
542 /// A normal ordering can keep such a constant (see
543 /// `EquivalenceGroup::normalize_sort_exprs`). Within a partition `k` has
544 /// one value, so it is left out of the keys and of the result.
545 ///
546 /// # Example: directions that differ
547 ///
548 /// * Ordering: `[a ASC, c DESC]`
549 /// * Equality: `a = CAST(c AS DATE)`
550 /// * Returns: nothing
551 ///
552 /// `c` descends within a date but ascends across dates, so the rows are
553 /// not sorted by `c` in either direction.
554 fn implied_by(&self, ordering: &LexOrdering) -> Result<Vec<LexOrdering>> {
555 let keys: Vec<_> = ordering
556 .iter()
557 .filter(|sort_expr| self.eq_group.is_expr_constant(&sort_expr.expr).is_none())
558 .collect();
559 let mut implied = vec![];
560 for (idx, key) in keys.iter().enumerate() {
561 if let Some(rest) =
562 self.implied_ordering(key, keys[idx + 1..].iter().copied())?
563 {
564 let prefix = keys[..idx].iter().copied().cloned();
565 implied.extend(LexOrdering::new(prefix.chain(rest)));
566 }
567 }
568 Ok(implied)
569 }
570
571 /// Returns the ordering that the normal ordering `[leading, rest..]`
572 /// implies through an equality on its leading expression, if any.
573 ///
574 /// If data is sorted by `[c, a, b]` and `c = f(a, b)` for a function `f`
575 /// that preserves the lexicographical order of its arguments, the data is
576 /// also sorted by `[a, b]`: rows with different `(a, b)` are in the order
577 /// of `f(a, b)`, which is the order of `c`, and rows with equal `c` are
578 /// sorted by `[a, b]` anyway. Whatever follows `b` stays sorted as well, so
579 /// the implied ordering is all of `rest`.
580 fn implied_ordering<'b>(
581 &self,
582 leading: &PhysicalSortExpr,
583 rest: impl Iterator<Item = &'b PhysicalSortExpr> + Clone,
584 ) -> Result<Option<Vec<PhysicalSortExpr>>> {
585 // The expressions equal to `leading`; any of them can play `f(a, b)`:
586 let members = match self.eq_group.get_equivalence_class(&leading.expr) {
587 Some(class) => Either::Left(class.iter()),
588 None => Either::Right(std::iter::once(&leading.expr)),
589 };
590 for member in members {
591 let args = member.children();
592 // An expression without arguments, such as a column, implies
593 // nothing:
594 if args.is_empty() {
595 continue;
596 }
597 // The arguments must be the next expressions of the ordering, in
598 // order, and are then sorted the way the ordering says:
599 let mut sorted = rest.clone();
600 let mut arg_properties = vec![];
601 for arg in args {
602 match sorted.next() {
603 Some(sort_expr) if sort_expr.expr.eq(arg) => {
604 let data_type = arg.data_type(&self.schema)?;
605 arg_properties.push(ExprProperties {
606 sort_properties: SortProperties::Ordered(sort_expr.options),
607 range: Interval::make_unbounded(&data_type)?,
608 preserves_lex_ordering: true,
609 strictly_order_preserving: true,
610 });
611 }
612 // This ends the whole search: members after this one are
613 // not tried, even if their arguments would match.
614 _ => return Ok(None),
615 }
616 }
617 // `member` must preserve the lexicographical order of its
618 // arguments, in the direction of `leading`. If that cannot be
619 // derived, this member implies nothing:
620 let Ok(properties) = member.get_properties(&arg_properties) else {
621 continue;
622 };
623 if properties.preserves_lex_ordering
624 && properties.sort_properties == SortProperties::Ordered(leading.options)
625 {
626 return Ok(Some(rest.cloned().collect()));
627 }
628 }
629 Ok(None)
630 }
631
632 /// Updates the ordering equivalence class within assuming that the table
633 /// is re-sorted according to the argument `ordering`, and returns whether
634 /// this operation resulted in any change. Note that equivalence classes
635 /// (and constants) do not change as they are unaffected by a re-sort. If
636 /// the given ordering is already satisfied, the function does nothing.
637 pub fn reorder(
638 &mut self,
639 ordering: impl IntoIterator<Item = PhysicalSortExpr>,
640 ) -> Result<bool> {
641 let (ordering, ordering_tee) = ordering.into_iter().tee();
642 // First, standardize the given ordering:
643 let Some(normal_ordering) = self.normalize_sort_exprs(ordering) else {
644 // If the ordering vanishes after normalization, it is satisfied:
645 return Ok(false);
646 };
647 if normal_ordering.len() != self.common_sort_prefix_length(&normal_ordering)? {
648 // If the ordering is unsatisfied, replace existing orderings:
649 self.clear_orderings();
650 self.add_ordering(ordering_tee);
651 return Ok(true);
652 }
653 Ok(false)
654 }
655
656 /// Normalizes the given sort expressions (i.e. `sort_exprs`) using the
657 /// equivalence group within. Returns a `LexOrdering` instance if the
658 /// expressions define a proper lexicographical ordering. For more details,
659 /// see [`EquivalenceGroup::normalize_sort_exprs`].
660 pub fn normalize_sort_exprs(
661 &self,
662 sort_exprs: impl IntoIterator<Item = PhysicalSortExpr>,
663 ) -> Option<LexOrdering> {
664 LexOrdering::new(self.eq_group.normalize_sort_exprs(sort_exprs))
665 }
666
667 /// Normalizes the given sort requirements (i.e. `sort_reqs`) using the
668 /// equivalence group within. Returns a `LexRequirement` instance if the
669 /// expressions define a proper lexicographical requirement. For more
670 /// details, see [`EquivalenceGroup::normalize_sort_exprs`].
671 pub fn normalize_sort_requirements(
672 &self,
673 sort_reqs: impl IntoIterator<Item = PhysicalSortRequirement>,
674 ) -> Option<LexRequirement> {
675 LexRequirement::new(self.eq_group.normalize_sort_requirements(sort_reqs))
676 }
677
678 /// Iteratively checks whether the given ordering is satisfied by any of
679 /// the existing orderings. See [`Self::ordering_satisfy_requirement`] for
680 /// more details and examples.
681 pub fn ordering_satisfy(
682 &self,
683 given: impl IntoIterator<Item = PhysicalSortExpr>,
684 ) -> Result<bool> {
685 // First, standardize the given ordering:
686 let Some(normal_ordering) = self.normalize_sort_exprs(given) else {
687 // If the ordering vanishes after normalization, it is satisfied:
688 return Ok(true);
689 };
690 Ok(normal_ordering.len() == self.common_sort_prefix_length(&normal_ordering)?)
691 }
692
693 /// Iteratively checks whether the given sort requirement is satisfied by
694 /// any of the existing orderings.
695 ///
696 /// ### Example Scenarios
697 ///
698 /// In these scenarios, assume that all expressions share the same sort
699 /// properties.
700 ///
701 /// #### Case 1: Sort Requirement `[a, c]`
702 ///
703 /// **Existing orderings:** `[[a, b, c], [a, d]]`, **constants:** `[]`
704 /// 1. The function first checks the leading requirement `a`, which is
705 /// satisfied by `[a, b, c].first()`.
706 /// 2. `a` is pinned: the next key only has to be sorted among rows that
707 /// tie on `a`.
708 /// 3. The orderings now start at `[b, c]` and `[d]`.
709 /// 4. The function fails for `c` in the second iteration, as neither
710 /// `[b, c]` nor `[d]` satisfies `c`.
711 ///
712 /// #### Case 2: Sort Requirement `[a, d]`
713 ///
714 /// **Existing orderings:** `[[a, b, c], [a, d]]`, **constants:** `[]`
715 /// 1. The function first checks the leading requirement `a`, which is
716 /// satisfied by `[a, b, c].first()`.
717 /// 2. `a` is pinned: the next key only has to be sorted among rows that
718 /// tie on `a`.
719 /// 3. The orderings now start at `[b, c]` and `[d]`.
720 /// 4. The function returns `true` as `[d]` satisfies `d`.
721 pub fn ordering_satisfy_requirement(
722 &self,
723 given: impl IntoIterator<Item = PhysicalSortRequirement>,
724 ) -> Result<bool> {
725 // First, standardize the given requirement:
726 let Some(normal_reqs) = self.normalize_sort_requirements(given) else {
727 // If the requirement vanishes after normalization, it is satisfied:
728 return Ok(true);
729 };
730 // Then, check whether given requirement is satisfied by constraints:
731 if self.satisfied_by_constraints(&normal_reqs) {
732 return Ok(true);
733 }
734 let keys = normal_reqs.iter().map(|req| (&req.expr, req.options));
735 Ok(SortKeyWalk::new(self).sorted_prefix_len(keys)? == normal_reqs.len())
736 }
737
738 /// Returns the number of consecutive sort expressions (starting from the
739 /// left) that are satisfied by the existing ordering.
740 fn common_sort_prefix_length(&self, normal_ordering: &LexOrdering) -> Result<usize> {
741 let full_length = normal_ordering.len();
742 // Check whether the given ordering is satisfied by constraints:
743 if self.satisfied_by_constraints_ordering(normal_ordering) {
744 // If constraints satisfy all sort expressions, return the full
745 // length:
746 return Ok(full_length);
747 }
748 let keys = normal_ordering
749 .iter()
750 .map(|sort_expr| (&sort_expr.expr, Some(sort_expr.options)));
751 SortKeyWalk::new(self).sorted_prefix_len(keys)
752 }
753
754 /// Determines the longest normal prefix of `ordering` satisfied by the
755 /// existing ordering. Returns that prefix as a new `LexOrdering`, and a
756 /// boolean indicating whether all the sort expressions are satisfied.
757 pub fn extract_common_sort_prefix(
758 &self,
759 ordering: LexOrdering,
760 ) -> Result<(Vec<PhysicalSortExpr>, bool)> {
761 // First, standardize the given ordering:
762 let Some(normal_ordering) = self.normalize_sort_exprs(ordering) else {
763 // If the ordering vanishes after normalization, it is satisfied:
764 return Ok((vec![], true));
765 };
766 let prefix_len = self.common_sort_prefix_length(&normal_ordering)?;
767 let flag = prefix_len == normal_ordering.len();
768 let mut sort_exprs: Vec<_> = normal_ordering.into();
769 if !flag {
770 sort_exprs.truncate(prefix_len);
771 }
772 Ok((sort_exprs, flag))
773 }
774
775 /// Checks if the sort expressions are satisfied by any of the table
776 /// constraints (primary key or unique). Returns true if any constraint
777 /// fully satisfies the expressions (i.e. constraint indices form a valid
778 /// prefix of an existing ordering that matches the expressions). For
779 /// unique constraints, also verifies nullable columns.
780 fn satisfied_by_constraints_ordering(
781 &self,
782 normal_exprs: &[PhysicalSortExpr],
783 ) -> bool {
784 self.constraints.iter().any(|constraint| match constraint {
785 Constraint::PrimaryKey(indices) | Constraint::Unique(indices) => {
786 let check_null = matches!(constraint, Constraint::Unique(_));
787 let normalized_size = normal_exprs.len();
788 indices.len() <= normalized_size
789 && self.oeq_class.iter().any(|ordering| {
790 let length = ordering.len();
791 if indices.len() > length || normalized_size < length {
792 return false;
793 }
794 // Build a map of column positions in the ordering:
795 let mut col_positions = HashMap::with_capacity(length);
796 for (pos, req) in ordering.iter().enumerate() {
797 if let Some(col) = req.expr.downcast_ref::<Column>() {
798 let nullable = col.nullable(&self.schema).unwrap_or(true);
799 col_positions.insert(col.index(), (pos, nullable));
800 }
801 }
802 // Check if all constraint indices appear in valid positions:
803 if !indices.iter().all(|idx| {
804 col_positions.get(idx).is_some_and(|&(pos, nullable)| {
805 // For unique constraints, verify column is not nullable if it's first/last:
806 !check_null
807 || !nullable
808 || (pos != 0 && pos != length - 1)
809 })
810 }) {
811 return false;
812 }
813 // Check if this ordering matches the prefix:
814 normal_exprs.iter().zip(ordering).all(|(given, existing)| {
815 existing.satisfy_expr(given, &self.schema)
816 })
817 })
818 }
819 })
820 }
821
822 /// Checks if the sort requirements are satisfied by any of the table
823 /// constraints (primary key or unique). Returns true if any constraint
824 /// fully satisfies the requirements (i.e. constraint indices form a valid
825 /// prefix of an existing ordering that matches the requirements). For
826 /// unique constraints, also verifies nullable columns.
827 fn satisfied_by_constraints(&self, normal_reqs: &[PhysicalSortRequirement]) -> bool {
828 self.constraints.iter().any(|constraint| match constraint {
829 Constraint::PrimaryKey(indices) | Constraint::Unique(indices) => {
830 let check_null = matches!(constraint, Constraint::Unique(_));
831 let normalized_size = normal_reqs.len();
832 indices.len() <= normalized_size
833 && self.oeq_class.iter().any(|ordering| {
834 let length = ordering.len();
835 if indices.len() > length || normalized_size < length {
836 return false;
837 }
838 // Build a map of column positions in the ordering:
839 let mut col_positions = HashMap::with_capacity(length);
840 for (pos, req) in ordering.iter().enumerate() {
841 if let Some(col) = req.expr.downcast_ref::<Column>() {
842 let nullable = col.nullable(&self.schema).unwrap_or(true);
843 col_positions.insert(col.index(), (pos, nullable));
844 }
845 }
846 // Check if all constraint indices appear in valid positions:
847 if !indices.iter().all(|idx| {
848 col_positions.get(idx).is_some_and(|&(pos, nullable)| {
849 // For unique constraints, verify column is not nullable if it's first/last:
850 !check_null
851 || !nullable
852 || (pos != 0 && pos != length - 1)
853 })
854 }) {
855 return false;
856 }
857 // Check if this ordering matches the prefix:
858 normal_reqs.iter().zip(ordering).all(|(given, existing)| {
859 existing.satisfy(given, &self.schema)
860 })
861 })
862 }
863 })
864 }
865
866 /// Checks whether the `given` sort requirements are equal or more specific
867 /// than the `reference` sort requirements.
868 pub fn requirements_compatible(
869 &self,
870 given: LexRequirement,
871 reference: LexRequirement,
872 ) -> bool {
873 let Some(normal_given) = self.normalize_sort_requirements(given) else {
874 return true;
875 };
876 let Some(normal_reference) = self.normalize_sort_requirements(reference) else {
877 return true;
878 };
879
880 (normal_reference.len() <= normal_given.len())
881 && normal_reference
882 .into_iter()
883 .zip(normal_given)
884 .all(|(reference, given)| given.compatible(&reference))
885 }
886
887 /// Modify existing orderings by substituting sort expressions with appropriate
888 /// targets from the projection mapping. We substitute a sort expression when
889 /// its physical expression has a one-to-one functional relationship with a
890 /// target expression in the mapping.
891 ///
892 /// After substitution, we may generate more than one `LexOrdering` for each
893 /// existing equivalent ordering. For example, `[a ASC, b ASC]` will turn
894 /// into `[CAST(a) ASC, b ASC]` and `[a ASC, b ASC]` when applying projection
895 /// expressions `a, b, CAST(a)`.
896 ///
897 /// TODO: Handle all scenarios that allow substitution; e.g. when `x` is
898 /// sorted, `atan(x + 1000)` should also be substituted. For now, we
899 /// consider widening `CAST` expressions and single-child expressions
900 /// that declare themselves one-to-one order-preserving via
901 /// [`ExprProperties::strictly_order_preserving`].
902 fn substitute_oeq_class(
903 schema: &SchemaRef,
904 mapping: &ProjectionMapping,
905 oeq_class: OrderingEquivalenceClass,
906 column_ranges: &ColumnRanges,
907 ) -> OrderingEquivalenceClass {
908 let new_orderings = oeq_class.into_iter().flat_map(|order| {
909 // Modify/expand existing orderings by substituting sort
910 // expressions with appropriate targets from the mapping:
911 order
912 .into_iter()
913 .map(|sort_expr| {
914 let original_sort_expr = sort_expr.clone();
915 mapping
916 .iter()
917 .map(|(source, _target)| source)
918 .filter(|source| expr_refers(source, &original_sort_expr.expr))
919 .cloned()
920 .filter_map(|r_expr| {
921 Self::substitute_order_preserving_ordering(
922 r_expr,
923 &original_sort_expr,
924 schema,
925 column_ranges,
926 )
927 })
928 .chain(std::iter::once(sort_expr))
929 .collect::<Vec<_>>()
930 })
931 // Generate all valid orderings given substituted expressions:
932 .multi_cartesian_product()
933 });
934 OrderingEquivalenceClass::new(new_orderings)
935 }
936
937 /// Projects argument `expr` according to the projection described by
938 /// `mapping`, taking equivalences into account.
939 ///
940 /// For example, assume that columns `a` and `c` are always equal, and that
941 /// the projection described by `mapping` encodes the following:
942 ///
943 /// ```text
944 /// a -> a1
945 /// b -> b1
946 /// ```
947 ///
948 /// Then, this function projects `a + b` to `Some(a1 + b1)`, `c + b` to
949 /// `Some(a1 + b1)` and `d` to `None`, meaning that it is not projectable.
950 pub fn project_expr(
951 &self,
952 expr: &Arc<dyn PhysicalExpr>,
953 mapping: &ProjectionMapping,
954 ) -> Option<Arc<dyn PhysicalExpr>> {
955 self.eq_group.project_expr(mapping, expr)
956 }
957
958 /// Projects the given `expressions` according to the projection described
959 /// by `mapping`, taking equivalences into account. This function is similar
960 /// to [`Self::project_expr`], but projects multiple expressions at once
961 /// more efficiently than calling `project_expr` for each expression.
962 pub fn project_expressions<'a>(
963 &'a self,
964 expressions: impl IntoIterator<Item = &'a Arc<dyn PhysicalExpr>> + 'a,
965 mapping: &'a ProjectionMapping,
966 ) -> impl Iterator<Item = Option<Arc<dyn PhysicalExpr>>> + 'a {
967 self.eq_group.project_expressions(mapping, expressions)
968 }
969
970 /// Constructs a dependency map based on existing orderings referred to in
971 /// the projection.
972 ///
973 /// This function analyzes the orderings in the normalized order-equivalence
974 /// class and builds a dependency map. The dependency map captures relationships
975 /// between expressions within the orderings, helping to identify dependencies
976 /// and construct valid projected orderings during projection operations.
977 ///
978 /// # Parameters
979 ///
980 /// - `mapping`: A reference to the `ProjectionMapping` that defines the
981 /// relationship between source and target expressions.
982 ///
983 /// # Returns
984 ///
985 /// A [`DependencyMap`] representing the dependency map, where each
986 /// \[`DependencyNode`\] contains dependencies for the key [`PhysicalSortExpr`].
987 ///
988 /// # Example
989 ///
990 /// Assume we have two equivalent orderings: `[a ASC, b ASC]` and `[a ASC, c ASC]`,
991 /// and the projection mapping is `[a -> a_new, b -> b_new, b + c -> b + c]`.
992 /// Then, the dependency map will be:
993 ///
994 /// ```text
995 /// a ASC: Node {Some(a_new ASC), HashSet{}}
996 /// b ASC: Node {Some(b_new ASC), HashSet{a ASC}}
997 /// c ASC: Node {None, HashSet{a ASC}}
998 /// ```
999 fn construct_dependency_map(
1000 &self,
1001 oeq_class: OrderingEquivalenceClass,
1002 mapping: &ProjectionMapping,
1003 ) -> DependencyMap {
1004 let mut map = DependencyMap::default();
1005 for ordering in oeq_class.into_iter() {
1006 // Previous expression is a dependency. Note that there is no
1007 // dependency for the leading expression.
1008 if !self.insert_to_dependency_map(
1009 mapping,
1010 ordering[0].clone(),
1011 None,
1012 &mut map,
1013 ) {
1014 continue;
1015 }
1016 for (dependency, sort_expr) in ordering.into_iter().tuple_windows() {
1017 if !self.insert_to_dependency_map(
1018 mapping,
1019 sort_expr,
1020 Some(dependency),
1021 &mut map,
1022 ) {
1023 // If we can't project, stop constructing the dependency map
1024 // as remaining dependencies will be invalid post projection.
1025 break;
1026 }
1027 }
1028 }
1029 map
1030 }
1031
1032 /// Projects the sort expression according to the projection mapping and
1033 /// inserts it into the dependency map with the given dependency. Returns
1034 /// a boolean flag indicating whether the given expression is projectable.
1035 fn insert_to_dependency_map(
1036 &self,
1037 mapping: &ProjectionMapping,
1038 sort_expr: PhysicalSortExpr,
1039 dependency: Option<PhysicalSortExpr>,
1040 map: &mut DependencyMap,
1041 ) -> bool {
1042 let target_sort_expr = self
1043 .project_expr(&sort_expr.expr, mapping)
1044 .map(|expr| PhysicalSortExpr::new(expr, sort_expr.options));
1045 let projectable = target_sort_expr.is_some();
1046 if projectable
1047 || mapping
1048 .iter()
1049 .any(|(source, _)| expr_refers(source, &sort_expr.expr))
1050 {
1051 // Add sort expressions that can be projected or referred to
1052 // by any of the projection expressions to the dependency map:
1053 map.insert(sort_expr, target_sort_expr, dependency);
1054 }
1055 projectable
1056 }
1057
1058 /// Returns a new `ProjectionMapping` where source expressions are in normal
1059 /// form. Normalization ensures that source expressions are transformed into
1060 /// a consistent representation, which is beneficial for algorithms that rely
1061 /// on exact equalities, as it allows for more precise and reliable comparisons.
1062 ///
1063 /// # Parameters
1064 ///
1065 /// - `mapping`: A reference to the original `ProjectionMapping` to normalize.
1066 ///
1067 /// # Returns
1068 ///
1069 /// A new `ProjectionMapping` with source expressions in normal form.
1070 fn normalize_mapping(&self, mapping: &ProjectionMapping) -> ProjectionMapping {
1071 mapping
1072 .iter()
1073 .map(|(source, target)| {
1074 let normal_source = self.eq_group.normalize_expr(Arc::clone(source));
1075 (normal_source, target.clone())
1076 })
1077 .collect()
1078 }
1079
1080 /// Computes projected orderings based on a given projection mapping.
1081 ///
1082 /// This function takes a `ProjectionMapping` and computes the possible
1083 /// orderings for the projected expressions. It considers dependencies
1084 /// between expressions and generates valid orderings according to the
1085 /// specified sort properties.
1086 ///
1087 /// # Parameters
1088 ///
1089 /// - `mapping`: A reference to the `ProjectionMapping` that defines the
1090 /// relationship between source and target expressions.
1091 /// - `oeq_class`: The `OrderingEquivalenceClass` containing the orderings
1092 /// to project.
1093 ///
1094 /// # Returns
1095 ///
1096 /// A vector of all valid (but not in normal form) orderings after projection.
1097 fn projected_orderings(
1098 &self,
1099 mapping: &ProjectionMapping,
1100 mut oeq_class: OrderingEquivalenceClass,
1101 ) -> Vec<LexOrdering> {
1102 // Normalize source expressions in the mapping:
1103 let mapping = self.normalize_mapping(mapping);
1104 // Substitution examines every source that refers to an ordered column, and building the
1105 // orderings examines every source, even one that refers to no ordered column (it then
1106 // gets an empty set of dependencies). Sharing one cache across both steps builds the
1107 // unbounded range of a wide column referenced by many sources only once.
1108 let column_ranges = ColumnRanges::default();
1109 oeq_class =
1110 Self::substitute_oeq_class(&self.schema, &mapping, oeq_class, &column_ranges);
1111 // Get dependency map for existing orderings:
1112 let dependency_map = self.construct_dependency_map(oeq_class, &mapping);
1113 let orderings = mapping.iter().flat_map(|(source, targets)| {
1114 referred_dependencies(&dependency_map, source)
1115 .into_iter()
1116 .filter_map(|deps| {
1117 let ep =
1118 get_expr_properties(source, &deps, &self.schema, &column_ranges);
1119 let sort_properties = ep.map(|prop| prop.sort_properties);
1120 if let Ok(SortProperties::Ordered(options)) = sort_properties {
1121 Some((options, deps))
1122 } else {
1123 // Do not consider unordered cases.
1124 None
1125 }
1126 })
1127 .flat_map(|(options, relevant_deps)| {
1128 // Generate dependent orderings (i.e. prefixes for targets):
1129 let dependency_orderings =
1130 generate_dependency_orderings(&relevant_deps, &dependency_map);
1131 let sort_exprs = targets.iter().map(|(target, _)| {
1132 PhysicalSortExpr::new(Arc::clone(target), options)
1133 });
1134 if dependency_orderings.is_empty() {
1135 sort_exprs.map(|sort_expr| [sort_expr].into()).collect()
1136 } else {
1137 sort_exprs
1138 .flat_map(|sort_expr| {
1139 let mut result = dependency_orderings.clone();
1140 for ordering in result.iter_mut() {
1141 ordering.push(sort_expr.clone());
1142 }
1143 result
1144 })
1145 .collect::<Vec<_>>()
1146 }
1147 })
1148 });
1149
1150 // Add valid projected orderings. For example, if existing ordering is
1151 // `a + b` and projection is `[a -> a_new, b -> b_new]`, we need to
1152 // preserve `a_new + b_new` as ordered. Please note that `a_new` and
1153 // `b_new` themselves need not be ordered. Such dependencies cannot be
1154 // deduced via the pass above.
1155 let projected_orderings = dependency_map.iter().flat_map(|(sort_expr, node)| {
1156 let mut prefixes = construct_prefix_orderings(sort_expr, &dependency_map);
1157 if prefixes.is_empty() {
1158 // If prefix is empty, there is no dependency. Insert
1159 // empty ordering:
1160 if let Some(target) = &node.target {
1161 prefixes.push([target.clone()].into());
1162 }
1163 } else {
1164 // Append current ordering on top its dependencies:
1165 for ordering in prefixes.iter_mut() {
1166 if let Some(target) = &node.target {
1167 ordering.push(target.clone());
1168 }
1169 }
1170 }
1171 prefixes
1172 });
1173
1174 // Simplify each ordering by removing redundant sections:
1175 orderings.chain(projected_orderings).collect()
1176 }
1177
1178 /// Projects constraints according to the given projection mapping.
1179 ///
1180 /// This function takes a projection mapping and extracts column indices of
1181 /// target columns. It then projects the constraints to only include
1182 /// relationships between columns that exist in the projected output.
1183 ///
1184 /// # Parameters
1185 ///
1186 /// * `mapping` - A reference to the `ProjectionMapping` that defines the
1187 /// projection operation.
1188 ///
1189 /// # Returns
1190 ///
1191 /// Returns an optional `Constraints` object containing only the constraints
1192 /// that are valid for the projected columns (if any exists).
1193 fn projected_constraints(&self, mapping: &ProjectionMapping) -> Option<Constraints> {
1194 let indices = mapping
1195 .iter()
1196 .flat_map(|(_, targets)| {
1197 targets.iter().filter_map(|(target, _)| {
1198 target.downcast_ref::<Column>().map(|c| c.index())
1199 })
1200 })
1201 .collect::<Vec<_>>();
1202 self.constraints.project(&indices)
1203 }
1204
1205 /// Projects these equivalence properties onto `output_schema` according to
1206 /// `mapping`, returning the properties that still hold for the projected
1207 /// output.
1208 ///
1209 /// `mapping` maps each source expression (evaluated against the current
1210 /// schema) to the output column(s) it produces. This is more than a
1211 /// column-index remap: the orderings, the equivalence group and the
1212 /// constraints are all carried through `mapping`, keeping only what the
1213 /// projected schema can still express.
1214 ///
1215 /// - Orderings: an existing ordering is carried to a target only when the
1216 /// mapping expression is order-preserving for it, as determined from the
1217 /// expression's [`SortProperties`]. For example, an ordering on `c` is
1218 /// preserved through `c + 1` but dropped through `abs(c)`. Orderings
1219 /// implied by the mapping are also derived, e.g. an ordering on `a + b`
1220 /// yields one on the projected `a_new + b_new`.
1221 /// - Equivalence group: each class is re-expressed on the output columns.
1222 /// - Constraints: projected onto the surviving column indices.
1223 ///
1224 /// Expressions and orderings not representable in `output_schema` are
1225 /// dropped.
1226 pub fn project(&self, mapping: &ProjectionMapping, output_schema: SchemaRef) -> Self {
1227 let eq_group = self.eq_group.project(mapping);
1228 // Built here, so it satisfies the precondition by construction; going
1229 // through the checked entry point would reproject it under
1230 // `debug_assertions` for nothing.
1231 self.project_with_eq_group_unchecked(mapping, output_schema, eq_group)
1232 }
1233
1234 /// Projects `self`, reusing `cached`'s already-projected equivalence group
1235 /// when `self`'s group is unchanged from `previous`'s.
1236 ///
1237 /// [`EquivalenceGroup::project`] is a pure function of the group and the
1238 /// mapping, so when the group is unchanged the previous result can be handed
1239 /// back rather than recomputed. Orderings are still derived here: they are
1240 /// precisely what changes when a sort is introduced below this node.
1241 ///
1242 /// Falls back to a full projection when the groups differ, so there is no
1243 /// precondition to violate. The caller does still have to pass a `cached`
1244 /// that came from projecting `previous` through this same `mapping`; that
1245 /// part cannot be checked here, and in practice it holds because the caller
1246 /// carries its projection over untouched.
1247 pub fn project_reusing(
1248 &self,
1249 mapping: &ProjectionMapping,
1250 output_schema: SchemaRef,
1251 previous: &EquivalenceProperties,
1252 cached: &EquivalenceProperties,
1253 ) -> Self {
1254 let eq_group = if self.eq_group.has_same_classes(&previous.eq_group) {
1255 #[cfg(test)]
1256 eq_group_reuse_probe::record_hit();
1257 cached.eq_group.clone()
1258 } else {
1259 self.eq_group.project(mapping)
1260 };
1261 self.project_with_eq_group_unchecked(mapping, output_schema, eq_group)
1262 }
1263
1264 fn project_with_eq_group_unchecked(
1265 &self,
1266 mapping: &ProjectionMapping,
1267 output_schema: SchemaRef,
1268 eq_group: EquivalenceGroup,
1269 ) -> Self {
1270 let orderings =
1271 self.projected_orderings(mapping, self.oeq_cache.normal_cls.clone());
1272 let normal_orderings = orderings
1273 .iter()
1274 .cloned()
1275 .map(|o| eq_group.normalize_sort_exprs(o));
1276 Self {
1277 oeq_cache: OrderingEquivalenceCache::new(normal_orderings),
1278 oeq_class: OrderingEquivalenceClass::new(orderings),
1279 constraints: self.projected_constraints(mapping).unwrap_or_default(),
1280 schema: output_schema,
1281 eq_group,
1282 }
1283 }
1284
1285 /// Returns the longest (potentially partial) permutation satisfying the
1286 /// existing ordering. For example, if we have the equivalent orderings
1287 /// `[a ASC, b ASC]` and `[c DESC]`, with `exprs` containing `[c, b, a, d]`,
1288 /// then this function returns `([a ASC, b ASC, c DESC], [2, 1, 0])`.
1289 /// This means that the specification `[a ASC, b ASC, c DESC]` is satisfied
1290 /// by the existing ordering, and `[a, b, c]` resides at indices: `2, 1, 0`
1291 /// inside the argument `exprs` (respectively). For the mathematical
1292 /// definition of "partial permutation", see:
1293 ///
1294 /// <https://en.wikipedia.org/wiki/Permutation#k-permutations_of_n>
1295 pub fn find_longest_permutation(
1296 &self,
1297 exprs: &[Arc<dyn PhysicalExpr>],
1298 ) -> Result<(Vec<PhysicalSortExpr>, Vec<usize>)> {
1299 let mut walk = SortKeyWalk::new(self);
1300 let mut result = vec![];
1301 // The algorithm is as follows:
1302 // - Iterate over all the expressions and insert ordered expressions
1303 // into the result.
1304 // - Pin inserted expressions (see [`SortKeyWalk`]).
1305 // - Continue the above procedure until no expression is inserted; i.e.
1306 // the algorithm reaches a fixed point.
1307 // This algorithm should reach a fixed point in at most `exprs.len()`
1308 // iterations.
1309 let mut search_indices = (0..exprs.len()).collect::<IndexSet<_>>();
1310 for _ in 0..exprs.len() {
1311 // Get ordered expressions with their indices.
1312 let ordered_exprs = search_indices
1313 .iter()
1314 .filter_map(|&idx| {
1315 let ExprProperties {
1316 sort_properties, ..
1317 } = walk.expr_properties(Arc::clone(&exprs[idx]));
1318 match sort_properties {
1319 SortProperties::Ordered(options) => {
1320 let expr = Arc::clone(&exprs[idx]);
1321 Some((PhysicalSortExpr::new(expr, options), idx))
1322 }
1323 SortProperties::Singleton => {
1324 // Assign default ordering to constant expressions:
1325 let expr = Arc::clone(&exprs[idx]);
1326 Some((PhysicalSortExpr::new_default(expr), idx))
1327 }
1328 SortProperties::Unordered => None,
1329 }
1330 })
1331 .collect::<Vec<_>>();
1332 // We reached a fixed point, exit.
1333 if ordered_exprs.is_empty() {
1334 break;
1335 }
1336 // Remove indices that have an ordering from `search_indices`, and
1337 // pin the ordered expressions (in normal form, as the walk sees
1338 // the orderings) for the next iterations, if any. We can do this
1339 // because the "next" key only matters in a lexicographical
1340 // ordering when the keys to its left have the same values.
1341 for (_, idx) in &ordered_exprs {
1342 search_indices.shift_remove(idx);
1343 }
1344 if !search_indices.is_empty() {
1345 for (PhysicalSortExpr { expr, .. }, _) in &ordered_exprs {
1346 walk.pin(self.eq_group.normalize_expr(Arc::clone(expr)))?;
1347 }
1348 }
1349 // Add new ordered section to the state.
1350 result.extend(ordered_exprs);
1351 }
1352 Ok(result.into_iter().unzip())
1353 }
1354
1355 /// This function determines whether the provided expression is constant
1356 /// based on the known constants. For example, if columns `a` and `b` are
1357 /// constant, then expressions `a`, `b` and `a + b` will all return `true`
1358 /// whereas expression `c` will return `false`.
1359 ///
1360 /// # Parameters
1361 ///
1362 /// - `expr`: A reference to a `Arc<dyn PhysicalExpr>` representing the
1363 /// expression to be checked.
1364 ///
1365 /// # Returns
1366 ///
1367 /// Returns a `Some` value if the expression is constant according to
1368 /// equivalence group, and `None` otherwise. The `Some` variant contains
1369 /// an `AcrossPartitions` value indicating whether the expression is
1370 /// constant across partitions, and its actual value (if available).
1371 pub fn is_expr_constant(
1372 &self,
1373 expr: &Arc<dyn PhysicalExpr>,
1374 ) -> Option<AcrossPartitions> {
1375 self.eq_group.is_expr_constant(expr)
1376 }
1377
1378 /// Retrieves the properties for a given physical expression.
1379 ///
1380 /// This function constructs an [`ExprProperties`] object for the given
1381 /// expression, which encapsulates information about the expression's
1382 /// properties, including its [`SortProperties`] and [`Interval`].
1383 ///
1384 /// # Parameters
1385 ///
1386 /// - `expr`: An `Arc<dyn PhysicalExpr>` representing the physical expression
1387 /// for which ordering information is sought.
1388 ///
1389 /// # Returns
1390 ///
1391 /// Returns an [`ExprProperties`] object containing the ordering and range
1392 /// information for the given expression. If its ordering is unknown, falls
1393 /// back to the sort properties of an equivalent expression.
1394 pub fn get_expr_properties(&self, expr: Arc<dyn PhysicalExpr>) -> ExprProperties {
1395 SortKeyWalk::new(self).expr_properties(expr)
1396 }
1397
1398 /// Returns whether `transformed_expr` reports the same ordering direction
1399 /// when `source_expr` is ordered and all other inputs are singleton.
1400 pub(crate) fn is_same_direction_ordered_transform(
1401 &self,
1402 transformed_expr: &Arc<dyn PhysicalExpr>,
1403 source_expr: &Arc<dyn PhysicalExpr>,
1404 ) -> bool {
1405 if transformed_expr.eq(source_expr) {
1406 return false;
1407 }
1408
1409 let options = SortOptions::default();
1410 let dependencies = Dependencies::new(std::iter::once(PhysicalSortExpr::new(
1411 Arc::clone(source_expr),
1412 options,
1413 )));
1414 matches!(
1415 get_expr_properties(
1416 transformed_expr,
1417 &dependencies,
1418 &self.schema,
1419 &ColumnRanges::default(),
1420 )
1421 .map(|properties| properties.sort_properties),
1422 Ok(SortProperties::Ordered(actual)) if actual == options
1423 )
1424 }
1425
1426 /// Transforms this `EquivalenceProperties` by mapping columns in the
1427 /// original schema to columns in the new schema by index.
1428 pub fn with_new_schema(mut self, schema: SchemaRef) -> Result<Self> {
1429 // The new schema and the original schema is aligned when they have the
1430 // same number of columns, and fields at the same index have the same
1431 // type in both schemas.
1432 let schemas_aligned = (self.schema.fields.len() == schema.fields.len())
1433 && self
1434 .schema
1435 .fields
1436 .iter()
1437 .zip(schema.fields.iter())
1438 .all(|(lhs, rhs)| lhs.data_type().eq(rhs.data_type()));
1439 if !schemas_aligned {
1440 // Rewriting equivalence properties in terms of new schema is not
1441 // safe when schemas are not aligned:
1442 return plan_err!(
1443 "Schemas have to be aligned to rewrite equivalences:\n Old schema: {}\n New schema: {}",
1444 self.schema,
1445 schema
1446 );
1447 }
1448
1449 // Rewrite equivalence classes according to the new schema:
1450 let mut eq_classes = Vec::with_capacity(self.eq_group.len());
1451 for mut eq_class in self.eq_group {
1452 // Rewrite the expressions in the equivalence class:
1453 eq_class.exprs = eq_class
1454 .exprs
1455 .into_iter()
1456 .map(|expr| with_new_schema(expr, &schema))
1457 .collect::<Result<_>>()?;
1458 // Rewrite the constant value (if available and known):
1459 let data_type = eq_class
1460 .canonical_expr()
1461 .map(|e| e.data_type(&schema))
1462 .transpose()?;
1463 if let (Some(data_type), Some(AcrossPartitions::Uniform(Some(value)))) =
1464 (data_type, &mut eq_class.constant)
1465 {
1466 match value.cast_to(&data_type) {
1467 Ok(cast_value) => *value = cast_value,
1468 Err(_) => {
1469 // This is optimizer metadata. If a stale constant
1470 // value cannot be represented after schema rewrite,
1471 // drop the constant instead of failing planning.
1472 eq_class.constant = None;
1473 }
1474 }
1475 }
1476 if eq_class.is_trivial() {
1477 continue;
1478 }
1479 eq_classes.push(eq_class);
1480 }
1481 self.eq_group = eq_classes.into();
1482
1483 // Rewrite orderings according to new schema:
1484 self.oeq_class = self.oeq_class.with_new_schema(&schema)?;
1485 self.oeq_cache.normal_cls = self.oeq_cache.normal_cls.with_new_schema(&schema)?;
1486
1487 // Update the schema:
1488 self.schema = schema;
1489
1490 Ok(self)
1491 }
1492}
1493
1494impl From<EquivalenceProperties> for OrderingEquivalenceClass {
1495 fn from(eq_properties: EquivalenceProperties) -> Self {
1496 eq_properties.oeq_class
1497 }
1498}
1499
1500/// More readable display version of the `EquivalenceProperties`.
1501///
1502/// Format:
1503/// ```text
1504/// order: [[b@1 ASC NULLS LAST]], eq: [{members: [a@0], constant: (heterogeneous)}]
1505/// ```
1506impl Display for EquivalenceProperties {
1507 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1508 let empty_eq_group = self.eq_group.is_empty();
1509 let empty_oeq_class = self.oeq_class.is_empty();
1510 if empty_oeq_class && empty_eq_group {
1511 write!(f, "No properties")?;
1512 } else if !empty_oeq_class {
1513 write!(f, "order: {}", self.oeq_class)?;
1514 if !empty_eq_group {
1515 write!(f, ", eq: {}", self.eq_group)?;
1516 }
1517 } else {
1518 write!(f, "eq: {}", self.eq_group)?;
1519 }
1520 Ok(())
1521 }
1522}
1523
1524/// This function examines whether a referring expression directly refers to a
1525/// given referred expression or if any of its children in the expression tree
1526/// refer to the specified expression.
1527///
1528/// # Parameters
1529///
1530/// - `referring_expr`: A reference to the referring expression (`Arc<dyn PhysicalExpr>`).
1531/// - `referred_expr`: A reference to the referred expression (`Arc<dyn PhysicalExpr>`)
1532///
1533/// # Returns
1534///
1535/// A boolean value indicating whether `referring_expr` refers (needs it to evaluate its result)
1536/// `referred_expr` or not.
1537fn expr_refers(
1538 referring_expr: &Arc<dyn PhysicalExpr>,
1539 referred_expr: &Arc<dyn PhysicalExpr>,
1540) -> bool {
1541 referring_expr.eq(referred_expr)
1542 || referring_expr
1543 .children()
1544 .iter()
1545 .any(|child| expr_refers(child, referred_expr))
1546}
1547
1548/// Unbounded ranges of the columns of one schema, built on first use.
1549///
1550/// Building the unbounded range of a nested type materializes a null array of that type, so
1551/// a wide struct referenced by many projection sources is costly to rebuild per reference.
1552/// Only `Column`s are cached, by index: the schema is fixed for the cache's lifetime. Other
1553/// expressions and failures are computed as before and never cached. Cloning a cached range
1554/// clones its two endpoints, which for nested types share their arrays.
1555#[derive(Default)]
1556struct ColumnRanges(std::cell::RefCell<HashMap<usize, Interval>>);
1557
1558impl ColumnRanges {
1559 fn unbounded(
1560 &self,
1561 expr: &Arc<dyn PhysicalExpr>,
1562 schema: &SchemaRef,
1563 ) -> Result<Interval> {
1564 let Some(column) = expr.downcast_ref::<Column>() else {
1565 return Interval::make_unbounded(&expr.data_type(schema)?);
1566 };
1567 if let Some(range) = self.0.borrow().get(&column.index()) {
1568 return Ok(range.clone());
1569 }
1570 let range = Interval::make_unbounded(&expr.data_type(schema)?)?;
1571 self.0.borrow_mut().insert(column.index(), range.clone());
1572 Ok(range)
1573 }
1574}
1575
1576/// This function examines the given expression and its properties to determine
1577/// the ordering properties of the expression. The range knowledge is not utilized
1578/// yet in the scope of this function.
1579///
1580/// # Parameters
1581///
1582/// - `expr`: A reference to the source expression (`Arc<dyn PhysicalExpr>`) for
1583/// which ordering properties need to be determined.
1584/// - `dependencies`: A reference to `Dependencies`, containing sort expressions
1585/// referred to by `expr`.
1586/// - `schema``: A reference to the schema which the `expr` columns refer.
1587///
1588/// # Returns
1589///
1590/// A `SortProperties` indicating the ordering information of the given expression.
1591fn get_expr_properties(
1592 expr: &Arc<dyn PhysicalExpr>,
1593 dependencies: &Dependencies,
1594 schema: &SchemaRef,
1595 column_ranges: &ColumnRanges,
1596) -> Result<ExprProperties> {
1597 if let Some(column_order) = dependencies.iter().find(|&order| expr.eq(&order.expr)) {
1598 // If exact match is found, return its ordering. This is a base case
1599 // of the recursion: the expression is treated as an atomic ordered
1600 // input from here on, so `strictly_order_preserving` states only that
1601 // it is a one-to-one mapping *of itself* (the identity), which holds
1602 // for any expression. It makes no claim about the expression being
1603 // one-to-one in its own inputs (e.g. `floor(x)` as a sort key), and
1604 // it does not need to: parent expressions are substituted for this
1605 // sort key, so their strictness only has to be relative to it.
1606 Ok(ExprProperties {
1607 sort_properties: SortProperties::Ordered(column_order.options),
1608 range: column_ranges.unbounded(expr, schema)?,
1609 preserves_lex_ordering: false,
1610 strictly_order_preserving: true,
1611 })
1612 } else if expr.downcast_ref::<Column>().is_some() {
1613 Ok(ExprProperties {
1614 sort_properties: SortProperties::Unordered,
1615 range: column_ranges.unbounded(expr, schema)?,
1616 preserves_lex_ordering: false,
1617 // A base case of the recursion: a column is the identity mapping
1618 // of itself, which is trivially one-to-one.
1619 strictly_order_preserving: true,
1620 })
1621 } else if let Some(literal) = expr.downcast_ref::<Literal>() {
1622 Ok(ExprProperties {
1623 sort_properties: SortProperties::Singleton,
1624 range: literal.value().into(),
1625 preserves_lex_ordering: true,
1626 // Vacuously true: a literal has no ordered inputs.
1627 strictly_order_preserving: true,
1628 })
1629 } else {
1630 // Find orderings of its children
1631 let child_states = expr
1632 .children()
1633 .iter()
1634 .map(|child| get_expr_properties(child, dependencies, schema, column_ranges))
1635 .collect::<Result<Vec<_>>>()?;
1636 // Calculate expression ordering using ordering of its children.
1637 expr.get_properties(&child_states)
1638 }
1639}
1640
1641#[cfg(test)]
1642mod tests {
1643 use super::*;
1644
1645 use crate::equivalence::tests::create_test_params;
1646 use crate::expressions::col;
1647
1648 use arrow::datatypes::{DataType, Field, Schema};
1649
1650 /// Renames `a`, `b`, `c` and `d` so the projection is non-trivial while
1651 /// still carrying every ordering and the `a = c` class across.
1652 fn renaming_mapping(
1653 schema: &SchemaRef,
1654 output_schema: &SchemaRef,
1655 ) -> Result<ProjectionMapping> {
1656 [
1657 ("a", "a1", 0),
1658 ("b", "b1", 1),
1659 ("c", "c1", 2),
1660 ("d", "d1", 3),
1661 ]
1662 .into_iter()
1663 .map(|(source, target, index)| {
1664 Ok((
1665 col(source, schema)?,
1666 vec![(col(target, output_schema)?, index)].into(),
1667 ))
1668 })
1669 .collect::<Result<Vec<_>>>()
1670 .map(|entries| entries.into_iter().collect())
1671 }
1672
1673 fn renamed_schema() -> SchemaRef {
1674 Arc::new(Schema::new(vec![
1675 Field::new("a1", DataType::Int32, true),
1676 Field::new("b1", DataType::Int32, true),
1677 Field::new("c1", DataType::Int32, true),
1678 Field::new("d1", DataType::Int32, true),
1679 ]))
1680 }
1681
1682 #[test]
1683 fn test_project_reusing_matches_project() -> Result<()> {
1684 let (schema, eq_properties) = create_test_params()?;
1685 let output_schema = renamed_schema();
1686 let mapping = renaming_mapping(&schema, &output_schema)?;
1687
1688 let baseline = eq_properties.project(&mapping, Arc::clone(&output_schema));
1689
1690 // Reusing the projection of an identical group must reproduce it exactly.
1691 let (reused, hits) = eq_group_reuse_probe::count(|| {
1692 eq_properties.project_reusing(
1693 &mapping,
1694 Arc::clone(&output_schema),
1695 &eq_properties,
1696 &baseline,
1697 )
1698 });
1699 assert_eq!(
1700 hits, 1,
1701 "the reuse path was not taken, so this compares nothing"
1702 );
1703
1704 // Guard against a vacuous comparison.
1705 assert!(
1706 !baseline.eq_group().is_empty(),
1707 "the projection dropped the equivalence class, nothing is being tested"
1708 );
1709 assert!(
1710 !baseline.oeq_class().is_empty(),
1711 "the projection dropped every ordering, nothing is being tested"
1712 );
1713
1714 assert!(
1715 baseline.eq_group().has_same_classes(reused.eq_group()),
1716 "equivalence group"
1717 );
1718 assert_eq!(baseline.oeq_class(), reused.oeq_class(), "orderings");
1719 assert_eq!(baseline.constraints(), reused.constraints(), "constraints");
1720 assert_eq!(baseline.schema(), reused.schema(), "schema");
1721
1722 Ok(())
1723 }
1724
1725 #[test]
1726 fn test_project_reusing_falls_back_when_the_group_moved() -> Result<()> {
1727 // A `previous` whose group differs must not have its projection carried
1728 // over. There is no precondition to violate here: the fallback is what
1729 // keeps a mismatched pair from producing properties that disagree with
1730 // the projection.
1731 let (schema, eq_properties) = create_test_params()?;
1732 let output_schema = renamed_schema();
1733 let mapping = renaming_mapping(&schema, &output_schema)?;
1734
1735 let baseline = eq_properties.project(&mapping, Arc::clone(&output_schema));
1736 let unrelated = EquivalenceProperties::new(Arc::clone(&schema));
1737 assert!(
1738 !eq_properties
1739 .eq_group()
1740 .has_same_classes(unrelated.eq_group()),
1741 "the two groups were meant to differ"
1742 );
1743
1744 let (recomputed, hits) = eq_group_reuse_probe::count(|| {
1745 eq_properties.project_reusing(
1746 &mapping,
1747 Arc::clone(&output_schema),
1748 &unrelated,
1749 &baseline,
1750 )
1751 });
1752 assert_eq!(hits, 0, "a mismatched group was carried over anyway");
1753
1754 // Falling back must land on exactly what `project` would have produced.
1755 assert!(
1756 baseline.eq_group().has_same_classes(recomputed.eq_group()),
1757 "equivalence group"
1758 );
1759 assert_eq!(baseline.oeq_class(), recomputed.oeq_class(), "orderings");
1760
1761 Ok(())
1762 }
1763}