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