Created
December 6, 2020 21:57
-
-
Save mbuczko/e1168b37b36a7367a14679de178263ed to your computer and use it in GitHub Desktop.
rust / (de)serialize DateTime to Sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rusqlite::{ToSql, types::{FromSql, FromSqlResult, ToSqlOutput, ValueRef}}; | |
use miniserde::{Deserialize, Serialize, de::Visitor, make_place, ser::Fragment}; | |
use miniserde::Result; | |
make_place!(Place); | |
#[derive(Serialize, Clone, Deserialize, Debug)] | |
pub struct DateTime( | |
pub time::OffsetDateTime | |
); | |
impl FromSql for DateTime { | |
fn column_result(value: ValueRef) -> FromSqlResult<Self> { | |
i64::column_result(value).map(|as_i64| { | |
DateTime(time::OffsetDateTime::from_unix_timestamp(as_i64)) | |
}) | |
} | |
} | |
impl ToSql for DateTime { | |
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> { | |
Ok(self.0.timestamp().into()) | |
} | |
} | |
impl Serialize for DateTime { | |
fn begin(&self) -> Fragment { | |
Fragment::I64(self.0.timestamp().into()) | |
} | |
} | |
impl Deserialize for DateTime { | |
fn begin(out: &mut Option<Self>) -> &mut dyn Visitor { | |
impl Visitor for Place<DateTime> { | |
fn negative(&mut self, n: i64) -> Result<()> { | |
self.out = Some(DateTime(time::OffsetDateTime::from_unix_timestamp(n))); | |
Ok(()) | |
} | |
} | |
Place::new(out) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment