Skip to main content

datafusion_common/
partitioning.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::utils::compare_rows;
6use crate::{Result, ScalarValue, error::_plan_err};
7use arrow::compute::SortOptions;
8use std::cmp::Ordering;
9use std::fmt::{self, Display};
10
11/// A boundary between adjacent range partitions.
12///
13/// A split point is a tuple with one [`ScalarValue`] per partitioning
14/// expression. Split points are interpreted lexicographically according to the
15/// ordering of the range partitioning that owns them.
16///
17/// `N` split points define `N + 1` partitions:
18///
19/// ```text
20/// partition 0: key < split_points[0]
21/// partition 1: split_points[0] <= key < split_points[1]
22/// ...
23/// partition N - 1: split_points[N - 2] <= key < split_points[N - 1]
24/// partition N: split_points[N - 1] <= key
25/// ```
26///
27/// Values equal to split point `i` belong to partition `i + 1`, so interior
28/// partitions are lower-inclusive and upper-exclusive.
29#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
30pub struct SplitPoint {
31    values: Vec<ScalarValue>,
32}
33
34impl SplitPoint {
35    /// Creates a new split point from its tuple values.
36    pub fn new(values: Vec<ScalarValue>) -> Self {
37        Self { values }
38    }
39
40    /// Returns the tuple values for this split point.
41    pub fn values(&self) -> &[ScalarValue] {
42        &self.values
43    }
44}
45
46impl Display for SplitPoint {
47    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48        let values = self
49            .values
50            .iter()
51            .map(ToString::to_string)
52            .collect::<Vec<_>>()
53            .join(", ");
54        write!(f, "({values})")
55    }
56}
57
58/// Validates that split points match the ordering width and are strictly
59/// ordered according to the provided sort options.
60pub fn validate_range_split_points(
61    split_points: &[SplitPoint],
62    sort_options: &[SortOptions],
63) -> Result<()> {
64    let width = sort_options.len();
65    for (idx, split_point) in split_points.iter().enumerate() {
66        let split_point_width = split_point.values().len();
67        if split_point_width != width {
68            return _plan_err!(
69                "Range partitioning split point {idx} has width {split_point_width}, but ordering has width {width}"
70            );
71        }
72    }
73
74    for (idx, split_points) in split_points.windows(2).enumerate() {
75        if compare_rows(
76            split_points[0].values(),
77            split_points[1].values(),
78            sort_options,
79        )? != Ordering::Less
80        {
81            return _plan_err!(
82                "Range partitioning split points must be strictly ordered: split point {idx} ({}) must be less than split point {} ({})",
83                split_points[0],
84                idx + 1,
85                split_points[1]
86            );
87        }
88    }
89
90    Ok(())
91}