Skip to main content

uqa_sql/expr/
range.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! `PostgreSQL` built-in range and multirange text carriers.
8
9use std::cmp::Ordering;
10
11use uqa_core::{
12    memory::{Produced, ProductionControl},
13    Value,
14};
15
16mod comparison;
17mod construction;
18pub use construction::{
19    multirange_from_ranges_with_operations, parse_multirange_with_operations,
20    parse_range_with_operations, range_bound_flags, range_from_bounds_with_operations,
21    RangeBoundsInput, RangeConstruction,
22};
23mod descriptor;
24pub use descriptor::RangeValueDescriptor;
25pub(crate) mod datum;
26pub use datum::{declared_multirange_datum_with_control, declared_range_datum_with_control};
27mod host;
28mod input;
29mod production;
30pub use host::{multirange_value_from_members_with_control, range_value_from_bounds_with_control};
31mod observation;
32mod relationships;
33mod semantics;
34pub(in crate::expr) mod subtype_distance;
35mod typed;
36pub use observation::RangeBoundValues;
37pub(super) use production::{
38    canonical_multirange_text_with_control, canonical_range_as_multirange_text_with_control,
39    canonical_range_text_with_control, multirange_from_produced_ranges,
40    parse_multirange_with_control, parse_range_with_control, range_from_values_with_control,
41};
42pub use typed::RangeComparisonValue;
43
44use semantics::RangeSemantics;
45
46use crate::ast::RangeSubtype;
47use crate::error::Result;
48use crate::SQLError;
49
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct CanonicalRange<I = RangeSubtype> {
52    subtype: I,
53    lower: Option<Value>,
54    upper: Option<Value>,
55    lower_inclusive: bool,
56    upper_inclusive: bool,
57    empty: bool,
58}
59
60impl CanonicalRange {
61    fn semantics(&self) -> &'static RangeSemantics {
62        RangeSemantics::native(self.subtype)
63    }
64
65    #[must_use]
66    pub const fn subtype(&self) -> RangeSubtype {
67        self.subtype
68    }
69}
70
71impl<I> CanonicalRange<I> {
72    #[must_use]
73    pub const fn identity(&self) -> &I {
74        &self.subtype
75    }
76
77    fn empty(subtype: I) -> Self {
78        Self {
79            subtype,
80            lower: None,
81            upper: None,
82            lower_inclusive: false,
83            upper_inclusive: false,
84            empty: true,
85        }
86    }
87
88    #[must_use]
89    pub const fn is_empty(&self) -> bool {
90        self.empty
91    }
92
93    #[must_use]
94    pub const fn lower_inclusive(&self) -> bool {
95        self.lower_inclusive
96    }
97
98    #[must_use]
99    pub const fn upper_inclusive(&self) -> bool {
100        self.upper_inclusive
101    }
102
103    #[must_use]
104    pub fn lower(&self) -> Option<&Value> {
105        self.lower.as_ref()
106    }
107
108    #[must_use]
109    pub fn upper(&self) -> Option<&Value> {
110        self.upper.as_ref()
111    }
112}
113
114impl CanonicalRange {
115    #[must_use]
116    pub fn overlaps(&self, other: &Self) -> bool {
117        self.overlaps_with_control(other, &ProductionControl::uncontrolled())
118            .expect("ordinary range overlap")
119    }
120
121    #[must_use]
122    pub fn adjacent(&self, other: &Self) -> bool {
123        self.adjacent_with_control(other, &ProductionControl::uncontrolled())
124            .expect("ordinary range adjacency")
125    }
126
127    #[must_use]
128    pub fn contains_range(&self, other: &Self) -> bool {
129        self.contains_range_with_control(other, &ProductionControl::uncontrolled())
130            .expect("ordinary range containment")
131    }
132
133    #[must_use]
134    pub fn contains_value(&self, value: &Value) -> bool {
135        self.contains_value_with_control(value, &ProductionControl::uncontrolled())
136            .expect("ordinary range element containment")
137    }
138
139    /// Smallest range containing both operands. Unlike union, `PostgreSQL`'s
140    /// `range_merge` also spans a gap between disjoint ranges.
141    #[must_use]
142    pub fn merge_cover(&self, other: &Self) -> Self {
143        self.merge_cover_with_control(other, &ProductionControl::uncontrolled())
144            .expect("ordinary range cover")
145            .into_uncontrolled()
146            .expect("ordinary range")
147    }
148
149    pub(super) fn to_text_with_control(
150        &self,
151        control: &ProductionControl<'_>,
152    ) -> Result<Produced<String>> {
153        production::range_text(self, control)
154    }
155
156    #[must_use]
157    pub fn to_text(&self) -> String {
158        production::range_text(self, &ProductionControl::uncontrolled())
159            .expect("ordinary range formatting")
160            .into_uncontrolled()
161            .expect("ordinary range text")
162    }
163}
164
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct CanonicalMultirange<I = RangeSubtype> {
167    subtype: I,
168    ranges: Vec<CanonicalRange<I>>,
169}
170
171impl<I> CanonicalMultirange<I> {
172    #[must_use]
173    pub const fn identity(&self) -> &I {
174        &self.subtype
175    }
176
177    #[must_use]
178    pub fn ranges(&self) -> &[CanonicalRange<I>] {
179        &self.ranges
180    }
181
182    #[must_use]
183    pub fn is_empty(&self) -> bool {
184        self.ranges.is_empty()
185    }
186}
187
188impl CanonicalMultirange {
189    #[must_use]
190    pub fn contains_range(&self, range: &CanonicalRange) -> bool {
191        range.subtype == self.subtype
192            && (range.empty || self.ranges.iter().any(|item| item.contains_range(range)))
193    }
194
195    #[must_use]
196    pub fn contains_multirange(&self, other: &Self) -> bool {
197        self.subtype == other.subtype && other.ranges.iter().all(|range| self.contains_range(range))
198    }
199
200    #[must_use]
201    pub fn overlaps_range(&self, range: &CanonicalRange) -> bool {
202        range.subtype == self.subtype && self.ranges.iter().any(|item| item.overlaps(range))
203    }
204
205    #[must_use]
206    pub fn overlaps_multirange(&self, other: &Self) -> bool {
207        self.subtype == other.subtype
208            && self
209                .ranges
210                .iter()
211                .any(|left| other.ranges.iter().any(|right| left.overlaps(right)))
212    }
213
214    #[must_use]
215    pub fn merge_cover(&self) -> CanonicalRange {
216        self.merge_cover_with_control(&ProductionControl::uncontrolled())
217            .expect("ordinary multirange cover")
218            .into_uncontrolled()
219            .expect("ordinary range")
220    }
221
222    pub(super) fn to_text_with_control(
223        &self,
224        control: &ProductionControl<'_>,
225    ) -> Result<Produced<String>> {
226        production::multirange_text(self, control)
227    }
228
229    #[must_use]
230    pub fn to_text(&self) -> String {
231        production::multirange_text(self, &ProductionControl::uncontrolled())
232            .expect("ordinary multirange formatting")
233            .into_uncontrolled()
234            .expect("ordinary multirange text")
235    }
236}
237
238pub fn parse_range(text: &str, subtype: RangeSubtype) -> Result<CanonicalRange> {
239    Ok(
240        production::parse_range_with_control(text, subtype, &ProductionControl::uncontrolled())?
241            .into_uncontrolled()
242            .expect("ordinary range"),
243    )
244}
245
246pub fn parse_multirange(text: &str, subtype: RangeSubtype) -> Result<CanonicalMultirange> {
247    Ok(production::parse_multirange_with_control(
248        text,
249        subtype,
250        &ProductionControl::uncontrolled(),
251    )?
252    .into_uncontrolled()
253    .expect("ordinary multirange"))
254}
255
256pub fn multirange_from_ranges(
257    subtype: RangeSubtype,
258    ranges: impl IntoIterator<Item = CanonicalRange>,
259) -> CanonicalMultirange {
260    production::normalize_ranges(ranges, subtype, &ProductionControl::uncontrolled(), None)
261        .expect("ordinary multirange normalization")
262        .into_uncontrolled()
263        .expect("ordinary multirange")
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn discrete_ranges_canonicalize_to_inclusive_exclusive_bounds() {
272        assert_eq!(
273            parse_range("(1,4]", RangeSubtype::Integer)
274                .unwrap()
275                .to_text(),
276            "[2,5)"
277        );
278        assert_eq!(
279            parse_range("[2024-01-01,2024-01-02]", RangeSubtype::Date)
280                .unwrap()
281                .to_text(),
282            "[2024-01-01,2024-01-03)"
283        );
284    }
285
286    #[test]
287    fn multiranges_merge_overlapping_and_adjacent_members() {
288        assert_eq!(
289            parse_multirange("{[10,12),[1,3),[3,5)}", RangeSubtype::Integer)
290                .unwrap()
291                .to_text(),
292            "{[1,5),[10,12)}"
293        );
294    }
295
296    #[test]
297    fn range_relationships_cover_temporal_constraint_checks() {
298        let left = parse_range("[1,3)", RangeSubtype::Integer).unwrap();
299        let right = parse_range("[3,5)", RangeSubtype::Integer).unwrap();
300        let coverage = multirange_from_ranges(RangeSubtype::Integer, [left, right]);
301        let child = parse_range("[2,4)", RangeSubtype::Integer).unwrap();
302        assert!(coverage.contains_range(&child));
303    }
304}