Skip to content

Commit

Permalink
fix(mysql): implement type traits for chrono::DateTime<Local> (#1335)
Browse files Browse the repository at this point in the history
closes #1222
  • Loading branch information
abonander committed Jul 21, 2021
1 parent be189bd commit 8bcac03
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion sqlx-core/src/mysql/types/chrono.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::convert::TryFrom;

use bytes::Buf;
use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc};
use chrono::{DateTime, Datelike, Local, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc};

use crate::decode::Decode;
use crate::encode::{Encode, IsNull};
Expand All @@ -21,12 +21,14 @@ impl Type<MySql> for DateTime<Utc> {
}
}

/// Note: assumes the connection's `time_zone` is set to `+00:00` (UTC).
impl Encode<'_, MySql> for DateTime<Utc> {
fn encode_by_ref(&self, buf: &mut Vec<u8>) -> IsNull {
Encode::<MySql>::encode(&self.naive_utc(), buf)
}
}

/// Note: assumes the connection's `time_zone` is set to `+00:00` (UTC).
impl<'r> Decode<'r, MySql> for DateTime<Utc> {
fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
let naive: NaiveDateTime = Decode::<MySql>::decode(value)?;
Expand All @@ -35,6 +37,30 @@ impl<'r> Decode<'r, MySql> for DateTime<Utc> {
}
}

impl Type<MySql> for DateTime<Local> {
fn type_info() -> MySqlTypeInfo {
MySqlTypeInfo::binary(ColumnType::Timestamp)
}

fn compatible(ty: &MySqlTypeInfo) -> bool {
matches!(ty.r#type, ColumnType::Datetime | ColumnType::Timestamp)
}
}

/// Note: assumes the connection's `time_zone` is set to `+00:00` (UTC).
impl Encode<'_, MySql> for DateTime<Local> {
fn encode_by_ref(&self, buf: &mut Vec<u8>) -> IsNull {
Encode::<MySql>::encode(&self.naive_utc(), buf)
}
}

/// Note: assumes the connection's `time_zone` is set to `+00:00` (UTC).
impl<'r> Decode<'r, MySql> for DateTime<Local> {
fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
Ok(<DateTime<Utc> as Decode<'r, MySql>>::decode(value)?.with_timezone(&Local))
}
}

impl Type<MySql> for NaiveTime {
fn type_info() -> MySqlTypeInfo {
MySqlTypeInfo::binary(ColumnType::Time)
Expand Down

0 comments on commit 8bcac03

Please sign in to comment.