Skip to content

Chrono TimeDelta support #1238

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions postgres-protocol/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,27 @@ pub fn time_from_sql(mut buf: &[u8]) -> Result<i64, StdBox<dyn Error + Sync + Se
Ok(v)
}

/// Serializes an `INTERVAL` value.
///
/// The value should represent the number of microseconds.
#[inline]
pub fn interval_to_sql(v: i128, buf: &mut BytesMut) {
buf.put_i128(v);
}

/// Deserializes an `INTERVAL` value.
///
/// The value represents the number of microseconds.
#[inline]
pub fn interval_from_sql(mut buf: &[u8]) -> Result<i128, StdBox<dyn Error + Sync + Send>> {
let v = buf.read_i128::<BigEndian>()?;
if !buf.is_empty() {
return Err("invalid message length: interval not drained".into());
}
Ok(v)
}


/// Serializes a `MACADDR` value.
#[inline]
pub fn macaddr_to_sql(v: [u8; 6], buf: &mut BytesMut) {
Expand Down
29 changes: 28 additions & 1 deletion postgres-types/src/chrono_04.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use bytes::BytesMut;
use chrono_04::{
DateTime, Duration, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc,
DateTime, Duration, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeDelta,
TimeZone, Utc,
};
use postgres_protocol::types;
use std::error::Error;
Expand Down Expand Up @@ -158,3 +159,29 @@ impl ToSql for NaiveTime {
accepts!(TIME);
to_sql_checked!();
}

impl<'a> FromSql<'a> for TimeDelta {
fn from_sql(_: &Type, raw: &[u8]) -> Result<TimeDelta, Box<dyn Error + Sync + Send>> {
let usec = types::interval_from_sql(raw)?;
if usec > i128::from(i64::max_value()) || jd < i128::from(i64::min_value()) {
return Err("value too large to transmit".into());
}
Ok(TimeDelta::microseconds(usec as i64))
}

accepts!(INTERVAL);
}

impl ToSql for TimeDelta {
fn to_sql(&self, _: &Type, w: &mut BytesMut) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
let usec = match self.num_microseconds() {
Some(usec) => usec,
None => return Err("value too large to transmit".into()),
};
types::interval_to_sql(i128::from(usec), w);
Ok(IsNull::No)
}

accepts!(INTERVAL);
to_sql_checked!();
}