Skip to content

Commit 92e87f6

Browse files
João Deppermannmeta-codesync[bot]
authored andcommitted
Add ToSQL and TryFromRowField implementations for chrono::NaiveDate to support MySQL DATE columns.
Summary: This change enables using chrono::NaiveDate directly with MySQL DATE columns. Without this, we would get the following error ``` the trait bound `chrono::NaiveDate: sql_helpers::mysql_query::ToSQL` is not satisfied ``` Same for TryFromRowField Reviewed By: macisamuele Differential Revision: D85050903 fbshipit-source-id: 232d751f2d355ba83cfc8a120eae8a9b17dac3e8
1 parent 9f95d54 commit 92e87f6

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

shed/sql/mysql_client_traits/row_field.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
use std::fmt;
1212

13+
use chrono::NaiveDate;
1314
use chrono::NaiveDateTime;
1415
use mysql_common::value::Value;
1516

@@ -246,6 +247,13 @@ impl OptionalTryFromRowField for NaiveDateTime {
246247
}
247248
}
248249

250+
/// Use NaiveDate values in Rust along with DATE columns in MySQL.
251+
impl OptionalTryFromRowField for NaiveDate {
252+
fn try_from_opt(field: RowField) -> Result<Option<Self>, ValueError> {
253+
opt_try_from_rowfield(field)
254+
}
255+
}
256+
249257
#[cfg(test)]
250258
mod test {
251259
use super::*;
@@ -262,4 +270,16 @@ mod test {
262270
println!("ok");
263271
Ok(())
264272
}
273+
274+
#[test]
275+
fn test_naive_date() -> Result<(), ValueError> {
276+
assert_eq!(
277+
NaiveDate::from_ymd_opt(2022, 5, 30).unwrap(),
278+
<NaiveDate as TryFromRowField>::try_from(RowField::Bytes(
279+
"2022-05-30".as_bytes().to_vec()
280+
))
281+
.unwrap()
282+
);
283+
Ok(())
284+
}
265285
}

shed/sql/mysql_client_traits/to_sql.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
use std::borrow::Cow;
1212

13+
use chrono::NaiveDate;
1314
use chrono::NaiveDateTime;
1415
use mysql_common::value::convert::ToValue;
1516
use seq_macro::seq;
@@ -188,6 +189,17 @@ impl ToSQL for NaiveDateTime {
188189
}
189190
}
190191

192+
impl ToSQL for NaiveDate {
193+
fn to_sql_string(&self) -> Cow<str> {
194+
Cow::Owned(
195+
self.format("%Y-%m-%d")
196+
.to_string()
197+
.to_sql_string()
198+
.to_string(),
199+
)
200+
}
201+
}
202+
191203
#[cfg(test)]
192204
mod test {
193205
use super::*;
@@ -197,4 +209,10 @@ mod test {
197209
let value = NaiveDateTime::parse_from_str("2022-05-30T13:39:58.012345Z", "%+").unwrap();
198210
assert_eq!(value.to_sql_string(), "'2022-05-30 13:39:58.012345'");
199211
}
212+
213+
#[test]
214+
fn test_naive_date() {
215+
let value = NaiveDate::from_ymd_opt(2022, 5, 30).unwrap();
216+
assert_eq!(value.to_sql_string(), "'2022-05-30'");
217+
}
200218
}

0 commit comments

Comments
 (0)