1use 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 static TRANSACTION_CLOCK: Cell<Option<i64>> = const { Cell::new(None) };
18}
19
20#[must_use]
22pub fn clock_timestamp_micros() -> i64 {
23 chrono::Utc::now().timestamp_micros()
24}
25
26#[must_use]
28pub fn transaction_clock_micros() -> Option<i64> {
29 TRANSACTION_CLOCK.get()
30}
31
32#[must_use]
34pub(crate) fn transaction_timestamp_or_clock() -> i64 {
35 transaction_clock_micros().unwrap_or_else(clock_timestamp_micros)
36}
37
38pub struct TransactionClockScope {
40 previous: Option<i64>,
41 _thread: PhantomData<Rc<()>>,
42}
43
44impl TransactionClockScope {
45 #[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_seconds: 0,
113 },
114 "localtime" => TemporalValue::Time {
115 micros: micros.rem_euclid(MICROS_PER_DAY),
116 },
117 "localtimestamp" => TemporalValue::Timestamp {
118 postgres_micros: (micros) - uqa_core::POSTGRES_EPOCH_MICROS,
119 },
120 "age" => {
121 return age_between(
122 &TemporalValue::Timestamp {
123 postgres_micros: (micros.div_euclid(MICROS_PER_DAY) * MICROS_PER_DAY)
124 - uqa_core::POSTGRES_EPOCH_MICROS,
125 },
126 &coerce_temporal(&args[0])?,
127 );
128 }
129 _ => TemporalValue::TimestampTz {
130 postgres_micros: (micros) - uqa_core::POSTGRES_EPOCH_MICROS,
131 },
132 };
133 Ok(Value::Temporal(value))
134 })())
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 #[test]
142 fn temporal_coercion_uses_the_transaction_clock() {
143 let _clock = TransactionClockScope::enter(90_123_456_789);
144 for (input, micros) in [
145 ("now", 90_123_456_789),
146 ("today", 86_400_000_000),
147 ("tomorrow", 172_800_000_000),
148 ("yesterday", 0),
149 ] {
150 assert_eq!(
151 coerce_temporal(&Value::Str(input.into())).unwrap(),
152 TemporalValue::Timestamp {
153 postgres_micros: (micros) - uqa_core::POSTGRES_EPOCH_MICROS
154 },
155 "{input}"
156 );
157 }
158 }
159
160 #[test]
161 fn temporal_comparisons_use_the_transaction_clock() {
162 use crate::expr::{compare_with_control, values_equal_with_control};
163 use uqa_core::memory::ProductionControl;
164 let _clock = TransactionClockScope::enter(90_123_456_789);
165 let control = ProductionControl::uncontrolled();
166 let now = Value::Str("now".into());
167 for temporal in [
168 TemporalValue::Date { days: 1 },
169 TemporalValue::Time {
170 micros: 3_723_456_789,
171 },
172 TemporalValue::TimeTz {
173 micros: 3_723_456_789,
174 offset_seconds: 0,
175 },
176 TemporalValue::Timestamp {
177 postgres_micros: (90_123_456_789) - uqa_core::POSTGRES_EPOCH_MICROS,
178 },
179 TemporalValue::TimestampTz {
180 postgres_micros: (90_123_456_789) - uqa_core::POSTGRES_EPOCH_MICROS,
181 },
182 ] {
183 let value = Value::Temporal(temporal);
184 for (left, right) in [(&value, &now), (&now, &value)] {
185 assert!(values_equal_with_control(left, right, &control).unwrap());
186 assert_eq!(
187 compare_with_control(left, right, &control).unwrap(),
188 std::cmp::Ordering::Equal
189 );
190 }
191 }
192 }
193
194 #[test]
195 fn temporal_range_bounds_use_the_transaction_clock() {
196 use crate::ast::RangeSubtype;
197 use crate::expr::parse_range;
198 let _clock = TransactionClockScope::enter(90_123_456_789);
199 for (kind, expected) in [
200 (
201 RangeSubtype::Timestamp,
202 TemporalValue::Timestamp {
203 postgres_micros: (90_123_456_789) - uqa_core::POSTGRES_EPOCH_MICROS,
204 },
205 ),
206 (
207 RangeSubtype::TimestampTz,
208 TemporalValue::TimestampTz {
209 postgres_micros: (90_123_456_789) - uqa_core::POSTGRES_EPOCH_MICROS,
210 },
211 ),
212 ] {
213 let range = parse_range("[now,now]", kind).unwrap();
214 assert_eq!(range.lower(), Some(&Value::Temporal(expected.clone())));
215 assert_eq!(range.upper(), Some(&Value::Temporal(expected)));
216 assert!(!range.is_empty());
217 }
218 let range = parse_range("[today,tomorrow)", RangeSubtype::Date).unwrap();
219 assert_eq!(
220 range.lower(),
221 Some(&Value::Temporal(TemporalValue::Date { days: 1 }))
222 );
223 assert_eq!(
224 range.upper(),
225 Some(&Value::Temporal(TemporalValue::Date { days: 2 }))
226 );
227 }
228
229 #[test]
230 fn transaction_clock_scopes_nest_and_restore() {
231 assert_eq!(transaction_clock_micros(), None);
232 {
233 let _outer = TransactionClockScope::enter(10);
234 assert_eq!(transaction_clock_micros(), Some(10));
235 assert_eq!(transaction_timestamp_or_clock(), 10);
236 {
237 let _inner = TransactionClockScope::enter(20);
238 assert_eq!(transaction_clock_micros(), Some(20));
239 }
240 assert_eq!(transaction_clock_micros(), Some(10));
241 }
242 assert_eq!(transaction_clock_micros(), None);
243 assert!(transaction_timestamp_or_clock() > 1_700_000_000_000_000);
244 }
245}