Skip to main content

uqa_sql/expr/
temporal_input.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Temporal context for analysis and worker execution. Guards restore the caller's clock, date order and interval input/output style on every exit.
8
9use std::{cell::Cell, marker::PhantomData};
10use uqa_core::{TemporalDateOrder, TemporalIntervalStyle};
11
12thread_local! {
13    static DATE_ORDER: Cell<TemporalDateOrder> = const { Cell::new(TemporalDateOrder::MonthDayYear) };
14    static INTERVAL_STYLE: Cell<TemporalIntervalStyle> = const { Cell::new(TemporalIntervalStyle::Postgres) };
15}
16
17#[must_use]
18pub fn temporal_interval_style() -> TemporalIntervalStyle {
19    INTERVAL_STYLE.with(Cell::get)
20}
21
22/// Restore the invoking thread's interval input/output style on every exit.
23pub struct IntervalStyleScope {
24    previous: TemporalIntervalStyle,
25    thread: PhantomData<std::rc::Rc<()>>,
26}
27
28impl IntervalStyleScope {
29    #[must_use]
30    pub fn enter(style: TemporalIntervalStyle) -> Self {
31        Self {
32            previous: INTERVAL_STYLE.with(|current| current.replace(style)),
33            thread: PhantomData,
34        }
35    }
36}
37
38impl Drop for IntervalStyleScope {
39    fn drop(&mut self) {
40        INTERVAL_STYLE.with(|current| current.set(self.previous));
41    }
42}
43
44#[must_use]
45pub fn temporal_date_order() -> TemporalDateOrder {
46    DATE_ORDER.with(Cell::get)
47}
48
49/// Restore the calling thread's date order when the input scope ends.
50pub struct DateOrderScope {
51    previous: TemporalDateOrder,
52    thread: PhantomData<std::rc::Rc<()>>,
53}
54
55impl DateOrderScope {
56    #[must_use]
57    pub fn enter(order: TemporalDateOrder) -> Self {
58        Self {
59            previous: DATE_ORDER.with(|current| current.replace(order)),
60            thread: PhantomData,
61        }
62    }
63}
64
65impl Drop for DateOrderScope {
66    fn drop(&mut self) {
67        DATE_ORDER.with(|current| current.set(self.previous));
68    }
69}
70
71/// A copyable context passed from a statement to its workers. Entering it reproduces every captured input exactly, including the absence of a transaction clock, so a thread never keeps an earlier statement's clock.
72#[derive(Clone, Copy)]
73pub struct TemporalInputContext {
74    pub transaction_clock_micros: Option<i64>,
75    pub date_order: TemporalDateOrder,
76    pub interval_style: TemporalIntervalStyle,
77}
78
79impl TemporalInputContext {
80    #[must_use]
81    pub fn current() -> Self {
82        Self {
83            transaction_clock_micros: super::transaction_clock_micros(),
84            date_order: temporal_date_order(),
85            interval_style: temporal_interval_style(),
86        }
87    }
88
89    #[must_use]
90    pub fn enter(self) -> TemporalInputScope {
91        TemporalInputScope {
92            _clock: super::TransactionClockScope::enter(self.transaction_clock_micros),
93            _order: DateOrderScope::enter(self.date_order),
94            _interval: IntervalStyleScope::enter(self.interval_style),
95        }
96    }
97}
98
99pub struct TemporalInputScope {
100    _clock: super::TransactionClockScope,
101    _order: DateOrderScope,
102    _interval: IntervalStyleScope,
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108    use uqa_core::Value;
109
110    #[test]
111    fn nested_input_contexts_restore_clocks_and_orders_after_failure() {
112        let _caller = TemporalInputContext {
113            transaction_clock_micros: Some(10),
114            date_order: TemporalDateOrder::DayMonthYear,
115            interval_style: TemporalIntervalStyle::SqlStandard,
116        }
117        .enter();
118        {
119            let _nested = TemporalInputContext {
120                transaction_clock_micros: Some(20),
121                date_order: TemporalDateOrder::YearMonthDay,
122                interval_style: TemporalIntervalStyle::Iso8601,
123            }
124            .enter();
125            assert_eq!(super::super::transaction_clock_micros(), Some(20));
126            assert_eq!(temporal_interval_style(), TemporalIntervalStyle::Iso8601);
127            assert!(crate::expr::cast_value(&Value::Str("13/02/2020".into()), "date").is_err());
128        }
129        assert_eq!(super::super::transaction_clock_micros(), Some(10));
130        assert_eq!(temporal_date_order(), TemporalDateOrder::DayMonthYear);
131        assert_eq!(
132            temporal_interval_style(),
133            TemporalIntervalStyle::SqlStandard
134        );
135        let Value::Temporal(value) =
136            crate::expr::cast_value(&Value::Str("02/03/2020".into()), "date").unwrap()
137        else {
138            panic!("date")
139        };
140        assert_eq!(value.to_sql_string(), "2020-03-02");
141    }
142
143    #[test]
144    fn a_context_without_a_clock_clears_the_thread_clock_until_it_ends() {
145        let _caller = TemporalInputContext {
146            transaction_clock_micros: Some(10),
147            date_order: TemporalDateOrder::DayMonthYear,
148            interval_style: TemporalIntervalStyle::SqlStandard,
149        }
150        .enter();
151        let captured = TemporalInputContext::current();
152        assert_eq!(captured.transaction_clock_micros, Some(10));
153        {
154            let _detached = TemporalInputContext {
155                transaction_clock_micros: None,
156                ..captured
157            }
158            .enter();
159            assert_eq!(super::super::transaction_clock_micros(), None);
160            assert!(super::super::transaction_timestamp_or_clock() > 1_700_000_000_000_000);
161            assert_eq!(
162                TemporalInputContext::current().transaction_clock_micros,
163                None
164            );
165            {
166                let _restored = captured.enter();
167                assert_eq!(super::super::transaction_clock_micros(), Some(10));
168            }
169            assert_eq!(super::super::transaction_clock_micros(), None);
170        }
171        assert_eq!(super::super::transaction_clock_micros(), Some(10));
172        std::thread::spawn(move || {
173            let _worker = TemporalInputContext {
174                transaction_clock_micros: None,
175                ..captured
176            }
177            .enter();
178            assert_eq!(super::super::transaction_clock_micros(), None);
179            assert_eq!(temporal_date_order(), TemporalDateOrder::DayMonthYear);
180        })
181        .join()
182        .unwrap();
183    }
184}