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

Upgrade to time 0.3 #1455

Merged
merged 2 commits into from Apr 14, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
151 changes: 9 additions & 142 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Expand Up @@ -137,7 +137,7 @@ sqlx-macros = { version = "0.5.10", path = "sqlx-macros", default-features = fal

[dev-dependencies]
anyhow = "1.0.52"
time_ = { version = "0.2.27", package = "time" }
time_ = { version = "0.3.2", package = "time" }
futures = "0.3.19"
env_logger = "0.8.4"
async-std = { version = "1.10.0", features = ["attributes"] }
Expand Down
2 changes: 1 addition & 1 deletion sqlx-core/Cargo.toml
Expand Up @@ -151,7 +151,7 @@ sha-1 = { version = "0.9.8", default-features = false, optional = true }
sha2 = { version = "0.9.8", default-features = false, optional = true }
sqlformat = "0.1.8"
thiserror = "1.0.30"
time = { version = "0.2.27", optional = true }
time = { version = "0.3.2", features = ["macros", "formatting", "parsing"], optional = true }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't #[serde(with = "time::serde::rfc3339")] (as described in this comment) require the serde-well-known feature flag? Since serializing with RFC3339 format is a very common use case, I guess adding serde-well-known would make sense...

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally you don't want to enable feature flags you don't strictly need. That would force that feature on for all crates that depend on SQLx.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense... but what is then the recommended way to read a timestamp from the database and put it into a DTO in RFC3339 format? Since the version of time that sqlx comes with doesn't support this (due to version and that feature flag), a user of sqlx has to use an intermediate "DatabaseDTO" with sqlx::types::time::OffsetDateTime for fetching from the database (using query_as), just to then convert it manually into an "ActualDTO" with time::OffsetDateTime (I did that with time::OffsetDateTime::from_unix_timestamp(db_dto.created_at.unix_timestamp()), but I'm not sure that's the best way). Only then the aforementioned way to serialize a timestamp using RFC3339 with with actually works. Or am I missing something?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's only an issue because SQLx is currently using a different version of time than you are. Otherwise sqlx::types::time::OffsetDateTime and time::OffsetDateTime should always refer to the same type.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

time::serde::rfc3339 exists since time v0.3.6, so it's not available in the version proposed in this PR (which means serde-well-known would only make sense when using >= 0.3.6 anyway; before that, there is no such feature flag).

I get that enabling too many features is not a good idea as it would impact lots of users. But what about going with a more recent version of time, i.e., >=0.3.6? That would make it easier for anyone trying to include timestamps in REST API responses :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

time::serde::rfc3339 exists since time v0.3.6, so it's not available in the version proposed in this PR

sqlx depending on 0.3.2 means versions >=0.3.2, <0.4.0 are allowed, so you're free to use features from newer patch versions of the time crate

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The version specified here is not restrictive and Cargo will automatically pull in the latest 0.3.x release if it's not in your Cargo.lock already when building your crate.

You should also specify time = { version = "0.3.6", features = ["serde-well-known"] } in your own dependencies to be certain of this.

tokio-stream = { version = "0.1.8", features = ["fs"], optional = true }
smallvec = "1.7.0"
url = { version = "2.2.2", default-features = false }
Expand Down
63 changes: 27 additions & 36 deletions sqlx-core/src/mysql/types/time.rs
@@ -1,8 +1,8 @@
use std::borrow::Cow;
use std::convert::TryFrom;

use byteorder::{ByteOrder, LittleEndian};
use bytes::Buf;
use time::macros::format_description;
use time::{Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset};

use crate::decode::Decode;
Expand Down Expand Up @@ -87,7 +87,7 @@ impl<'r> Decode<'r, MySql> for Time {
// are 0 then the length is 0 and no further data is send
// https://dev.mysql.com/doc/internals/en/binary-protocol-value.html
if len == 0 {
return Ok(Time::try_from_hms_micro(0, 0, 0, 0).unwrap());
return Ok(Time::MIDNIGHT);
}

// is negative : int<1>
Expand All @@ -101,21 +101,11 @@ impl<'r> Decode<'r, MySql> for Time {
decode_time(len - 5, buf)
}

MySqlValueFormat::Text => {
let s = value.as_str()?;

// If there are less than 9 digits after the decimal point
// We need to zero-pad
// TODO: Ask [time] to add a parse % for less-than-fixed-9 nanos

let s = if s.len() < 20 {
Cow::Owned(format!("{:0<19}", s))
} else {
Cow::Borrowed(s)
};

Time::parse(&*s, "%H:%M:%S.%N").map_err(Into::into)
}
MySqlValueFormat::Text => Time::parse(
value.as_str()?,
&format_description!("[hour]:[minute]:[second].[subsecond]"),
)
.map_err(Into::into),
}
}
}
Expand Down Expand Up @@ -148,7 +138,7 @@ impl<'r> Decode<'r, MySql> for Date {
}
MySqlValueFormat::Text => {
let s = value.as_str()?;
Date::parse(s, "%Y-%m-%d").map_err(Into::into)
Date::parse(s, &format_description!("[year]-[month]-[day]")).map_err(Into::into)
}
}
}
Expand Down Expand Up @@ -211,21 +201,22 @@ impl<'r> Decode<'r, MySql> for PrimitiveDateTime {
MySqlValueFormat::Text => {
let s = value.as_str()?;

// If there are less than 9 digits after the decimal point
// We need to zero-pad
// TODO: Ask [time] to add a parse % for less-than-fixed-9 nanos

let s = if s.len() < 31 {
if s.contains('.') {
Cow::Owned(format!("{:0<30}", s))
} else {
Cow::Owned(format!("{}.000000000", s))
}
// If there are no nanoseconds parse without them
if s.contains('.') {
PrimitiveDateTime::parse(
s,
&format_description!(
"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"
),
)
.map_err(Into::into)
} else {
Cow::Borrowed(s)
};

PrimitiveDateTime::parse(&*s, "%Y-%m-%d %H:%M:%S.%N").map_err(Into::into)
PrimitiveDateTime::parse(
s,
&format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"),
)
.map_err(Into::into)
}
}
}
}
Expand All @@ -237,7 +228,7 @@ fn encode_date(date: &Date, buf: &mut Vec<u8>) {
.unwrap_or_else(|_| panic!("Date out of range for Mysql: {}", date));

buf.extend_from_slice(&year.to_le_bytes());
buf.push(date.month());
buf.push(date.month().into());
buf.push(date.day());
}

Expand All @@ -247,9 +238,9 @@ fn decode_date(buf: &[u8]) -> Result<Option<Date>, BoxDynError> {
return Ok(None);
}

Date::try_from_ymd(
Date::from_calendar_date(
LittleEndian::read_u16(buf) as i32,
buf[2] as u8,
time::Month::try_from(buf[2] as u8)?,
buf[3] as u8,
)
.map_err(Into::into)
Expand Down Expand Up @@ -278,6 +269,6 @@ fn decode_time(len: u8, mut buf: &[u8]) -> Result<Time, BoxDynError> {
0
};

Time::try_from_hms_micro(hour, minute, seconds, micros as u32)
Time::from_hms_micro(hour, minute, seconds, micros as u32)
.map_err(|e| format!("Time out of range for MySQL: {}", e).into())
}