1mod arithmetic;
24pub mod codec;
25mod component;
26mod construct;
27mod format;
28mod parse;
29mod text;
30pub use text::{parse_metadata_millis, parse_rfc3339_millis};
31
32use crate::temporal::types::*;
33
34use std::cell::Cell;
35use std::cmp::Ordering;
36use std::fmt::{Display, Formatter};
37
38pub use ::time::{
40 Date, Duration as SignedDuration, Month, OffsetDateTime, PrimitiveDateTime as PlainDateTime,
41 Time, UtcOffset, Weekday,
42};
43pub(crate) mod types;
44
45use crate::Value;
46
47use arithmetic::between;
48pub use arithmetic::{arithmetic, truncate, TemporalArithmeticOp};
49pub use component::component;
50pub use construct::{construct, from_epoch, from_epoch_millis};
51pub use format::{format_date, format_datetime, format_local_datetime, format_local_time};
52pub use parse::{
53 parse_date, parse_datetime, parse_duration, parse_local_datetime, parse_local_time,
54};
55
56pub(crate) const NANOS_PER_SECOND: i128 = 1_000_000_000;
57pub(crate) const SECONDS_PER_DAY: i128 = 86_400;
58pub(crate) const NANOS_PER_DAY: i128 = NANOS_PER_SECOND * SECONDS_PER_DAY;
59pub(crate) const AVERAGE_DAYS_PER_MONTH: f64 = 30.436_875;
62
63#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct TemporalError(String);
67
68impl TemporalError {
69 pub(crate) fn new(message: impl Into<String>) -> Self {
70 Self(message.into())
71 }
72
73 pub fn message(&self) -> &str {
74 &self.0
75 }
76}
77
78impl Display for TemporalError {
79 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
80 f.write_str(&self.0)
81 }
82}
83
84impl std::error::Error for TemporalError {}
85
86impl From<TemporalError> for crate::HawDBError {
87 fn from(error: TemporalError) -> Self {
88 crate::HawDBError::Execution(error.0)
89 }
90}
91
92pub type TemporalResult<T> = std::result::Result<T, TemporalError>;
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
101pub struct Duration {
102 pub months: i64,
103 pub days: i64,
104 time: SignedDuration,
105}
106
107impl Duration {
108 pub fn new(months: i64, days: i64, time: SignedDuration) -> Option<Self> {
110 delta_from_nanos(time.whole_nanoseconds())?;
111 Some(Self { months, days, time })
112 }
113
114 pub const fn time(&self) -> SignedDuration {
115 self.time
116 }
117
118 pub fn from_parts(months: i64, days: i64, nanos: i128) -> Option<Self> {
120 Self::new(months, days, delta_from_nanos(nanos)?)
121 }
122
123 pub fn time_nanos(&self) -> i128 {
125 delta_nanos(self.time)
126 }
127
128 pub fn seconds(&self) -> i64 {
131 self.time_nanos().div_euclid(NANOS_PER_SECOND) as i64
132 }
133
134 pub fn nanos_of_second(&self) -> i64 {
136 self.time_nanos().rem_euclid(NANOS_PER_SECOND) as i64
137 }
138
139 pub fn checked_add(self, other: Self) -> Option<Self> {
140 Self::new(
141 self.months.checked_add(other.months)?,
142 self.days.checked_add(other.days)?,
143 delta_from_nanos(self.time_nanos().checked_add(other.time_nanos())?)?,
144 )
145 }
146
147 pub fn checked_neg(self) -> Option<Self> {
148 Self::new(
149 self.months.checked_neg()?,
150 self.days.checked_neg()?,
151 delta_from_nanos(-self.time_nanos())?,
152 )
153 }
154
155 pub fn checked_sub(self, other: Self) -> Option<Self> {
156 self.checked_add(other.checked_neg()?)
157 }
158}
159
160impl Display for Duration {
161 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
162 format::write_duration(f, self)
163 }
164}
165
166pub(crate) fn delta_nanos(delta: SignedDuration) -> i128 {
167 delta.whole_nanoseconds()
168}
169
170pub(crate) fn delta_from_nanos(nanos: i128) -> Option<SignedDuration> {
171 let limit = i128::from(i64::MAX) * 1_000_000;
173 (-limit..=limit)
174 .contains(&nanos)
175 .then(|| SignedDuration::nanoseconds_i128(nanos))
176}
177
178#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
180pub enum TemporalKind {
181 Date,
182 LocalTime,
183 LocalDateTime,
184 DateTime,
185}
186
187impl TemporalKind {
188 pub const fn function_name(self) -> &'static str {
189 match self {
190 Self::Date => "date",
191 Self::LocalTime => "localtime",
192 Self::LocalDateTime => "localdatetime",
193 Self::DateTime => "datetime",
194 }
195 }
196
197 pub const fn has_date(self) -> bool {
198 !matches!(self, Self::LocalTime)
199 }
200
201 pub const fn has_time(self) -> bool {
202 !matches!(self, Self::Date)
203 }
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
208pub enum TemporalFunction {
209 Construct(TemporalKind),
213 Duration,
215 DurationBetween,
217 DurationInMonths,
219 DurationInDays,
221 DurationInSeconds,
223 Truncate(TemporalKind),
225 DateTimeFromEpoch,
227 DateTimeFromEpochMillis,
229}
230
231const KINDS: [TemporalKind; 4] = [
232 TemporalKind::Date,
233 TemporalKind::LocalTime,
234 TemporalKind::LocalDateTime,
235 TemporalKind::DateTime,
236];
237
238impl TemporalFunction {
239 pub const ALL: [Self; 15] = [
241 Self::Construct(TemporalKind::Date),
242 Self::Construct(TemporalKind::LocalTime),
243 Self::Construct(TemporalKind::LocalDateTime),
244 Self::Construct(TemporalKind::DateTime),
245 Self::Duration,
246 Self::DurationBetween,
247 Self::DurationInMonths,
248 Self::DurationInDays,
249 Self::DurationInSeconds,
250 Self::Truncate(TemporalKind::Date),
251 Self::Truncate(TemporalKind::LocalTime),
252 Self::Truncate(TemporalKind::LocalDateTime),
253 Self::Truncate(TemporalKind::DateTime),
254 Self::DateTimeFromEpoch,
255 Self::DateTimeFromEpochMillis,
256 ];
257
258 pub fn is_namespace(name: &str) -> bool {
262 KINDS
263 .iter()
264 .any(|kind| name.eq_ignore_ascii_case(kind.function_name()))
265 || name.eq_ignore_ascii_case("duration")
266 }
267
268 pub fn from_name(namespace: &str, member: Option<&str>) -> Option<Self> {
270 Self::ALL.into_iter().find(|function| {
271 let (expected_namespace, expected_member) = function.name_parts();
272 namespace.eq_ignore_ascii_case(expected_namespace)
273 && match (member, expected_member) {
274 (None, None) => true,
275 (Some(member), Some(expected)) => member.eq_ignore_ascii_case(expected),
276 _ => false,
277 }
278 })
279 }
280
281 const fn name_parts(self) -> (&'static str, Option<&'static str>) {
282 match self {
283 Self::Construct(kind) => (kind.function_name(), None),
284 Self::Duration => ("duration", None),
285 Self::DurationBetween => ("duration", Some("between")),
286 Self::DurationInMonths => ("duration", Some("inMonths")),
287 Self::DurationInDays => ("duration", Some("inDays")),
288 Self::DurationInSeconds => ("duration", Some("inSeconds")),
289 Self::Truncate(kind) => (kind.function_name(), Some("truncate")),
290 Self::DateTimeFromEpoch => ("datetime", Some("fromepoch")),
291 Self::DateTimeFromEpochMillis => ("datetime", Some("fromepochmillis")),
292 }
293 }
294
295 pub fn function_name(self) -> String {
297 match self.name_parts() {
298 (namespace, None) => namespace.to_string(),
299 (namespace, Some(member)) => format!("{namespace}.{member}"),
300 }
301 }
302
303 pub const fn arity(self) -> (usize, usize) {
305 match self {
306 Self::Construct(_) => (0, 1),
307 Self::Duration | Self::DateTimeFromEpochMillis => (1, 1),
308 Self::DurationBetween
309 | Self::DurationInMonths
310 | Self::DurationInDays
311 | Self::DurationInSeconds
312 | Self::Truncate(_)
313 | Self::DateTimeFromEpoch => (2, 2),
314 }
315 }
316
317 pub const fn reads_clock(self, argument_count: usize) -> bool {
320 matches!(self, Self::Construct(_)) && argument_count == 0
321 }
322}
323
324pub fn evaluate(
327 function: TemporalFunction,
328 arguments: &[Value],
329 now: OffsetDateTime,
330) -> TemporalResult<Value> {
331 let (min, max) = function.arity();
332 if !(min..=max).contains(&arguments.len()) {
333 return Err(TemporalError::new(format!(
334 "{}() expects {} argument(s), got {}",
335 function.function_name(),
336 if min == max {
337 min.to_string()
338 } else {
339 format!("{min} or {max}")
340 },
341 arguments.len()
342 )));
343 }
344 if arguments.iter().any(|value| matches!(value, Value::Null)) {
345 return Ok(Value::Null);
346 }
347 match function {
348 TemporalFunction::Construct(kind) => {
349 let now = now.checked_to_offset(UtcOffset::UTC).ok_or_else(|| {
350 TemporalError::new("statement clock UTC datetime is out of range")
351 })?;
352 construct(kind, arguments.first(), now)
353 }
354 TemporalFunction::Duration => construct::duration(&arguments[0]),
355 TemporalFunction::DurationBetween => {
356 between(&arguments[0], &arguments[1], arithmetic::BetweenMode::Full)
357 }
358 TemporalFunction::DurationInMonths => between(
359 &arguments[0],
360 &arguments[1],
361 arithmetic::BetweenMode::Months,
362 ),
363 TemporalFunction::DurationInDays => {
364 between(&arguments[0], &arguments[1], arithmetic::BetweenMode::Days)
365 }
366 TemporalFunction::DurationInSeconds => between(
367 &arguments[0],
368 &arguments[1],
369 arithmetic::BetweenMode::Seconds,
370 ),
371 TemporalFunction::Truncate(kind) => {
372 let Value::String(unit) = &arguments[0] else {
373 return Err(TemporalError::new(format!(
374 "{}() unit must be a string",
375 function.function_name()
376 )));
377 };
378 truncate(kind, unit, &arguments[1])
379 }
380 TemporalFunction::DateTimeFromEpoch => match (&arguments[0], &arguments[1]) {
381 (Value::Int(seconds), Value::Int(nanos)) => from_epoch(*seconds, *nanos),
382 _ => Err(TemporalError::new(
383 "datetime.fromepoch() expects integer seconds and nanoseconds",
384 )),
385 },
386 TemporalFunction::DateTimeFromEpochMillis => match &arguments[0] {
387 Value::Int(millis) => from_epoch_millis(*millis),
388 _ => Err(TemporalError::new(
389 "datetime.fromepochmillis() expects integer milliseconds",
390 )),
391 },
392 }
393}
394
395pub const fn is_temporal(value: &Value) -> bool {
397 matches!(
398 value,
399 Value::Date(_)
400 | Value::LocalTime(_)
401 | Value::LocalDateTime(_)
402 | Value::DateTime(_)
403 | Value::Duration(_)
404 )
405}
406
407pub fn comparable_ordering(left: &Value, right: &Value) -> Option<Ordering> {
415 match (left, right) {
416 (Value::Date(left), Value::Date(right)) => Some(left.cmp(right)),
417 (Value::LocalTime(left), Value::LocalTime(right)) => Some(left.cmp(right)),
418 (Value::LocalDateTime(left), Value::LocalDateTime(right)) => Some(left.cmp(right)),
419 (Value::DateTime(left), Value::DateTime(right)) => Some(datetime_cmp(left, right)),
420 _ => None,
421 }
422}
423
424pub fn is_clock_reading_map(value: &Value) -> bool {
428 matches!(value, Value::Map(map)
429 if map.keys().all(|key| key.eq_ignore_ascii_case("timezone")))
430}
431
432pub const fn ordering_is_null(left: &Value, right: &Value) -> bool {
436 matches!((left, right), (Value::Duration(_), Value::Duration(_)))
437}
438
439pub fn datetime_cmp(left: &OffsetDateTime, right: &OffsetDateTime) -> Ordering {
442 left.cmp(right).then_with(|| {
443 left.offset()
444 .whole_seconds()
445 .cmp(&right.offset().whole_seconds())
446 })
447}
448
449pub const JSON_TAGS: [&str; 5] = [
455 "$date",
456 "$localtime",
457 "$localdatetime",
458 "$datetime",
459 "$duration",
460];
461
462pub const fn json_tag(value: &Value) -> Option<&'static str> {
464 Some(match value {
465 Value::Date(_) => JSON_TAGS[0],
466 Value::LocalTime(_) => JSON_TAGS[1],
467 Value::LocalDateTime(_) => JSON_TAGS[2],
468 Value::DateTime(_) => JSON_TAGS[3],
469 Value::Duration(_) => JSON_TAGS[4],
470 _ => return None,
471 })
472}
473
474pub fn from_json_tag(tag: &str, text: &str) -> Option<TemporalResult<Value>> {
477 Some(match tag {
478 "$date" => parse_date(text).map(Value::Date),
479 "$localtime" => parse_local_time(text).map(Value::LocalTime),
480 "$localdatetime" => parse_local_datetime(text).map(Value::LocalDateTime),
481 "$datetime" => parse_datetime(text).map(Value::DateTime),
482 "$duration" => parse_duration(text).map(Value::duration),
483 _ => return None,
484 })
485}
486
487thread_local! {
488 static STATEMENT_CLOCK: Cell<Option<OffsetDateTime>> = const { Cell::new(None) };
489}
490
491pub fn statement_now() -> OffsetDateTime {
494 STATEMENT_CLOCK.with(Cell::get).unwrap_or_else(system_now)
495}
496
497fn system_now() -> OffsetDateTime {
498 let nanos = crate::time::SystemTime::now()
499 .duration_since(crate::time::UNIX_EPOCH)
500 .map(|duration| duration.as_nanos().min(i64::MAX as u128) as i64)
501 .unwrap_or(0);
502 datetime_from_nanos(nanos)
503}
504
505pub fn with_statement_clock<R>(instant: OffsetDateTime, f: impl FnOnce() -> R) -> R {
511 struct Restore(Option<OffsetDateTime>);
512 impl Drop for Restore {
513 fn drop(&mut self) {
514 STATEMENT_CLOCK.with(|clock| clock.set(self.0));
515 }
516 }
517 let _restore = Restore(
518 STATEMENT_CLOCK.with(|clock| clock.replace(Some(instant.to_offset(UtcOffset::UTC)))),
519 );
520 f()
521}
522
523pub fn with_stable_statement_clock<R>(f: impl FnOnce() -> R) -> R {
526 if STATEMENT_CLOCK.with(Cell::get).is_some() {
527 return f();
528 }
529 with_statement_clock(system_now(), f)
530}
531
532pub fn pinned_statement_clock() -> Option<OffsetDateTime> {
536 STATEMENT_CLOCK.with(Cell::get)
537}
538
539pub fn with_optional_statement_clock<R>(
542 instant: Option<OffsetDateTime>,
543 f: impl FnOnce() -> R,
544) -> R {
545 match instant {
546 Some(instant) => with_statement_clock(instant, f),
547 None => f(),
548 }
549}
550
551#[cfg(test)]
552mod tests;