surrealdb/sql/
datetime.rs

1use crate::sql::duration::Duration;
2use crate::sql::strand::Strand;
3use crate::syn;
4use chrono::{DateTime, SecondsFormat, 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#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, Hash)]
18#[serde(rename = "$surrealdb::private::sql::Datetime")]
19#[revisioned(revision = 1)]
20pub struct Datetime(pub DateTime<Utc>);
21
22impl Default for Datetime {
23	fn default() -> Self {
24		Self(Utc::now())
25	}
26}
27
28impl From<DateTime<Utc>> for Datetime {
29	fn from(v: DateTime<Utc>) -> Self {
30		Self(v)
31	}
32}
33
34impl From<Datetime> for DateTime<Utc> {
35	fn from(x: Datetime) -> Self {
36		x.0
37	}
38}
39
40impl FromStr for Datetime {
41	type Err = ();
42	fn from_str(s: &str) -> Result<Self, Self::Err> {
43		Self::try_from(s)
44	}
45}
46
47impl TryFrom<String> for Datetime {
48	type Error = ();
49	fn try_from(v: String) -> Result<Self, Self::Error> {
50		Self::try_from(v.as_str())
51	}
52}
53
54impl TryFrom<Strand> for Datetime {
55	type Error = ();
56	fn try_from(v: Strand) -> Result<Self, Self::Error> {
57		Self::try_from(v.as_str())
58	}
59}
60
61impl TryFrom<&str> for Datetime {
62	type Error = ();
63	fn try_from(v: &str) -> Result<Self, Self::Error> {
64		match syn::datetime_raw(v) {
65			Ok(v) => Ok(v),
66			_ => Err(()),
67		}
68	}
69}
70
71impl Deref for Datetime {
72	type Target = DateTime<Utc>;
73	fn deref(&self) -> &Self::Target {
74		&self.0
75	}
76}
77
78impl Datetime {
79	/// Convert the Datetime to a raw String
80	pub fn to_raw(&self) -> String {
81		self.0.to_rfc3339_opts(SecondsFormat::AutoSi, true)
82	}
83}
84
85impl Display for Datetime {
86	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
87		Display::fmt(&quote_str(&self.to_raw()), f)
88	}
89}
90
91impl ops::Sub<Self> for Datetime {
92	type Output = Duration;
93	fn sub(self, other: Self) -> Duration {
94		match (self.0 - other.0).to_std() {
95			Ok(d) => Duration::from(d),
96			Err(_) => Duration::default(),
97		}
98	}
99}