surrealdb_core/sql/
datetime.rs1use crate::sql::duration::Duration;
2use crate::sql::strand::Strand;
3use crate::syn;
4use chrono::{offset::LocalResult, DateTime, SecondsFormat, TimeZone, Utc};
5use revision::revisioned;
6use serde::{Deserialize, Serialize};
7use std::fmt::{self, Display, Formatter};
8use std::ops;
9use std::ops::Deref;
10use std::str;
11use std::str::FromStr;
12
13use super::escape::quote_str;
14
15pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Datetime";
16
17#[revisioned(revision = 1)]
18#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, Hash)]
19#[serde(rename = "$surrealdb::private::sql::Datetime")]
20#[non_exhaustive]
21pub struct Datetime(pub DateTime<Utc>);
22
23impl Default for Datetime {
24 fn default() -> Self {
25 Self(Utc::now())
26 }
27}
28
29impl From<DateTime<Utc>> for Datetime {
30 fn from(v: DateTime<Utc>) -> Self {
31 Self(v)
32 }
33}
34
35impl From<Datetime> for DateTime<Utc> {
36 fn from(x: Datetime) -> Self {
37 x.0
38 }
39}
40
41impl FromStr for Datetime {
42 type Err = ();
43 fn from_str(s: &str) -> Result<Self, Self::Err> {
44 Self::try_from(s)
45 }
46}
47
48impl TryFrom<String> for Datetime {
49 type Error = ();
50 fn try_from(v: String) -> Result<Self, Self::Error> {
51 Self::try_from(v.as_str())
52 }
53}
54
55impl TryFrom<Strand> for Datetime {
56 type Error = ();
57 fn try_from(v: Strand) -> Result<Self, Self::Error> {
58 Self::try_from(v.as_str())
59 }
60}
61
62impl TryFrom<&str> for Datetime {
63 type Error = ();
64 fn try_from(v: &str) -> Result<Self, Self::Error> {
65 match syn::datetime_raw(v) {
66 Ok(v) => Ok(v),
67 _ => Err(()),
68 }
69 }
70}
71
72impl TryFrom<(i64, u32)> for Datetime {
73 type Error = ();
74 fn try_from(v: (i64, u32)) -> Result<Self, Self::Error> {
75 match Utc.timestamp_opt(v.0, v.1) {
76 LocalResult::Single(v) => Ok(Self(v)),
77 _ => Err(()),
78 }
79 }
80}
81
82impl Deref for Datetime {
83 type Target = DateTime<Utc>;
84 fn deref(&self) -> &Self::Target {
85 &self.0
86 }
87}
88
89impl Datetime {
90 pub fn to_raw(&self) -> String {
92 self.0.to_rfc3339_opts(SecondsFormat::AutoSi, true)
93 }
94}
95
96impl Display for Datetime {
97 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
98 write!(f, "d{}", "e_str(&self.to_raw()))
99 }
100}
101
102impl ops::Sub<Self> for Datetime {
103 type Output = Duration;
104 fn sub(self, other: Self) -> Duration {
105 match (self.0 - other.0).to_std() {
106 Ok(d) => Duration::from(d),
107 Err(_) => Duration::default(),
108 }
109 }
110}