Skip to main content

uqa_sql/expr/
current_time.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! SQL current date/time values read from the owning execution context, and the transaction clock the thread's statement runs under.
8
9use std::cell::Cell;
10use std::marker::PhantomData;
11use std::rc::Rc;
12
13use super::{age_between, coerce_temporal, EvalContext, Result, SQLError, TemporalValue, Value};
14
15thread_local! {
16    /// The start of the transaction whose statement the current thread executes, in Unix microseconds, while a [`TransactionClockScope`] is entered.
17    static TRANSACTION_CLOCK: Cell<Option<i64>> = const { Cell::new(None) };
18}
19
20/// Read the platform wall clock as Unix microseconds.
21#[must_use]
22pub fn clock_timestamp_micros() -> i64 {
23    chrono::Utc::now().timestamp_micros()
24}
25
26/// The transaction start entered for the current thread, or `None` outside any statement.
27#[must_use]
28pub fn transaction_clock_micros() -> Option<i64> {
29    TRANSACTION_CLOCK.get()
30}
31
32/// The transaction start the special date and time inputs `now`, `today`, `tomorrow` and `yesterday` resolve against, as `GetCurrentTransactionStartTimestamp` supplies it to the input functions; an evaluation outside any statement reads the wall clock.
33#[must_use]
34pub(crate) fn transaction_timestamp_or_clock() -> i64 {
35    transaction_clock_micros().unwrap_or_else(clock_timestamp_micros)
36}
37
38/// Enters a transaction start for the current thread until it drops, restoring the clock entered before it. The engine enters its transaction timestamp at every statement boundary, and the parallel executor enters the dispatching thread's clock on each worker.
39pub struct TransactionClockScope {
40    previous: Option<i64>,
41    _thread: PhantomData<Rc<()>>,
42}
43
44impl TransactionClockScope {
45    /// Enter `micros` as the transaction start. Entering `None` runs the thread without a transaction clock, where evaluation reads the wall clock, as a worker does for work dispatched from a thread that had none.
46    #[must_use]
47    pub fn enter(micros: impl Into<Option<i64>>) -> Self {
48        Self {
49            previous: TRANSACTION_CLOCK.replace(micros.into()),
50            _thread: PhantomData,
51        }
52    }
53}
54
55impl Drop for TransactionClockScope {
56    fn drop(&mut self) {
57        TRANSACTION_CLOCK.set(self.previous);
58    }
59}
60
61pub(super) fn eval_current_time(
62    name: &str,
63    args: &[Value],
64    context: Option<&EvalContext<'_>>,
65) -> Option<Result<Value>> {
66    if !(matches!(
67        name,
68        "now"
69            | "transaction_timestamp"
70            | "statement_timestamp"
71            | "current_timestamp"
72            | "current_date"
73            | "current_time"
74            | "localtime"
75            | "localtimestamp"
76    ) || name == "age" && args.len() == 1)
77    {
78        return None;
79    }
80    Some((|| {
81        if name == "age" && matches!(args, [Value::Null]) {
82            return Ok(Value::Null);
83        }
84        if name != "age" && !args.is_empty() {
85            return Err(SQLError::BadArity {
86                name: name.into(),
87                expected: "0".into(),
88                actual: args.len(),
89            });
90        }
91        let statement = name == "statement_timestamp";
92        let micros = context
93            .and_then(|context| context.engine)
94            .and_then(|engine| {
95                if statement {
96                    engine.statement_timestamp_micros()
97                } else {
98                    engine.transaction_timestamp_micros()
99                }
100            })
101            .or_else(|| (!statement).then(transaction_clock_micros).flatten())
102            .unwrap_or_else(clock_timestamp_micros);
103        const MICROS_PER_DAY: i64 = 86_400_000_000;
104        let value = match name {
105            "current_date" => TemporalValue::Date {
106                days: i32::try_from(micros.div_euclid(MICROS_PER_DAY)).map_err(|_| {
107                    SQLError::Internal("current date exceeds its day carrier".into())
108                })?,
109            },
110            "current_time" => TemporalValue::TimeTz {
111                micros: micros.rem_euclid(MICROS_PER_DAY),
112                offset_minutes: 0,
113            },
114            "localtime" => TemporalValue::Time {
115                micros: micros.rem_euclid(MICROS_PER_DAY),
116            },
117            "localtimestamp" => TemporalValue::Timestamp { micros },
118            "age" => {
119                return age_between(
120                    &TemporalValue::Timestamp {
121                        micros: micros.div_euclid(MICROS_PER_DAY) * MICROS_PER_DAY,
122                    },
123                    &coerce_temporal(&args[0])?,
124                );
125            }
126            _ => TemporalValue::TimestampTz { micros },
127        };
128        Ok(Value::Temporal(value))
129    })())
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn temporal_coercion_uses_the_transaction_clock() {
138        let _clock = TransactionClockScope::enter(90_123_456_789);
139        for (input, micros) in [
140            ("now", 90_123_456_789),
141            ("today", 86_400_000_000),
142            ("tomorrow", 172_800_000_000),
143            ("yesterday", 0),
144        ] {
145            assert_eq!(
146                coerce_temporal(&Value::Str(input.into())).unwrap(),
147                TemporalValue::Timestamp { micros },
148                "{input}"
149            );
150        }
151    }
152
153    #[test]
154    fn temporal_comparisons_use_the_transaction_clock() {
155        use crate::expr::{compare_with_control, values_equal_with_control};
156        use uqa_core::memory::ProductionControl;
157        let _clock = TransactionClockScope::enter(90_123_456_789);
158        let control = ProductionControl::uncontrolled();
159        let now = Value::Str("now".into());
160        for temporal in [
161            TemporalValue::Date { days: 1 },
162            TemporalValue::Time {
163                micros: 3_723_456_789,
164            },
165            TemporalValue::TimeTz {
166                micros: 3_723_456_789,
167                offset_minutes: 0,
168            },
169            TemporalValue::Timestamp {
170                micros: 90_123_456_789,
171            },
172            TemporalValue::TimestampTz {
173                micros: 90_123_456_789,
174            },
175        ] {
176            let value = Value::Temporal(temporal);
177            for (left, right) in [(&value, &now), (&now, &value)] {
178                assert!(values_equal_with_control(left, right, &control).unwrap());
179                assert_eq!(
180                    compare_with_control(left, right, &control).unwrap(),
181                    std::cmp::Ordering::Equal
182                );
183            }
184        }
185    }
186
187    #[test]
188    fn temporal_range_bounds_use_the_transaction_clock() {
189        use crate::ast::RangeSubtype;
190        use crate::expr::parse_range;
191        let _clock = TransactionClockScope::enter(90_123_456_789);
192        for (kind, expected) in [
193            (
194                RangeSubtype::Timestamp,
195                TemporalValue::Timestamp {
196                    micros: 90_123_456_789,
197                },
198            ),
199            (
200                RangeSubtype::TimestampTz,
201                TemporalValue::TimestampTz {
202                    micros: 90_123_456_789,
203                },
204            ),
205        ] {
206            let range = parse_range("[now,now]", kind).unwrap();
207            assert_eq!(range.lower(), Some(&Value::Temporal(expected.clone())));
208            assert_eq!(range.upper(), Some(&Value::Temporal(expected)));
209            assert!(!range.is_empty());
210        }
211        let range = parse_range("[today,tomorrow)", RangeSubtype::Date).unwrap();
212        assert_eq!(
213            range.lower(),
214            Some(&Value::Temporal(TemporalValue::Date { days: 1 }))
215        );
216        assert_eq!(
217            range.upper(),
218            Some(&Value::Temporal(TemporalValue::Date { days: 2 }))
219        );
220    }
221
222    #[test]
223    fn transaction_clock_scopes_nest_and_restore() {
224        assert_eq!(transaction_clock_micros(), None);
225        {
226            let _outer = TransactionClockScope::enter(10);
227            assert_eq!(transaction_clock_micros(), Some(10));
228            assert_eq!(transaction_timestamp_or_clock(), 10);
229            {
230                let _inner = TransactionClockScope::enter(20);
231                assert_eq!(transaction_clock_micros(), Some(20));
232            }
233            assert_eq!(transaction_clock_micros(), Some(10));
234        }
235        assert_eq!(transaction_clock_micros(), None);
236        assert!(transaction_timestamp_or_clock() > 1_700_000_000_000_000);
237    }
238}