surrealpatch/core/src/sql/datetime.rs

101 lines
2 KiB
Rust
Raw Normal View History

use crate::sql::duration::Duration;
use crate::sql::strand::Strand;
use crate::syn;
use chrono::{DateTime, SecondsFormat, Utc};
use revision::revisioned;
2020-06-29 15:36:01 +00:00
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display, Formatter};
use std::ops;
use std::ops::Deref;
2020-06-29 15:36:01 +00:00
use std::str;
use std::str::FromStr;
2020-06-29 15:36:01 +00:00
use super::escape::quote_str;
2023-09-08 11:28:36 +00:00
pub(crate) const TOKEN: &str = "$surrealdb::private::sql::Datetime";
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, Hash)]
2023-04-29 15:58:22 +00:00
#[serde(rename = "$surrealdb::private::sql::Datetime")]
#[revisioned(revision = 1)]
#[non_exhaustive]
pub struct Datetime(pub DateTime<Utc>);
2020-06-29 15:36:01 +00:00
impl Default for Datetime {
fn default() -> Self {
Self(Utc::now())
2020-06-29 15:36:01 +00:00
}
}
impl From<DateTime<Utc>> for Datetime {
fn from(v: DateTime<Utc>) -> Self {
Self(v)
}
}
impl From<Datetime> for DateTime<Utc> {
fn from(x: Datetime) -> Self {
x.0
}
}
impl FromStr for Datetime {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl TryFrom<String> for Datetime {
type Error = ();
fn try_from(v: String) -> Result<Self, Self::Error> {
Self::try_from(v.as_str())
}
}
impl TryFrom<Strand> for Datetime {
type Error = ();
fn try_from(v: Strand) -> Result<Self, Self::Error> {
Self::try_from(v.as_str())
}
}
impl TryFrom<&str> for Datetime {
type Error = ();
fn try_from(v: &str) -> Result<Self, Self::Error> {
match syn::datetime_raw(v) {
Ok(v) => Ok(v),
_ => Err(()),
2021-03-29 15:43:37 +00:00
}
2020-06-29 15:36:01 +00:00
}
}
impl Deref for Datetime {
type Target = DateTime<Utc>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Datetime {
2022-10-19 09:55:19 +00:00
/// Convert the Datetime to a raw String
pub fn to_raw(&self) -> String {
self.0.to_rfc3339_opts(SecondsFormat::AutoSi, true)
}
}
impl Display for Datetime {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
2023-06-26 11:02:26 +00:00
Display::fmt(&quote_str(&self.to_raw()), f)
2021-03-29 15:43:37 +00:00
}
}
impl ops::Sub<Self> for Datetime {
type Output = Duration;
fn sub(self, other: Self) -> Duration {
match (self.0 - other.0).to_std() {
Ok(d) => Duration::from(d),
Err(_) => Duration::default(),
}
}
}