Skip to content
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

fix: Use rfc3339 to decode date from text #3411

Merged
merged 1 commit into from
Sep 2, 2024
Merged
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
31 changes: 25 additions & 6 deletions sqlx-postgres/src/types/chrono/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,22 +86,41 @@ impl<Tz: TimeZone> Encode<'_, Postgres> for DateTime<Tz> {

impl<'r> Decode<'r, Postgres> for DateTime<Local> {
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
let naive = <NaiveDateTime as Decode<Postgres>>::decode(value)?;
Ok(Local.from_utc_datetime(&naive))
let fixed = <DateTime<FixedOffset> as Decode<Postgres>>::decode(value)?;
Ok(Local.from_utc_datetime(&fixed.naive_utc()))
}
}

impl<'r> Decode<'r, Postgres> for DateTime<Utc> {
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
let naive = <NaiveDateTime as Decode<Postgres>>::decode(value)?;
Ok(Utc.from_utc_datetime(&naive))
let fixed = <DateTime<FixedOffset> as Decode<Postgres>>::decode(value)?;
Ok(Utc.from_utc_datetime(&fixed.naive_utc()))
}
}

impl<'r> Decode<'r, Postgres> for DateTime<FixedOffset> {
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
let naive = <NaiveDateTime as Decode<Postgres>>::decode(value)?;
Ok(Utc.fix().from_utc_datetime(&naive))
Ok(match value.format() {
PgValueFormat::Binary => {
let naive = <NaiveDateTime as Decode<Postgres>>::decode(value)?;
Utc.fix().from_utc_datetime(&naive)
}

PgValueFormat::Text => {
let s = value.as_str()?;
DateTime::parse_from_str(
s,
if s.contains('+') || s.contains('-') {
// Contains a time-zone specifier
// This is given for timestamptz for some reason
// Postgres already guarantees this to always be UTC
"%Y-%m-%d %H:%M:%S%.f%#z"
} else {
"%Y-%m-%d %H:%M:%S%.f"
},
)?
}
})
}
}

Expand Down