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