datafusion_physical_expr_common/sort_expr.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
5//! Sort expressions
6
7use std::cmp::Ordering;
8use std::fmt::{self, Display, Formatter};
9use std::hash::{Hash, Hasher};
10use std::ops::{Deref, DerefMut};
11use std::sync::Arc;
12use std::vec::IntoIter;
13
14use crate::physical_expr::{PhysicalExpr, fmt_sql};
15
16use arrow::compute::kernels::sort::{SortColumn, SortOptions};
17use arrow::datatypes::Schema;
18use arrow::record_batch::RecordBatch;
19use datafusion_common::{HashSet, Result};
20use datafusion_expr_common::columnar_value::ColumnarValue;
21use indexmap::IndexSet;
22/// Represents Sort operation for a column in a RecordBatch
23///
24/// Example:
25/// ```
26/// # use std::any::Any;
27/// # use std::collections::HashMap;
28/// # use std::fmt::{Display, Formatter};
29/// # use std::hash::Hasher;
30/// # use std::sync::Arc;
31/// # use arrow::array::RecordBatch;
32/// # use datafusion_common::Result;
33/// # use arrow::compute::SortOptions;
34/// # use arrow::datatypes::{DataType, Field, FieldRef, Schema};
35/// # use datafusion_expr_common::columnar_value::ColumnarValue;
36/// # use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
37/// # use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
38/// # // this crate doesn't have a physical expression implementation
39/// # // so make a really simple one
40/// # #[derive(Clone, Debug, PartialEq, Eq, Hash)]
41/// # struct MyPhysicalExpr;
42/// # impl PhysicalExpr for MyPhysicalExpr {
43/// # fn data_type(&self, input_schema: &Schema) -> Result<DataType> {todo!()}
44/// # fn nullable(&self, input_schema: &Schema) -> Result<bool> {todo!() }
45/// # fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {todo!() }
46/// # fn return_field(&self, input_schema: &Schema) -> Result<FieldRef> { unimplemented!() }
47/// # fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {todo!()}
48/// # fn with_new_children(self: Arc<Self>, children: Vec<Arc<dyn PhysicalExpr>>) -> Result<Arc<dyn PhysicalExpr>> {todo!()}
49/// # fn fmt_sql(&self, f: &mut Formatter<'_>) -> std::fmt::Result { todo!() }
50/// # }
51/// # impl Display for MyPhysicalExpr {
52/// # fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "a") }
53/// # }
54/// # fn col(name: &str) -> Arc<dyn PhysicalExpr> { Arc::new(MyPhysicalExpr) }
55/// // Sort by a ASC
56/// let options = SortOptions::default();
57/// let sort_expr = PhysicalSortExpr::new(col("a"), options);
58/// assert_eq!(sort_expr.to_string(), "a ASC");
59///
60/// // Sort by a DESC NULLS LAST
61/// let sort_expr = PhysicalSortExpr::new_default(col("a"))
62/// .desc()
63/// .nulls_last();
64/// assert_eq!(sort_expr.to_string(), "a DESC NULLS LAST");
65/// ```
66#[derive(Clone, Debug, Eq)]
67pub struct PhysicalSortExpr {
68 /// Physical expression representing the column to sort
69 pub expr: Arc<dyn PhysicalExpr>,
70 /// Option to specify how the given column should be sorted
71 pub options: SortOptions,
72}
73
74impl PhysicalSortExpr {
75 /// Create a new PhysicalSortExpr
76 pub fn new(expr: Arc<dyn PhysicalExpr>, options: SortOptions) -> Self {
77 Self { expr, options }
78 }
79
80 /// Create a new PhysicalSortExpr with default [`SortOptions`]
81 pub fn new_default(expr: Arc<dyn PhysicalExpr>) -> Self {
82 Self::new(expr, SortOptions::default())
83 }
84
85 /// Reverses the sort expression. For instance, `[a ASC NULLS LAST]` turns
86 /// into `[a DESC NULLS FIRST]`. Such reversals are useful in planning, e.g.
87 /// when constructing equivalent window expressions.
88 pub fn reverse(&self) -> Self {
89 let mut result = self.clone();
90 result.options = !result.options;
91 result
92 }
93
94 /// Set the sort options to ASC
95 pub fn asc(mut self) -> Self {
96 self.options.descending = false;
97 self
98 }
99
100 /// Set the sort options to DESC
101 pub fn desc(mut self) -> Self {
102 self.options.descending = true;
103 self
104 }
105
106 /// Set the sort options to NULLS FIRST
107 pub fn nulls_first(mut self) -> Self {
108 self.options.nulls_first = true;
109 self
110 }
111
112 /// Set the sort options to NULLS LAST
113 pub fn nulls_last(mut self) -> Self {
114 self.options.nulls_first = false;
115 self
116 }
117
118 /// Like [`PhysicalExpr::fmt_sql`] prints a [`PhysicalSortExpr`] in a SQL-like format.
119 pub fn fmt_sql(&self, f: &mut Formatter) -> fmt::Result {
120 write!(
121 f,
122 "{} {}",
123 fmt_sql(self.expr.as_ref()),
124 to_str(&self.options)
125 )
126 }
127
128 /// Evaluates the sort expression into a `SortColumn` that can be passed
129 /// into the arrow sort kernel.
130 pub fn evaluate_to_sort_column(&self, batch: &RecordBatch) -> Result<SortColumn> {
131 let array_to_sort = match self.expr.evaluate(batch)? {
132 ColumnarValue::Array(array) => array,
133 ColumnarValue::Scalar(scalar) => scalar.to_array_of_size(batch.num_rows())?,
134 };
135 Ok(SortColumn {
136 values: array_to_sort,
137 options: Some(self.options),
138 })
139 }
140
141 /// Checks whether this sort expression satisfies the given `requirement`.
142 /// If sort options are unspecified in `requirement`, only expressions are
143 /// compared for inequality. See [`options_compatible`] for details on
144 /// how sort options compare with one another.
145 pub fn satisfy(
146 &self,
147 requirement: &PhysicalSortRequirement,
148 schema: &Schema,
149 ) -> bool {
150 self.expr.eq(&requirement.expr)
151 && requirement.options.is_none_or(|opts| {
152 options_compatible(
153 &self.options,
154 &opts,
155 self.expr.nullable(schema).unwrap_or(true),
156 )
157 })
158 }
159
160 /// Checks whether this sort expression satisfies the given `sort_expr`.
161 /// See [`options_compatible`] for details on how sort options compare with
162 /// one another.
163 pub fn satisfy_expr(&self, sort_expr: &Self, schema: &Schema) -> bool {
164 self.expr.eq(&sort_expr.expr)
165 && options_compatible(
166 &self.options,
167 &sort_expr.options,
168 self.expr.nullable(schema).unwrap_or(true),
169 )
170 }
171}
172
173/// Protobuf conversions for [`PhysicalSortExpr`].
174///
175/// This is the flat [`PhysicalSortExprNode`] representation used wherever the
176/// wire format stores an ordering (scan output orderings, range partitioning,
177/// window frames, …). It is *not* the `PhysicalExprNode::Sort` wrapping that
178/// `SortExec` uses for its own `expr` field.
179///
180/// [`PhysicalSortExprNode`]: datafusion_proto_models::protobuf::PhysicalSortExprNode
181#[cfg(feature = "proto")]
182impl PhysicalSortExpr {
183 /// Serialize this sort expression, encoding its child expression through
184 /// `ctx`.
185 pub fn try_to_proto(
186 &self,
187 ctx: &crate::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
188 ) -> Result<datafusion_proto_models::protobuf::PhysicalSortExprNode> {
189 let Self { expr, options } = self;
190 Ok(datafusion_proto_models::protobuf::PhysicalSortExprNode {
191 expr: Some(Box::new(ctx.encode_child(expr)?)),
192 asc: !options.descending,
193 nulls_first: options.nulls_first,
194 })
195 }
196
197 /// Reconstruct a [`PhysicalSortExpr`] from its protobuf representation.
198 pub fn try_from_proto(
199 node: &datafusion_proto_models::protobuf::PhysicalSortExprNode,
200 ctx: &crate::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
201 ) -> Result<Self> {
202 let datafusion_proto_models::protobuf::PhysicalSortExprNode {
203 expr,
204 asc,
205 nulls_first,
206 } = node;
207 let expr =
208 ctx.decode_required_expression(expr.as_deref(), "PhysicalSortExpr", "expr")?;
209 Ok(PhysicalSortExpr {
210 expr,
211 options: SortOptions {
212 descending: !asc,
213 nulls_first: *nulls_first,
214 },
215 })
216 }
217}
218
219/// Serialize a sequence of sort expressions into the flat
220/// [`PhysicalSortExprNode`] list the wire format uses for an ordering.
221///
222/// Accepts anything that yields [`PhysicalSortExpr`]s by value or by reference,
223/// so a [`LexOrdering`], a `&[PhysicalSortExpr]`, or a [`LexRequirement`]
224/// mapped through [`PhysicalSortExpr::from`] all work:
225///
226/// ```ignore
227/// let nodes = sort_exprs_try_to_proto(ordering.iter(), ctx)?;
228/// let nodes = sort_exprs_try_to_proto(
229/// requirement.iter().map(|req| PhysicalSortExpr::from(req.clone())),
230/// ctx,
231/// )?;
232/// ```
233///
234/// The `PhysicalSortExprNodeCollection` message some plans use is just this
235/// list in a wrapper, so those callers wrap the result themselves rather than
236/// this function guessing which shape they mean.
237///
238/// [`PhysicalSortExprNode`]: datafusion_proto_models::protobuf::PhysicalSortExprNode
239#[cfg(feature = "proto")]
240pub fn sort_exprs_try_to_proto<E: std::borrow::Borrow<PhysicalSortExpr>>(
241 exprs: impl IntoIterator<Item = E>,
242 ctx: &crate::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
243) -> Result<Vec<datafusion_proto_models::protobuf::PhysicalSortExprNode>> {
244 exprs
245 .into_iter()
246 .map(|expr| expr.borrow().try_to_proto(ctx))
247 .collect()
248}
249
250/// Reconstruct a sequence of sort expressions from the flat
251/// [`PhysicalSortExprNode`] list, the counterpart of
252/// [`sort_exprs_try_to_proto`].
253///
254/// Returns the expressions rather than a [`LexOrdering`] or a
255/// [`LexRequirement`], because callers differ in what an empty list means:
256/// `LexOrdering::new` / `LexRequirement::new` return `None` for it, which is
257/// "no ordering declared" for a scan and an error for an operator that requires
258/// one. Callers with the former convention can use
259/// [`optional_ordering_try_from_proto`] instead.
260///
261/// [`PhysicalSortExprNode`]: datafusion_proto_models::protobuf::PhysicalSortExprNode
262#[cfg(feature = "proto")]
263pub fn sort_exprs_try_from_proto(
264 nodes: &[datafusion_proto_models::protobuf::PhysicalSortExprNode],
265 ctx: &crate::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
266) -> Result<Vec<PhysicalSortExpr>> {
267 nodes
268 .iter()
269 .map(|node| PhysicalSortExpr::try_from_proto(node, ctx))
270 .collect()
271}
272
273/// Serialize an optional [`LexOrdering`], encoding `None` as an empty list.
274#[cfg(feature = "proto")]
275pub fn optional_ordering_try_to_proto(
276 ordering: Option<&LexOrdering>,
277 ctx: &crate::physical_expr::proto_encode::PhysicalExprEncodeCtx<'_>,
278) -> Result<Vec<datafusion_proto_models::protobuf::PhysicalSortExprNode>> {
279 sort_exprs_try_to_proto(ordering.into_iter().flatten(), ctx)
280}
281
282/// Counterpart of [`optional_ordering_try_to_proto`]: an empty list decodes
283/// as `None`.
284#[cfg(feature = "proto")]
285pub fn optional_ordering_try_from_proto(
286 nodes: &[datafusion_proto_models::protobuf::PhysicalSortExprNode],
287 ctx: &crate::physical_expr::proto_decode::PhysicalExprDecodeCtx<'_>,
288) -> Result<Option<LexOrdering>> {
289 Ok(LexOrdering::new(sort_exprs_try_from_proto(nodes, ctx)?))
290}
291
292impl PartialEq for PhysicalSortExpr {
293 fn eq(&self, other: &Self) -> bool {
294 self.options == other.options && self.expr.eq(&other.expr)
295 }
296}
297
298impl Hash for PhysicalSortExpr {
299 fn hash<H: Hasher>(&self, state: &mut H) {
300 self.expr.hash(state);
301 self.options.hash(state);
302 }
303}
304
305impl Display for PhysicalSortExpr {
306 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
307 write!(f, "{} {}", self.expr, to_str(&self.options))
308 }
309}
310
311/// Returns whether the given two [`SortOptions`] are compatible. Here,
312/// compatibility means that they are either exactly equal, or they differ only
313/// in whether NULL values come in first/last, which is immaterial because the
314/// column in question is not nullable (specified by the `nullable` parameter).
315pub fn options_compatible(
316 options_lhs: &SortOptions,
317 options_rhs: &SortOptions,
318 nullable: bool,
319) -> bool {
320 if nullable {
321 options_lhs == options_rhs
322 } else {
323 // If the column is not nullable, NULLS FIRST/LAST is not important.
324 options_lhs.descending == options_rhs.descending
325 }
326}
327
328/// Represents sort requirement associated with a plan
329///
330/// If the requirement includes [`SortOptions`] then both the
331/// expression *and* the sort options must match.
332///
333/// If the requirement does not include [`SortOptions`]) then only the
334/// expressions must match.
335///
336/// # Examples
337///
338/// With sort options (`A`, `DESC NULLS FIRST`):
339/// * `ORDER BY A DESC NULLS FIRST` matches
340/// * `ORDER BY A ASC NULLS FIRST` does not match (`ASC` vs `DESC`)
341/// * `ORDER BY B DESC NULLS FIRST` does not match (different expr)
342///
343/// Without sort options (`A`, None):
344/// * `ORDER BY A DESC NULLS FIRST` matches
345/// * `ORDER BY A ASC NULLS FIRST` matches (`ASC` and `NULL` options ignored)
346/// * `ORDER BY B DESC NULLS FIRST` does not match (different expr)
347#[derive(Clone, Debug)]
348pub struct PhysicalSortRequirement {
349 /// Physical expression representing the column to sort
350 pub expr: Arc<dyn PhysicalExpr>,
351 /// Option to specify how the given column should be sorted.
352 /// If unspecified, there are no constraints on sort options.
353 pub options: Option<SortOptions>,
354}
355
356impl PartialEq for PhysicalSortRequirement {
357 fn eq(&self, other: &Self) -> bool {
358 self.options == other.options && self.expr.eq(&other.expr)
359 }
360}
361
362impl Display for PhysicalSortRequirement {
363 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
364 let opts_string = self.options.as_ref().map_or("NA", to_str);
365 write!(f, "{} {}", self.expr, opts_string)
366 }
367}
368
369/// Writes a list of [`PhysicalSortRequirement`]s to a `std::fmt::Formatter`.
370///
371/// Example output: `[a + 1, b]`
372pub fn format_physical_sort_requirement_list(
373 exprs: &[PhysicalSortRequirement],
374) -> impl Display + '_ {
375 struct DisplayWrapper<'a>(&'a [PhysicalSortRequirement]);
376 impl Display for DisplayWrapper<'_> {
377 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
378 let mut iter = self.0.iter();
379 write!(f, "[")?;
380 if let Some(expr) = iter.next() {
381 write!(f, "{expr}")?;
382 }
383 for expr in iter {
384 write!(f, ", {expr}")?;
385 }
386 write!(f, "]")?;
387 Ok(())
388 }
389 }
390 DisplayWrapper(exprs)
391}
392
393impl PhysicalSortRequirement {
394 /// Creates a new requirement.
395 ///
396 /// If `options` is `Some(..)`, creates an `exact` requirement,
397 /// which must match both `options` and `expr`.
398 ///
399 /// If `options` is `None`, Creates a new `expr_only` requirement,
400 /// which must match only `expr`.
401 ///
402 /// See [`PhysicalSortRequirement`] for examples.
403 pub fn new(expr: Arc<dyn PhysicalExpr>, options: Option<SortOptions>) -> Self {
404 Self { expr, options }
405 }
406
407 /// Returns whether this requirement is equal or more specific than `other`.
408 pub fn compatible(&self, other: &Self) -> bool {
409 self.expr.eq(&other.expr)
410 && other
411 .options
412 .is_none_or(|other_opts| self.options == Some(other_opts))
413 }
414}
415
416/// Returns the SQL string representation of the given [`SortOptions`] object.
417#[inline]
418fn to_str(options: &SortOptions) -> &str {
419 match (options.descending, options.nulls_first) {
420 (true, true) => "DESC",
421 (true, false) => "DESC NULLS LAST",
422 (false, true) => "ASC",
423 (false, false) => "ASC NULLS LAST",
424 }
425}
426
427// Cross-conversion utilities between `PhysicalSortExpr` and `PhysicalSortRequirement`
428impl From<PhysicalSortExpr> for PhysicalSortRequirement {
429 fn from(value: PhysicalSortExpr) -> Self {
430 Self::new(value.expr, Some(value.options))
431 }
432}
433
434impl From<PhysicalSortRequirement> for PhysicalSortExpr {
435 /// The default sort options `ASC, NULLS LAST` when the requirement does
436 /// not specify sort options. This default is consistent with PostgreSQL.
437 ///
438 /// Reference: <https://www.postgresql.org/docs/current/queries-order.html>
439 fn from(value: PhysicalSortRequirement) -> Self {
440 let options = value
441 .options
442 .unwrap_or_else(|| SortOptions::new(false, false));
443 Self::new(value.expr, options)
444 }
445}
446
447/// This object represents a lexicographical ordering and contains a vector
448/// of `PhysicalSortExpr` objects.
449///
450/// For example, a `vec![a ASC, b DESC]` represents a lexicographical ordering
451/// that first sorts by column `a` in ascending order, then by column `b` in
452/// descending order.
453///
454/// # Invariants
455///
456/// The following always hold true for a `LexOrdering`:
457///
458/// 1. It is non-degenerate, meaning it contains at least one element.
459/// 2. It is duplicate-free, meaning it does not contain multiple entries for
460/// the same column.
461#[derive(Clone, Debug)]
462pub struct LexOrdering {
463 /// Vector of sort expressions representing the lexicographical ordering.
464 exprs: Vec<PhysicalSortExpr>,
465 /// Set of expressions in the lexicographical ordering, used to ensure
466 /// that the ordering is duplicate-free. Note that the elements in this
467 /// set are the same underlying physical expressions as in `exprs`.
468 set: IndexSet<Arc<dyn PhysicalExpr>>,
469}
470
471impl LexOrdering {
472 /// Creates a new [`LexOrdering`] from the given vector of sort expressions.
473 /// If the vector is empty, returns `None`.
474 pub fn new(exprs: impl IntoIterator<Item = PhysicalSortExpr>) -> Option<Self> {
475 let exprs = exprs.into_iter();
476 let capacity = exprs.size_hint().0;
477 let mut candidate = Self {
478 // not valid yet; valid publicly-returned instance must be non-empty
479 exprs: Vec::with_capacity(capacity),
480 set: IndexSet::with_capacity(capacity),
481 };
482 for expr in exprs {
483 candidate.push(expr);
484 }
485 if candidate.exprs.is_empty() {
486 None
487 } else {
488 Some(candidate)
489 }
490 }
491
492 /// Appends an element to the back of the `LexOrdering`.
493 pub fn push(&mut self, sort_expr: PhysicalSortExpr) {
494 if self.set.insert(Arc::clone(&sort_expr.expr)) {
495 self.exprs.push(sort_expr);
496 }
497 }
498
499 /// Add all elements from `iter` to the `LexOrdering`.
500 pub fn extend(&mut self, sort_exprs: impl IntoIterator<Item = PhysicalSortExpr>) {
501 for sort_expr in sort_exprs {
502 self.push(sort_expr);
503 }
504 }
505
506 /// Returns the leading `PhysicalSortExpr` of the `LexOrdering`. Note that
507 /// this function does not return an `Option`, as a `LexOrdering` is always
508 /// non-degenerate (i.e. it contains at least one element).
509 pub fn first(&self) -> &PhysicalSortExpr {
510 // Can safely `unwrap` because `LexOrdering` is non-degenerate:
511 self.exprs.first().unwrap()
512 }
513
514 /// Returns the number of elements that can be stored in the `LexOrdering`
515 /// without reallocating.
516 pub fn capacity(&self) -> usize {
517 self.exprs.capacity()
518 }
519
520 /// Truncates the `LexOrdering`, keeping only the first `len` elements.
521 /// Returns `true` if truncation made a change, `false` otherwise. Negative
522 /// cases happen in two scenarios: (1) When `len` is greater than or equal
523 /// to the number of expressions inside this `LexOrdering`, making truncation
524 /// a no-op, or (2) when `len` is `0`, making truncation impossible.
525 pub fn truncate(&mut self, len: usize) -> bool {
526 if len == 0 || len >= self.exprs.len() {
527 return false;
528 }
529 for PhysicalSortExpr { expr, .. } in self.exprs[len..].iter() {
530 self.set.swap_remove(expr);
531 }
532 self.exprs.truncate(len);
533 true
534 }
535
536 /// Check if reversing this ordering would satisfy another ordering requirement.
537 ///
538 /// This supports **prefix matching**: if this ordering is `[A DESC, B ASC]`
539 /// and `other` is `[A ASC]`, reversing this gives `[A ASC, B DESC]`, which
540 /// satisfies `other` since `[A ASC]` is a prefix.
541 ///
542 /// # Arguments
543 /// * `other` - The ordering requirement to check against
544 ///
545 /// # Returns
546 /// `true` if reversing this ordering would satisfy `other`
547 ///
548 /// # Example
549 /// ```text
550 /// self: [number DESC, letter ASC]
551 /// other: [number ASC]
552 /// After reversing self: [number ASC, letter DESC] ✓ Prefix match!
553 /// ```
554 pub fn is_reverse(&self, other: &LexOrdering) -> bool {
555 let self_exprs = self.as_ref();
556 let other_exprs = other.as_ref();
557
558 if other_exprs.len() > self_exprs.len() {
559 return false;
560 }
561
562 other_exprs.iter().zip(self_exprs.iter()).all(|(req, cur)| {
563 req.expr.eq(&cur.expr) && is_reversed_sort_options(&req.options, &cur.options)
564 })
565 }
566
567 /// Returns the sort options for the given expression if one is defined in this `LexOrdering`.
568 pub fn get_sort_options(&self, expr: &dyn PhysicalExpr) -> Option<SortOptions> {
569 for e in self {
570 if e.expr.as_ref().dyn_eq(expr) {
571 return Some(e.options);
572 }
573 }
574
575 None
576 }
577}
578
579/// Check if two SortOptions represent reversed orderings.
580///
581/// Returns `true` if both `descending` and `nulls_first` are opposite.
582///
583/// # Example
584/// ```
585/// use arrow::compute::SortOptions;
586/// # use datafusion_physical_expr_common::sort_expr::is_reversed_sort_options;
587///
588/// let asc_nulls_last = SortOptions {
589/// descending: false,
590/// nulls_first: false,
591/// };
592/// let desc_nulls_first = SortOptions {
593/// descending: true,
594/// nulls_first: true,
595/// };
596///
597/// assert!(is_reversed_sort_options(&asc_nulls_last, &desc_nulls_first));
598/// assert!(is_reversed_sort_options(&desc_nulls_first, &asc_nulls_last));
599/// ```
600pub fn is_reversed_sort_options(lhs: &SortOptions, rhs: &SortOptions) -> bool {
601 lhs.descending != rhs.descending && lhs.nulls_first != rhs.nulls_first
602}
603
604impl PartialEq for LexOrdering {
605 fn eq(&self, other: &Self) -> bool {
606 let Self {
607 exprs,
608 set: _, // derived from `exprs`
609 } = self;
610 // PartialEq must be consistent with PartialOrd
611 exprs == &other.exprs
612 }
613}
614impl Eq for LexOrdering {}
615impl PartialOrd for LexOrdering {
616 /// There is a partial ordering among `LexOrdering` objects. For example, the
617 /// ordering `[a ASC]` is coarser (less) than ordering `[a ASC, b ASC]`.
618 /// If two orderings do not share a prefix, they are incomparable.
619 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
620 // PartialEq must be consistent with PartialOrd
621 self.exprs
622 .iter()
623 .zip(other.exprs.iter())
624 .all(|(lhs, rhs)| lhs == rhs)
625 .then(|| self.len().cmp(&other.len()))
626 }
627}
628
629impl<const N: usize> From<[PhysicalSortExpr; N]> for LexOrdering {
630 fn from(value: [PhysicalSortExpr; N]) -> Self {
631 // TODO: Replace this assertion with a condition on the generic parameter
632 // when Rust supports it.
633 assert!(N > 0);
634 Self::new(value)
635 .expect("A LexOrdering from non-empty array must be non-degenerate")
636 }
637}
638
639impl Deref for LexOrdering {
640 type Target = [PhysicalSortExpr];
641
642 fn deref(&self) -> &Self::Target {
643 self.exprs.as_slice()
644 }
645}
646
647impl Display for LexOrdering {
648 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
649 let mut first = true;
650 for sort_expr in &self.exprs {
651 if first {
652 first = false;
653 } else {
654 write!(f, ", ")?;
655 }
656 write!(f, "{sort_expr}")?;
657 }
658 Ok(())
659 }
660}
661
662impl IntoIterator for LexOrdering {
663 type Item = PhysicalSortExpr;
664 type IntoIter = IntoIter<Self::Item>;
665
666 fn into_iter(self) -> Self::IntoIter {
667 self.exprs.into_iter()
668 }
669}
670
671impl<'a> IntoIterator for &'a LexOrdering {
672 type Item = &'a PhysicalSortExpr;
673 type IntoIter = std::slice::Iter<'a, PhysicalSortExpr>;
674
675 fn into_iter(self) -> Self::IntoIter {
676 self.exprs.iter()
677 }
678}
679
680impl From<LexOrdering> for Vec<PhysicalSortExpr> {
681 fn from(ordering: LexOrdering) -> Self {
682 ordering.exprs
683 }
684}
685
686/// This object represents a lexicographical ordering requirement and contains
687/// a vector of `PhysicalSortRequirement` objects.
688///
689/// For example, a `vec![a Some(ASC), b None]` represents a lexicographical
690/// requirement that firsts imposes an ordering by column `a` in ascending
691/// order, then by column `b` in *any* (ascending or descending) order. The
692/// ordering is non-degenerate, meaning it contains at least one element, and
693/// it is duplicate-free, meaning it does not contain multiple entries for the
694/// same column.
695///
696/// Note that a `LexRequirement` need not enforce the uniqueness of its sort
697/// expressions after construction like a `LexOrdering` does, because it provides
698/// no mutation methods. If such methods become necessary, we will need to
699/// enforce uniqueness like the latter object.
700#[derive(Debug, Clone, PartialEq)]
701pub struct LexRequirement {
702 reqs: Vec<PhysicalSortRequirement>,
703}
704
705impl LexRequirement {
706 /// Creates a new [`LexRequirement`] from the given vector of sort expressions.
707 /// If the vector is empty, returns `None`.
708 pub fn new(reqs: impl IntoIterator<Item = PhysicalSortRequirement>) -> Option<Self> {
709 let (non_empty, requirements) = Self::construct(reqs);
710 non_empty.then_some(requirements)
711 }
712
713 /// Returns the leading `PhysicalSortRequirement` of the `LexRequirement`.
714 /// Note that this function does not return an `Option`, as a `LexRequirement`
715 /// is always non-degenerate (i.e. it contains at least one element).
716 pub fn first(&self) -> &PhysicalSortRequirement {
717 // Can safely `unwrap` because `LexRequirement` is non-degenerate:
718 self.reqs.first().unwrap()
719 }
720
721 /// Constructs a new `LexRequirement` from the given sort requirements w/o
722 /// enforcing non-degeneracy. This function is used internally and is not
723 /// meant (or safe) for external use.
724 fn construct(
725 reqs: impl IntoIterator<Item = PhysicalSortRequirement>,
726 ) -> (bool, Self) {
727 let reqs = reqs.into_iter();
728 let mut set = HashSet::with_capacity(reqs.size_hint().0);
729 let reqs = reqs
730 .filter_map(|r| set.insert(Arc::clone(&r.expr)).then_some(r))
731 .collect();
732 (!set.is_empty(), Self { reqs })
733 }
734}
735
736impl<const N: usize> From<[PhysicalSortRequirement; N]> for LexRequirement {
737 fn from(value: [PhysicalSortRequirement; N]) -> Self {
738 // TODO: Replace this assertion with a condition on the generic parameter
739 // when Rust supports it.
740 assert!(N > 0);
741 let (non_empty, requirement) = Self::construct(value);
742 debug_assert!(non_empty);
743 requirement
744 }
745}
746
747impl Deref for LexRequirement {
748 type Target = [PhysicalSortRequirement];
749
750 fn deref(&self) -> &Self::Target {
751 self.reqs.as_slice()
752 }
753}
754
755impl IntoIterator for LexRequirement {
756 type Item = PhysicalSortRequirement;
757 type IntoIter = IntoIter<Self::Item>;
758
759 fn into_iter(self) -> Self::IntoIter {
760 self.reqs.into_iter()
761 }
762}
763
764impl<'a> IntoIterator for &'a LexRequirement {
765 type Item = &'a PhysicalSortRequirement;
766 type IntoIter = std::slice::Iter<'a, PhysicalSortRequirement>;
767
768 fn into_iter(self) -> Self::IntoIter {
769 self.reqs.iter()
770 }
771}
772
773impl From<LexRequirement> for Vec<PhysicalSortRequirement> {
774 fn from(requirement: LexRequirement) -> Self {
775 requirement.reqs
776 }
777}
778
779// Cross-conversion utilities between `LexOrdering` and `LexRequirement`
780impl From<LexOrdering> for LexRequirement {
781 fn from(value: LexOrdering) -> Self {
782 // Can construct directly as `value` is non-degenerate:
783 let (non_empty, requirements) =
784 Self::construct(value.into_iter().map(Into::into));
785 debug_assert!(non_empty);
786 requirements
787 }
788}
789
790impl From<LexRequirement> for LexOrdering {
791 fn from(value: LexRequirement) -> Self {
792 // Can construct directly as `value` is non-degenerate
793 Self::new(value.into_iter().map(Into::into))
794 .expect("A LexOrdering from LexRequirement must be non-degenerate")
795 }
796}
797
798/// Represents a plan's input ordering requirements. Vector elements represent
799/// alternative ordering requirements in the order of preference. The list of
800/// alternatives can be either hard or soft, depending on whether the operator
801/// can work without an input ordering.
802///
803/// # Invariants
804///
805/// The following always hold true for a `OrderingRequirements`:
806///
807/// 1. It is non-degenerate, meaning it contains at least one ordering. The
808/// absence of an input ordering requirement is represented by a `None` value
809/// in `ExecutionPlan` APIs, which return an `Option<OrderingRequirements>`.
810#[derive(Debug, Clone, PartialEq)]
811pub enum OrderingRequirements {
812 /// The operator is not able to work without one of these requirements.
813 Hard(Vec<LexRequirement>),
814 /// The operator can benefit from these input orderings when available,
815 /// but can still work in the absence of any input ordering.
816 Soft(Vec<LexRequirement>),
817}
818
819impl OrderingRequirements {
820 /// Creates a new instance from the given alternatives. If an empty list of
821 /// alternatives are given, returns `None`.
822 pub fn new_alternatives(
823 alternatives: impl IntoIterator<Item = LexRequirement>,
824 soft: bool,
825 ) -> Option<Self> {
826 let alternatives = alternatives.into_iter().collect::<Vec<_>>();
827 (!alternatives.is_empty()).then(|| {
828 if soft {
829 Self::Soft(alternatives)
830 } else {
831 Self::Hard(alternatives)
832 }
833 })
834 }
835
836 /// Creates a new instance with a single hard requirement.
837 pub fn new(requirement: LexRequirement) -> Self {
838 Self::Hard(vec![requirement])
839 }
840
841 /// Creates a new instance with a single soft requirement.
842 pub fn new_soft(requirement: LexRequirement) -> Self {
843 Self::Soft(vec![requirement])
844 }
845
846 /// Adds an alternative requirement to the list of alternatives.
847 pub fn add_alternative(&mut self, requirement: LexRequirement) {
848 match self {
849 Self::Hard(alts) | Self::Soft(alts) => alts.push(requirement),
850 }
851 }
852
853 /// Returns the first (i.e. most preferred) `LexRequirement` among
854 /// alternative requirements.
855 pub fn into_single(self) -> LexRequirement {
856 match self {
857 Self::Hard(mut alts) | Self::Soft(mut alts) => alts.swap_remove(0),
858 }
859 }
860
861 /// Returns a reference to the first (i.e. most preferred) `LexRequirement`
862 /// among alternative requirements.
863 pub fn first(&self) -> &LexRequirement {
864 match self {
865 Self::Hard(alts) | Self::Soft(alts) => &alts[0],
866 }
867 }
868
869 /// Returns all alternatives as a vector of `LexRequirement` objects and a
870 /// boolean value indicating softness/hardness of the requirements.
871 pub fn into_alternatives(self) -> (Vec<LexRequirement>, bool) {
872 match self {
873 Self::Hard(alts) => (alts, false),
874 Self::Soft(alts) => (alts, true),
875 }
876 }
877}
878
879impl From<LexRequirement> for OrderingRequirements {
880 fn from(requirement: LexRequirement) -> Self {
881 Self::new(requirement)
882 }
883}
884
885impl From<LexOrdering> for OrderingRequirements {
886 fn from(ordering: LexOrdering) -> Self {
887 Self::new(ordering.into())
888 }
889}
890
891impl Deref for OrderingRequirements {
892 type Target = [LexRequirement];
893
894 fn deref(&self) -> &Self::Target {
895 match &self {
896 Self::Hard(alts) | Self::Soft(alts) => alts.as_slice(),
897 }
898 }
899}
900
901impl DerefMut for OrderingRequirements {
902 fn deref_mut(&mut self) -> &mut Self::Target {
903 match self {
904 Self::Hard(alts) | Self::Soft(alts) => alts.as_mut_slice(),
905 }
906 }
907}
908
909#[cfg(test)]
910mod tests {
911 use super::*;
912
913 #[test]
914 fn test_is_reversed_sort_options() {
915 // Test basic reversal: ASC NULLS LAST ↔ DESC NULLS FIRST
916 let asc_nulls_last = SortOptions {
917 descending: false,
918 nulls_first: false,
919 };
920 let desc_nulls_first = SortOptions {
921 descending: true,
922 nulls_first: true,
923 };
924 assert!(is_reversed_sort_options(&asc_nulls_last, &desc_nulls_first));
925 assert!(is_reversed_sort_options(&desc_nulls_first, &asc_nulls_last));
926
927 // Test another reversal: ASC NULLS FIRST ↔ DESC NULLS LAST
928 let asc_nulls_first = SortOptions {
929 descending: false,
930 nulls_first: true,
931 };
932 let desc_nulls_last = SortOptions {
933 descending: true,
934 nulls_first: false,
935 };
936 assert!(is_reversed_sort_options(&asc_nulls_first, &desc_nulls_last));
937 assert!(is_reversed_sort_options(&desc_nulls_last, &asc_nulls_first));
938
939 // Test non-reversal: same options
940 assert!(!is_reversed_sort_options(&asc_nulls_last, &asc_nulls_last));
941 assert!(!is_reversed_sort_options(
942 &desc_nulls_first,
943 &desc_nulls_first
944 ));
945
946 // Test non-reversal: only descending differs
947 assert!(!is_reversed_sort_options(&asc_nulls_last, &desc_nulls_last));
948 assert!(!is_reversed_sort_options(&desc_nulls_last, &asc_nulls_last));
949
950 // Test non-reversal: only nulls_first differs
951 assert!(!is_reversed_sort_options(&asc_nulls_last, &asc_nulls_first));
952 assert!(!is_reversed_sort_options(&asc_nulls_first, &asc_nulls_last));
953 }
954}