From bdb9823b07bc9b8964ec0d03365f85f83c8b6ee6 Mon Sep 17 00:00:00 2001 From: gwenn Date: Mon, 22 Feb 2016 20:36:49 +0100 Subject: [PATCH 01/17] Add From/ToSql impl. for chrono types. --- Cargo.toml | 1 + src/types/chrono.rs | 267 +++++++++++++++++++++++++++++++++ src/{types.rs => types/mod.rs} | 3 + 3 files changed, 271 insertions(+) create mode 100644 src/types/chrono.rs rename src/{types.rs => types/mod.rs} (99%) diff --git a/Cargo.toml b/Cargo.toml index 3555180..471995d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ trace = [] time = "~0.1.0" bitflags = "~0.1" libc = "~0.2" +chrono = { version = "~0.2", optional = true } [dev-dependencies] tempdir = "~0.3.4" diff --git a/src/types/chrono.rs b/src/types/chrono.rs new file mode 100644 index 0000000..9dbacfe --- /dev/null +++ b/src/types/chrono.rs @@ -0,0 +1,267 @@ +//! Convert most of the [Time Strings](http://sqlite.org/lang_datefunc.html) to chrono types. +extern crate chrono; + +use std::error; +use self::chrono::{NaiveDate, NaiveTime, NaiveDateTime, DateTime, TimeZone, UTC, Local}; +use libc::c_int; + +use {Error, Result}; +use types::{FromSql, ToSql}; + +use ffi; +use ffi::sqlite3_stmt; +use ffi::sqlite3_column_type; + +const JULIAN_DAY: f64 = 2440587.5; // 1970-01-01 00:00:00 is JD 2440587.5 +const DAY_IN_SECONDS: f64 = 86400.0; +const JULIAN_DAY_GREGORIAN: f64 = 1721424.5; // Jan 1, 1 proleptic Gregorian calendar + +/// ISO 8601 calendar date without timezone => "YYYY-MM-DD" +impl ToSql for NaiveDate { + unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { + let date_str = self.format("%Y-%m-%d").to_string(); + date_str.bind_parameter(stmt, col) + } +} + +/// "YYYY-MM-DD" or Julian Day => ISO 8601 calendar date without timezone. +impl FromSql for NaiveDate { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { + match sqlite3_column_type(stmt, col) { + ffi::SQLITE_TEXT => { + let s = try!(String::column_result(stmt, col)); + match NaiveDate::parse_from_str(&s, "%Y-%m-%d") { + Ok(dt) => Ok(dt), + Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), + } + } + ffi::SQLITE_FLOAT => { + // if column affinity is REAL and an integer/unix timestamp is inserted => unexpected result + let mut jd = ffi::sqlite3_column_double(stmt, col); + jd -= JULIAN_DAY_GREGORIAN; + if jd < i32::min_value() as f64 || jd > i32::max_value() as f64 { + let err: Box = "out-of-range date".into(); + return Err(Error::FromSqlConversionFailure(err)); + } + match NaiveDate::from_num_days_from_ce_opt(jd as i32) { + Some(dt) => Ok(dt), + None => { + let err: Box = "out-of-range date".into(); + Err(Error::FromSqlConversionFailure(err)) + } + } + } + _ => Err(Error::InvalidColumnType), + } + } + + unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { + let sqlite_type = sqlite3_column_type(stmt, col); + sqlite_type == ffi::SQLITE_TEXT || sqlite_type == ffi::SQLITE_FLOAT + } +} + +/// ISO 8601 time without timezone => "HH:MM:SS.SSS" +impl ToSql for NaiveTime { + unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { + let date_str = self.format("%H:%M:%S.3f").to_string(); + date_str.bind_parameter(stmt, col) + } +} + +/// "HH:MM"/"HH:MM:SS"/"HH:MM:SS.SSS" => ISO 8601 time without timezone. +impl FromSql for NaiveTime { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { + match sqlite3_column_type(stmt, col) { + ffi::SQLITE_TEXT => { + let s = try!(String::column_result(stmt, col)); + let fmt = match s.len() { + 5 => "%H:%M", + 8 => "%H:%M:%S", + _ => "%H:%M:%S%.3f", + }; + match NaiveTime::parse_from_str(&s, fmt) { + Ok(dt) => Ok(dt), + Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), + } + } + _ => Err(Error::InvalidColumnType), + } + } + + unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { + sqlite3_column_type(stmt, col) == ffi::SQLITE_TEXT + } +} + +/// ISO 8601 combined date and time without timezone => "YYYY-MM-DD HH:MM:SS.SSS" +impl ToSql for NaiveDateTime { + unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { + let date_str = self.format("%Y-%m-%d %H:%M:%S%.3f").to_string(); + date_str.bind_parameter(stmt, col) + } +} + +/// "YYYY-MM-DD HH:MM"/"YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS"/ Julian Day / Unix Time => ISO 8601 combined date and time without timezone. +/// ("YYYY-MM-DDTHH:MM"/"YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported) +impl FromSql for NaiveDateTime { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { + match sqlite3_column_type(stmt, col) { + ffi::SQLITE_TEXT => { + let s = try!(String::column_result(stmt, col)); + let fmt = match s.len() { + 16 => { + match s.as_bytes()[10] { + b'T' => "%Y-%m-%dT%H:%M", + _ => "%Y-%m-%d %H:%M", + } + } + 19 => { + match s.as_bytes()[10] { + b'T' => "%Y-%m-%dT%H:%M:%S", + _ => "%Y-%m-%d %H:%M:%S", + } + } + _ => { + match s.as_bytes()[10] { + b'T' => "%Y-%m-%dT%H:%M:%S%.3f", + _ => "%Y-%m-%d %H:%M:%S%.3f", + } + } + }; + match NaiveDateTime::parse_from_str(&s, fmt) { + Ok(dt) => Ok(dt), + Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), + } + } + ffi::SQLITE_INTEGER => { + match NaiveDateTime::from_timestamp_opt(ffi::sqlite3_column_int64(stmt, col), 0) { + Some(dt) => Ok(dt), + None => { + let err: Box = "out-of-range number of seconds" + .into(); + Err(Error::FromSqlConversionFailure(err)) + } + } + } + ffi::SQLITE_FLOAT => { + // if column affinity is REAL and an integer/unix timestamp is inserted => unexpected result + let mut jd = ffi::sqlite3_column_double(stmt, col); + jd -= JULIAN_DAY; + jd *= DAY_IN_SECONDS; + let ns = jd.fract() * 10f64.powi(9); + match NaiveDateTime::from_timestamp_opt(jd as i64, ns as u32) { + Some(dt) => Ok(dt), + None => { + let err: Box = "out-of-range number of \ + seconds and/or invalid \ + nanosecond" + .into(); + Err(Error::FromSqlConversionFailure(err)) + } + } + } + _ => Err(Error::InvalidColumnType), + } + } + + unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { + let sqlite_type = sqlite3_column_type(stmt, col); + sqlite_type == ffi::SQLITE_TEXT || sqlite_type == ffi::SQLITE_INTEGER || + sqlite_type == ffi::SQLITE_FLOAT + } +} + +/// ISO 8601 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM" +impl ToSql for DateTime { + unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { + let date_str = self.format("%Y-%m-%dT%H:%M:%S%.3f%:z").to_string(); + date_str.bind_parameter(stmt, col) + } +} + +/// "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM"/"YYYY-MM-DD HH:MM"/"YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS"/ Julian Day / Unix Time => ISO 8601 date and time with time zone. +/// ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM"/"YYYY-MM-DDTHH:MM"/"YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported) +/// When the timezone is not specified, UTC is used. +impl FromSql for DateTime { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result> { + match sqlite3_column_type(stmt, col) { + ffi::SQLITE_TEXT => { + let s = try!(String::column_result(stmt, col)); + if s.len() > 23 { + let fmt = if s.as_bytes()[10] == b'T' { + "%Y-%m-%dT%H:%M:%S%.3f%:z" + } else { + "%Y-%m-%d %H:%M:%S%.3f%:z" + }; + match UTC.datetime_from_str(fmt, &s) { + Ok(dt) => Ok(dt), + Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), + } + } else { + NaiveDateTime::column_result(stmt, col).map(|dt| UTC.from_utc_datetime(&dt)) + } + } + ffi::SQLITE_INTEGER => { + NaiveDateTime::column_result(stmt, col).map(|dt| UTC.from_utc_datetime(&dt)) + } + ffi::SQLITE_FLOAT => { + NaiveDateTime::column_result(stmt, col).map(|dt| UTC.from_utc_datetime(&dt)) + } + _ => Err(Error::InvalidColumnType), + } + } + + unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { + NaiveDateTime::column_has_valid_sqlite_type(stmt, col) + } +} + + +/// ISO 8601 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM" +impl ToSql for DateTime { + unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { + let date_str = self.format("%Y-%m-%dT%H:%M:%S%.3f%:z").to_string(); + date_str.bind_parameter(stmt, col) + } +} + +/// "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM"/"YYYY-MM-DD HH:MM"/"YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS"/ Julian Day / Unix Time => ISO 8601 date and time with time zone. +/// ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM"/"YYYY-MM-DDTHH:MM"/"YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported) +/// When the timezone is not specified, Local is used. +impl FromSql for DateTime { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result> { + match sqlite3_column_type(stmt, col) { + ffi::SQLITE_TEXT => { + let s = try!(String::column_result(stmt, col)); + if s.len() > 23 { + let fmt = if s.as_bytes()[10] == b'T' { + "%Y-%m-%dT%H:%M:%S%.3f%:z" + } else { + "%Y-%m-%d %H:%M:%S%.3f%:z" + }; + match Local.datetime_from_str(fmt, &s) { + Ok(dt) => Ok(dt), + Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), + } + } else { + NaiveDateTime::column_result(stmt, col).map(|dt| Local.from_utc_datetime(&dt)) + } + } + ffi::SQLITE_INTEGER => { + NaiveDateTime::column_result(stmt, col).map(|dt| Local.from_utc_datetime(&dt)) + } + ffi::SQLITE_FLOAT => { + NaiveDateTime::column_result(stmt, col).map(|dt| Local.from_utc_datetime(&dt)) + } + _ => Err(Error::InvalidColumnType), + } + } + + unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { + NaiveDateTime::column_has_valid_sqlite_type(stmt, col) + } +} + +// struct UnixTime(NaiveDateTime); +// struct JulianTime(NaiveDateTime) diff --git a/src/types.rs b/src/types/mod.rs similarity index 99% rename from src/types.rs rename to src/types/mod.rs index c458e01..3f33c85 100644 --- a/src/types.rs +++ b/src/types/mod.rs @@ -66,6 +66,9 @@ pub use ffi::sqlite3_column_type; pub use ffi::{SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, SQLITE_NULL}; +#[cfg(feature = "chrono")] +mod chrono; + const SQLITE_DATETIME_FMT: &'static str = "%Y-%m-%d %H:%M:%S"; /// A trait for types that can be converted into SQLite values. From 33bc6edb4a62b961f493abb20135117b2a1a2df0 Mon Sep 17 00:00:00 2001 From: gwenn Date: Tue, 23 Feb 2016 18:18:56 +0100 Subject: [PATCH 02/17] Test From/ToSQL for chrono types. --- src/types/chrono.rs | 125 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 120 insertions(+), 5 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 9dbacfe..41dd024 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -64,7 +64,7 @@ impl FromSql for NaiveDate { /// ISO 8601 time without timezone => "HH:MM:SS.SSS" impl ToSql for NaiveTime { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let date_str = self.format("%H:%M:%S.3f").to_string(); + let date_str = self.format("%H:%M:%S%.3f").to_string(); date_str.bind_parameter(stmt, col) } } @@ -175,7 +175,7 @@ impl FromSql for NaiveDateTime { /// ISO 8601 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM" impl ToSql for DateTime { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let date_str = self.format("%Y-%m-%dT%H:%M:%S%.3f%:z").to_string(); + let date_str = self.format("%Y-%m-%d %H:%M:%S%.3f%:z").to_string(); date_str.bind_parameter(stmt, col) } } @@ -194,7 +194,7 @@ impl FromSql for DateTime { } else { "%Y-%m-%d %H:%M:%S%.3f%:z" }; - match UTC.datetime_from_str(fmt, &s) { + match UTC.datetime_from_str(&s, fmt) { Ok(dt) => Ok(dt), Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), } @@ -221,7 +221,7 @@ impl FromSql for DateTime { /// ISO 8601 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM" impl ToSql for DateTime { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let date_str = self.format("%Y-%m-%dT%H:%M:%S%.3f%:z").to_string(); + let date_str = self.format("%Y-%m-%d %H:%M:%S%.3f%:z").to_string(); date_str.bind_parameter(stmt, col) } } @@ -240,7 +240,7 @@ impl FromSql for DateTime { } else { "%Y-%m-%d %H:%M:%S%.3f%:z" }; - match Local.datetime_from_str(fmt, &s) { + match Local.datetime_from_str(&s, fmt) { Ok(dt) => Ok(dt), Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), } @@ -265,3 +265,118 @@ impl FromSql for DateTime { // struct UnixTime(NaiveDateTime); // struct JulianTime(NaiveDateTime) + +#[cfg(test)] +mod test { + use Connection; + use super::chrono::{DateTime, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, UTC}; + + fn checked_memory_handle() -> Connection { + let db = Connection::open_in_memory().unwrap(); + db.execute_batch("CREATE TABLE chrono (t TEXT, i INTEGER, f FLOAT, b BLOB)").unwrap(); + db + } + + #[test] + fn test_naive_date() { + let db = checked_memory_handle(); + let d = NaiveDate::from_ymd(2016, 2, 23); + db.execute("INSERT INTO chrono (t) VALUES (?)", &[&d]).unwrap(); + db.execute("UPDATE chrono SET f = julianday(t)", &[]).unwrap(); + + let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!("2016-02-23", s); + let t: NaiveDate = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(d, t); + let f: NaiveDate = db.query_row("SELECT f FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(d, f); + } + + #[test] + fn test_naive_time() { + let db = checked_memory_handle(); + let t = NaiveTime::from_hms(23, 56, 4); + db.execute("INSERT INTO chrono (t) VALUES (?)", &[&t]).unwrap(); + + let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!("23:56:04.000", s); + let v: NaiveTime = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(t, v); + } + + #[test] + fn test_naive_date_time() { + let db = checked_memory_handle(); + let d = NaiveDate::from_ymd(2016, 2, 23); + let t = NaiveTime::from_hms(23, 56, 4); + let dt = NaiveDateTime::new(d, t); + + let di = NaiveDateTime::new(d, NaiveTime::from_hms(23, 56, 3)); + let ds = NaiveDateTime::new(d, NaiveTime::from_hms(23, 56, 5)); + + db.execute("INSERT INTO chrono (t) VALUES (?)", &[&dt]).unwrap(); + db.execute("UPDATE chrono SET f = julianday(t), i = strftime('%s', t)", + &[]) + .unwrap(); + + let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!("2016-02-23 23:56:04.000", s); + let v: NaiveDateTime = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(dt, v); + let f: NaiveDateTime = db.query_row("SELECT f FROM chrono", &[], |r| r.get(0)).unwrap(); + // FIXME `2016-02-23T23:56:04` vs `2016-02-23T23:56:03.999992609` + assert!(f.ge(&di) && f.le(&ds)); + let i: NaiveDateTime = db.query_row("SELECT i FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(dt, i); + + db.execute("UPDATE chrono set b = datetime(t)", &[]).unwrap(); // "YYYY-MM-DD HH:MM:SS" + let b: NaiveDateTime = db.query_row("SELECT b FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(dt, b); + + db.execute("UPDATE chrono set b = strftime('%Y-%m-%dT%H:%M', t)", &[]).unwrap(); + let b: NaiveDateTime = db.query_row("SELECT b FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(NaiveDateTime::new(d, NaiveTime::from_hms(23, 56, 0)), b); + } + + #[test] + fn test_date_time_utc() { + let db = checked_memory_handle(); + let d = NaiveDate::from_ymd(2016, 2, 23); + let t = NaiveTime::from_hms(23, 56, 4); + let dt = NaiveDateTime::new(d, t); + let utc = UTC.from_utc_datetime(&dt); + + db.execute("INSERT INTO chrono (t) VALUES (?)", &[&utc]).unwrap(); + db.execute("UPDATE chrono SET f = julianday(t), i = strftime('%s', t)", + &[]) + .unwrap(); + + let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!("2016-02-23 23:56:04.000+00:00", s); + let v: DateTime = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(utc, v); + let i: DateTime = db.query_row("SELECT i FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(utc, i); + } + + #[test] + fn test_date_time_local() { + let db = checked_memory_handle(); + let d = NaiveDate::from_ymd(2016, 2, 23); + let t = NaiveTime::from_hms(23, 56, 4); + let dt = NaiveDateTime::new(d, t); + let local = Local.from_local_datetime(&dt).single().unwrap(); + + db.execute("INSERT INTO chrono (t) VALUES (?)", &[&local]).unwrap(); + db.execute("UPDATE chrono SET f = julianday(t), i = strftime('%s', t)", + &[]) + .unwrap(); + + let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!("2016-02-23 23:56:04.000+01:00", s); + let v: DateTime = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(local, v); + let i: DateTime = db.query_row("SELECT i FROM chrono", &[], |r| r.get(0)).unwrap(); + assert_eq!(local, i); + } +} From df245d17184e21877da115e2951e07db1a72c000 Mon Sep 17 00:00:00 2001 From: gwenn Date: Tue, 23 Feb 2016 18:28:39 +0100 Subject: [PATCH 03/17] Add chrono feature to CI files. --- .travis.yml | 3 ++- appveyor.yml | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 89334cf..e0d5eb5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,4 +13,5 @@ script: - cargo test --features load_extension - cargo test --features trace - cargo test --features functions - - cargo test --features "backup blob functions load_extension trace" + - cargo test --features chrono + - cargo test --features "backup blob chrono functions load_extension trace" diff --git a/appveyor.yml b/appveyor.yml index 9fb260e..0d9a5f3 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -16,7 +16,7 @@ build: false test_script: - cargo test --lib --verbose - - cargo test --lib --features "backup blob functions load_extension trace" + - cargo test --lib --features "backup blob chrono functions load_extension trace" cache: - C:\Users\appveyor\.cargo From 08d4d9aadf881802d729f9e925f35e1353002da5 Mon Sep 17 00:00:00 2001 From: gwenn Date: Tue, 23 Feb 2016 18:34:08 +0100 Subject: [PATCH 04/17] Comment out TZ sensitive tests. --- src/types/chrono.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 41dd024..2a71955 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -372,8 +372,8 @@ mod test { &[]) .unwrap(); - let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); - assert_eq!("2016-02-23 23:56:04.000+01:00", s); + //let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + //assert_eq!("2016-02-23 23:56:04.000+01:00", s); let v: DateTime = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); assert_eq!(local, v); let i: DateTime = db.query_row("SELECT i FROM chrono", &[], |r| r.get(0)).unwrap(); From ecac52dc4cf5abffa98fd64f530882b334d71daf Mon Sep 17 00:00:00 2001 From: gwenn Date: Thu, 25 Feb 2016 18:44:53 +0100 Subject: [PATCH 05/17] Make FromSql impl for TimeSpec support double/int. --- src/types/chrono.rs | 130 +++++++++++++++++++++----------------------- src/types/mod.rs | 47 +--------------- src/types/time.rs | 81 +++++++++++++++++++++++++++ 3 files changed, 145 insertions(+), 113 deletions(-) create mode 100644 src/types/time.rs diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 2a71955..dc1718f 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -55,16 +55,15 @@ impl FromSql for NaiveDate { } } - unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { - let sqlite_type = sqlite3_column_type(stmt, col); - sqlite_type == ffi::SQLITE_TEXT || sqlite_type == ffi::SQLITE_FLOAT + unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { + true // to avoid double check } } /// ISO 8601 time without timezone => "HH:MM:SS.SSS" impl ToSql for NaiveTime { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let date_str = self.format("%H:%M:%S%.3f").to_string(); + let date_str = self.format("%H:%M:%S%.f").to_string(); date_str.bind_parameter(stmt, col) } } @@ -72,20 +71,15 @@ impl ToSql for NaiveTime { /// "HH:MM"/"HH:MM:SS"/"HH:MM:SS.SSS" => ISO 8601 time without timezone. impl FromSql for NaiveTime { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { - match sqlite3_column_type(stmt, col) { - ffi::SQLITE_TEXT => { - let s = try!(String::column_result(stmt, col)); - let fmt = match s.len() { - 5 => "%H:%M", - 8 => "%H:%M:%S", - _ => "%H:%M:%S%.3f", - }; - match NaiveTime::parse_from_str(&s, fmt) { - Ok(dt) => Ok(dt), - Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), - } - } - _ => Err(Error::InvalidColumnType), + let s = try!(String::column_result(stmt, col)); + let fmt = match s.len() { + 5 => "%H:%M", + 8 => "%H:%M:%S", + _ => "%H:%M:%S%.f", + }; + match NaiveTime::parse_from_str(&s, fmt) { + Ok(dt) => Ok(dt), + Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), } } @@ -97,7 +91,7 @@ impl FromSql for NaiveTime { /// ISO 8601 combined date and time without timezone => "YYYY-MM-DD HH:MM:SS.SSS" impl ToSql for NaiveDateTime { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let date_str = self.format("%Y-%m-%d %H:%M:%S%.3f").to_string(); + let date_str = self.format("%Y-%m-%d %H:%M:%S%.f").to_string(); date_str.bind_parameter(stmt, col) } } @@ -124,8 +118,8 @@ impl FromSql for NaiveDateTime { } _ => { match s.as_bytes()[10] { - b'T' => "%Y-%m-%dT%H:%M:%S%.3f", - _ => "%Y-%m-%d %H:%M:%S%.3f", + b'T' => "%Y-%m-%dT%H:%M:%S%.f", + _ => "%Y-%m-%d %H:%M:%S%.f", } } }; @@ -165,17 +159,15 @@ impl FromSql for NaiveDateTime { } } - unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { - let sqlite_type = sqlite3_column_type(stmt, col); - sqlite_type == ffi::SQLITE_TEXT || sqlite_type == ffi::SQLITE_INTEGER || - sqlite_type == ffi::SQLITE_FLOAT + unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { + true // to avoid double check } } /// ISO 8601 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM" impl ToSql for DateTime { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let date_str = self.format("%Y-%m-%d %H:%M:%S%.3f%:z").to_string(); + let date_str = self.format("%Y-%m-%d %H:%M:%S%.f%:z").to_string(); date_str.bind_parameter(stmt, col) } } @@ -190,9 +182,9 @@ impl FromSql for DateTime { let s = try!(String::column_result(stmt, col)); if s.len() > 23 { let fmt = if s.as_bytes()[10] == b'T' { - "%Y-%m-%dT%H:%M:%S%.3f%:z" + "%Y-%m-%dT%H:%M:%S%.f%:z" } else { - "%Y-%m-%d %H:%M:%S%.3f%:z" + "%Y-%m-%d %H:%M:%S%.f%:z" }; match UTC.datetime_from_str(&s, fmt) { Ok(dt) => Ok(dt), @@ -212,8 +204,8 @@ impl FromSql for DateTime { } } - unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { - NaiveDateTime::column_has_valid_sqlite_type(stmt, col) + unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { + true // to avoid double check } } @@ -221,7 +213,7 @@ impl FromSql for DateTime { /// ISO 8601 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM" impl ToSql for DateTime { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let date_str = self.format("%Y-%m-%d %H:%M:%S%.3f%:z").to_string(); + let date_str = self.format("%Y-%m-%d %H:%M:%S%.f%:z").to_string(); date_str.bind_parameter(stmt, col) } } @@ -236,9 +228,9 @@ impl FromSql for DateTime { let s = try!(String::column_result(stmt, col)); if s.len() > 23 { let fmt = if s.as_bytes()[10] == b'T' { - "%Y-%m-%dT%H:%M:%S%.3f%:z" + "%Y-%m-%dT%H:%M:%S%.f%:z" } else { - "%Y-%m-%d %H:%M:%S%.3f%:z" + "%Y-%m-%d %H:%M:%S%.f%:z" }; match Local.datetime_from_str(&s, fmt) { Ok(dt) => Ok(dt), @@ -258,8 +250,8 @@ impl FromSql for DateTime { } } - unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { - NaiveDateTime::column_has_valid_sqlite_type(stmt, col) + unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { + true // to avoid double check } } @@ -273,7 +265,7 @@ mod test { fn checked_memory_handle() -> Connection { let db = Connection::open_in_memory().unwrap(); - db.execute_batch("CREATE TABLE chrono (t TEXT, i INTEGER, f FLOAT, b BLOB)").unwrap(); + db.execute_batch("CREATE TABLE foo (t TEXT, i INTEGER, f FLOAT, b BLOB)").unwrap(); db } @@ -281,14 +273,14 @@ mod test { fn test_naive_date() { let db = checked_memory_handle(); let d = NaiveDate::from_ymd(2016, 2, 23); - db.execute("INSERT INTO chrono (t) VALUES (?)", &[&d]).unwrap(); - db.execute("UPDATE chrono SET f = julianday(t)", &[]).unwrap(); + db.execute("INSERT INTO foo (t) VALUES (?)", &[&d]).unwrap(); + db.execute("UPDATE foo SET f = julianday(t)", &[]).unwrap(); - let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!("2016-02-23", s); - let t: NaiveDate = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + let t: NaiveDate = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(d, t); - let f: NaiveDate = db.query_row("SELECT f FROM chrono", &[], |r| r.get(0)).unwrap(); + let f: NaiveDate = db.query_row("SELECT f FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(d, f); } @@ -296,11 +288,11 @@ mod test { fn test_naive_time() { let db = checked_memory_handle(); let t = NaiveTime::from_hms(23, 56, 4); - db.execute("INSERT INTO chrono (t) VALUES (?)", &[&t]).unwrap(); + db.execute("INSERT INTO foo (t) VALUES (?)", &[&t]).unwrap(); - let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); - assert_eq!("23:56:04.000", s); - let v: NaiveTime = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); + assert_eq!("23:56:04", s); + let v: NaiveTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(t, v); } @@ -314,27 +306,27 @@ mod test { let di = NaiveDateTime::new(d, NaiveTime::from_hms(23, 56, 3)); let ds = NaiveDateTime::new(d, NaiveTime::from_hms(23, 56, 5)); - db.execute("INSERT INTO chrono (t) VALUES (?)", &[&dt]).unwrap(); - db.execute("UPDATE chrono SET f = julianday(t), i = strftime('%s', t)", + db.execute("INSERT INTO foo (t) VALUES (?)", &[&dt]).unwrap(); + db.execute("UPDATE foo SET f = julianday(t), i = strftime('%s', t)", &[]) .unwrap(); - let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); - assert_eq!("2016-02-23 23:56:04.000", s); - let v: NaiveDateTime = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); + assert_eq!("2016-02-23 23:56:04", s); + let v: NaiveDateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(dt, v); - let f: NaiveDateTime = db.query_row("SELECT f FROM chrono", &[], |r| r.get(0)).unwrap(); - // FIXME `2016-02-23T23:56:04` vs `2016-02-23T23:56:03.999992609` + let f: NaiveDateTime = db.query_row("SELECT f FROM foo", &[], |r| r.get(0)).unwrap(); + // `2016-02-23T23:56:04` vs `2016-02-23T23:56:03.999992609` assert!(f.ge(&di) && f.le(&ds)); - let i: NaiveDateTime = db.query_row("SELECT i FROM chrono", &[], |r| r.get(0)).unwrap(); + let i: NaiveDateTime = db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(dt, i); - db.execute("UPDATE chrono set b = datetime(t)", &[]).unwrap(); // "YYYY-MM-DD HH:MM:SS" - let b: NaiveDateTime = db.query_row("SELECT b FROM chrono", &[], |r| r.get(0)).unwrap(); + db.execute("UPDATE foo set b = datetime(t)", &[]).unwrap(); // "YYYY-MM-DD HH:MM:SS" + let b: NaiveDateTime = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(dt, b); - db.execute("UPDATE chrono set b = strftime('%Y-%m-%dT%H:%M', t)", &[]).unwrap(); - let b: NaiveDateTime = db.query_row("SELECT b FROM chrono", &[], |r| r.get(0)).unwrap(); + db.execute("UPDATE foo set b = strftime('%Y-%m-%dT%H:%M', t)", &[]).unwrap(); + let b: NaiveDateTime = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(NaiveDateTime::new(d, NaiveTime::from_hms(23, 56, 0)), b); } @@ -346,16 +338,16 @@ mod test { let dt = NaiveDateTime::new(d, t); let utc = UTC.from_utc_datetime(&dt); - db.execute("INSERT INTO chrono (t) VALUES (?)", &[&utc]).unwrap(); - db.execute("UPDATE chrono SET f = julianday(t), i = strftime('%s', t)", + db.execute("INSERT INTO foo (t) VALUES (?)", &[&utc]).unwrap(); + db.execute("UPDATE foo SET f = julianday(t), i = strftime('%s', t)", &[]) .unwrap(); - let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); - assert_eq!("2016-02-23 23:56:04.000+00:00", s); - let v: DateTime = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); + assert_eq!("2016-02-23 23:56:04+00:00", s); + let v: DateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(utc, v); - let i: DateTime = db.query_row("SELECT i FROM chrono", &[], |r| r.get(0)).unwrap(); + let i: DateTime = db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(utc, i); } @@ -367,16 +359,16 @@ mod test { let dt = NaiveDateTime::new(d, t); let local = Local.from_local_datetime(&dt).single().unwrap(); - db.execute("INSERT INTO chrono (t) VALUES (?)", &[&local]).unwrap(); - db.execute("UPDATE chrono SET f = julianday(t), i = strftime('%s', t)", + db.execute("INSERT INTO foo (t) VALUES (?)", &[&local]).unwrap(); + db.execute("UPDATE foo SET f = julianday(t), i = strftime('%s', t)", &[]) .unwrap(); - //let s: String = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); - //assert_eq!("2016-02-23 23:56:04.000+01:00", s); - let v: DateTime = db.query_row("SELECT t FROM chrono", &[], |r| r.get(0)).unwrap(); + // let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); + // assert_eq!("2016-02-23 23:56:04.000+01:00", s); + let v: DateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(local, v); - let i: DateTime = db.query_row("SELECT i FROM chrono", &[], |r| r.get(0)).unwrap(); + let i: DateTime = db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(local, i); } } diff --git a/src/types/mod.rs b/src/types/mod.rs index 3f33c85..2b33fba 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -52,8 +52,6 @@ //! } //! ``` -extern crate time; - use libc::{c_int, c_double, c_char}; use std::ffi::CStr; use std::mem; @@ -66,11 +64,10 @@ pub use ffi::sqlite3_column_type; pub use ffi::{SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, SQLITE_NULL}; +mod time; #[cfg(feature = "chrono")] mod chrono; -const SQLITE_DATETIME_FMT: &'static str = "%Y-%m-%d %H:%M:%S"; - /// A trait for types that can be converted into SQLite values. pub trait ToSql { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int; @@ -156,13 +153,6 @@ impl ToSql for Vec { } } -impl ToSql for time::Timespec { - unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let time_str = time::at_utc(*self).strftime(SQLITE_DATETIME_FMT).unwrap().to_string(); - time_str.bind_parameter(stmt, col) - } -} - impl ToSql for Option { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { match *self { @@ -265,22 +255,6 @@ impl FromSql for Vec { } } -impl FromSql for time::Timespec { - unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { - let col_str = FromSql::column_result(stmt, col); - col_str.and_then(|txt: String| { - match time::strptime(&txt, SQLITE_DATETIME_FMT) { - Ok(tm) => Ok(tm.to_timespec()), - Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), - } - }) - } - - unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { - String::column_has_valid_sqlite_type(stmt, col) - } -} - impl FromSql for Option { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result> { if sqlite3_column_type(stmt, col) == ffi::SQLITE_NULL { @@ -331,8 +305,9 @@ impl FromSql for Value { #[cfg(test)] mod test { + extern crate time; + use Connection; - use super::time; use Error; use libc::{c_int, c_double}; @@ -364,20 +339,6 @@ mod test { assert_eq!(from, s); } - #[test] - fn test_timespec() { - let db = checked_memory_handle(); - - let ts = time::Timespec { - sec: 10_000, - nsec: 0, - }; - db.execute("INSERT INTO foo(t) VALUES (?)", &[&ts]).unwrap(); - - let from: time::Timespec = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(from, ts); - } - #[test] fn test_option() { let db = checked_memory_handle(); @@ -455,7 +416,6 @@ mod test { assert!(is_invalid_column_type(row.get_checked::(2).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::(2).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::>(2).err().unwrap())); - assert!(is_invalid_column_type(row.get_checked::(2).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::>(2).err().unwrap())); // 3 is actually a float (c_double) @@ -463,7 +423,6 @@ mod test { assert!(is_invalid_column_type(row.get_checked::(3).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::(3).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::>(3).err().unwrap())); - assert!(is_invalid_column_type(row.get_checked::(3).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::>(3).err().unwrap())); // 4 is actually NULL diff --git a/src/types/time.rs b/src/types/time.rs new file mode 100644 index 0000000..30886a4 --- /dev/null +++ b/src/types/time.rs @@ -0,0 +1,81 @@ +extern crate time; + +use libc::c_int; +use {Error, Result}; +use types::{FromSql, ToSql}; + +use ffi; +use ffi::sqlite3_stmt; +use ffi::sqlite3_column_type; + +const SQLITE_DATETIME_FMT: &'static str = "%Y-%m-%d %H:%M:%S"; +const JULIAN_DAY: f64 = 2440587.5; // 1970-01-01 00:00:00 is JD 2440587.5 +const DAY_IN_SECONDS: f64 = 86400.0; + +impl ToSql for time::Timespec { + unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { + let time_str = time::at_utc(*self).strftime(SQLITE_DATETIME_FMT).unwrap().to_string(); + time_str.bind_parameter(stmt, col) + } +} + +impl FromSql for time::Timespec { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { + match sqlite3_column_type(stmt, col) { + ffi::SQLITE_TEXT => { + let col_str = FromSql::column_result(stmt, col); + col_str.and_then(|txt: String| { + match time::strptime(&txt, SQLITE_DATETIME_FMT) { + Ok(tm) => Ok(tm.to_timespec()), + Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), + } + }) + } + ffi::SQLITE_INTEGER => Ok(time::Timespec::new(ffi::sqlite3_column_int64(stmt, col), 0)), + ffi::SQLITE_FLOAT => { + let mut jd = ffi::sqlite3_column_double(stmt, col); + jd -= JULIAN_DAY; + jd *= DAY_IN_SECONDS; + let ns = jd.fract() * 10f64.powi(9); + Ok(time::Timespec::new(jd as i64, ns as i32)) + } + _ => Err(Error::InvalidColumnType), + } + } + + unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { + true // to avoid double check + } +} + +#[cfg(test)] +mod test { + use Connection; + use super::time; + + fn checked_memory_handle() -> Connection { + let db = Connection::open_in_memory().unwrap(); + db.execute_batch("CREATE TABLE foo (t TEXT, i INTEGER, f FLOAT)").unwrap(); + db + } + + #[test] + fn test_timespec() { + let db = checked_memory_handle(); + + let ts = time::Timespec { + sec: 10_000, + nsec: 0, + }; + db.execute("INSERT INTO foo(t, i) VALUES (?, ?)", &[&ts, &ts.sec]).unwrap(); + db.execute("UPDATE foo SET f = julianday(t)", &[]).unwrap(); + + let from: time::Timespec = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); + assert_eq!(from, ts); + let from: time::Timespec = db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap(); + assert_eq!(from, ts); + // `Timespec { sec: 9999, nsec: 999994039 }` vs `Timespec{ sec: 10000, nsec: 0 }` + let from: time::Timespec = db.query_row("SELECT f FROM foo", &[], |r| r.get(0)).unwrap(); + assert!((from.sec - ts.sec).abs() <= 1); + } +} From 3769d085ae6fceff8622566035a056444de2c460 Mon Sep 17 00:00:00 2001 From: gwenn Date: Sat, 2 Apr 2016 13:57:55 +0200 Subject: [PATCH 06/17] Fix clippy warnings. --- src/types/chrono.rs | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index dc1718f..22ac92a 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -272,39 +272,39 @@ mod test { #[test] fn test_naive_date() { let db = checked_memory_handle(); - let d = NaiveDate::from_ymd(2016, 2, 23); - db.execute("INSERT INTO foo (t) VALUES (?)", &[&d]).unwrap(); + let date = NaiveDate::from_ymd(2016, 2, 23); + db.execute("INSERT INTO foo (t) VALUES (?)", &[&date]).unwrap(); db.execute("UPDATE foo SET f = julianday(t)", &[]).unwrap(); let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!("2016-02-23", s); let t: NaiveDate = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(d, t); + assert_eq!(date, t); let f: NaiveDate = db.query_row("SELECT f FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(d, f); + assert_eq!(date, f); } #[test] fn test_naive_time() { let db = checked_memory_handle(); - let t = NaiveTime::from_hms(23, 56, 4); - db.execute("INSERT INTO foo (t) VALUES (?)", &[&t]).unwrap(); + let time = NaiveTime::from_hms(23, 56, 4); + db.execute("INSERT INTO foo (t) VALUES (?)", &[&time]).unwrap(); let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!("23:56:04", s); let v: NaiveTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(t, v); + assert_eq!(time, v); } #[test] fn test_naive_date_time() { let db = checked_memory_handle(); - let d = NaiveDate::from_ymd(2016, 2, 23); - let t = NaiveTime::from_hms(23, 56, 4); - let dt = NaiveDateTime::new(d, t); + let date = NaiveDate::from_ymd(2016, 2, 23); + let time = NaiveTime::from_hms(23, 56, 4); + let dt = NaiveDateTime::new(date, time); - let di = NaiveDateTime::new(d, NaiveTime::from_hms(23, 56, 3)); - let ds = NaiveDateTime::new(d, NaiveTime::from_hms(23, 56, 5)); + let di = NaiveDateTime::new(date, NaiveTime::from_hms(23, 56, 3)); + let ds = NaiveDateTime::new(date, NaiveTime::from_hms(23, 56, 5)); db.execute("INSERT INTO foo (t) VALUES (?)", &[&dt]).unwrap(); db.execute("UPDATE foo SET f = julianday(t), i = strftime('%s', t)", @@ -327,15 +327,15 @@ mod test { db.execute("UPDATE foo set b = strftime('%Y-%m-%dT%H:%M', t)", &[]).unwrap(); let b: NaiveDateTime = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(NaiveDateTime::new(d, NaiveTime::from_hms(23, 56, 0)), b); + assert_eq!(NaiveDateTime::new(date, NaiveTime::from_hms(23, 56, 0)), b); } #[test] fn test_date_time_utc() { let db = checked_memory_handle(); - let d = NaiveDate::from_ymd(2016, 2, 23); - let t = NaiveTime::from_hms(23, 56, 4); - let dt = NaiveDateTime::new(d, t); + let date = NaiveDate::from_ymd(2016, 2, 23); + let time = NaiveTime::from_hms(23, 56, 4); + let dt = NaiveDateTime::new(date, time); let utc = UTC.from_utc_datetime(&dt); db.execute("INSERT INTO foo (t) VALUES (?)", &[&utc]).unwrap(); @@ -354,9 +354,9 @@ mod test { #[test] fn test_date_time_local() { let db = checked_memory_handle(); - let d = NaiveDate::from_ymd(2016, 2, 23); - let t = NaiveTime::from_hms(23, 56, 4); - let dt = NaiveDateTime::new(d, t); + let date = NaiveDate::from_ymd(2016, 2, 23); + let time = NaiveTime::from_hms(23, 56, 4); + let dt = NaiveDateTime::new(date, time); let local = Local.from_local_datetime(&dt).single().unwrap(); db.execute("INSERT INTO foo (t) VALUES (?)", &[&local]).unwrap(); From 87844c688e92ddcbe539b651aec342ff6ca7fb9b Mon Sep 17 00:00:00 2001 From: gwenn Date: Sat, 2 Apr 2016 16:48:33 +0200 Subject: [PATCH 07/17] Fix clippy warning --- src/types/chrono.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 22ac92a..19f3372 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -322,12 +322,12 @@ mod test { assert_eq!(dt, i); db.execute("UPDATE foo set b = datetime(t)", &[]).unwrap(); // "YYYY-MM-DD HH:MM:SS" - let b: NaiveDateTime = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(dt, b); + let hms: NaiveDateTime = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap(); + assert_eq!(dt, hms); db.execute("UPDATE foo set b = strftime('%Y-%m-%dT%H:%M', t)", &[]).unwrap(); - let b: NaiveDateTime = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(NaiveDateTime::new(date, NaiveTime::from_hms(23, 56, 0)), b); + let hm: NaiveDateTime = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap(); + assert_eq!(NaiveDateTime::new(date, NaiveTime::from_hms(23, 56, 0)), hm); } #[test] From 79376a4ca96f4c645c3fe0aabff12525eff83c0e Mon Sep 17 00:00:00 2001 From: gwenn Date: Wed, 4 May 2016 21:57:16 +0200 Subject: [PATCH 08/17] Partially fix the bug reported by @iwinux. If microseconds are specified but no timezone indicator, parsing fails... --- src/types/chrono.rs | 73 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 58 insertions(+), 15 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 19f3372..41871d2 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -179,15 +179,14 @@ impl FromSql for DateTime { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result> { match sqlite3_column_type(stmt, col) { ffi::SQLITE_TEXT => { - let s = try!(String::column_result(stmt, col)); + let mut s = try!(String::column_result(stmt, col)); if s.len() > 23 { - let fmt = if s.as_bytes()[10] == b'T' { - "%Y-%m-%dT%H:%M:%S%.f%:z" - } else { - "%Y-%m-%d %H:%M:%S%.f%:z" + if s.as_bytes()[10] == b' ' { + s.as_mut_vec()[10] = b'T'; }; - match UTC.datetime_from_str(&s, fmt) { - Ok(dt) => Ok(dt), + // It cannot be used when the offset can be missing. + match DateTime::parse_from_rfc3339(&s) { + Ok(dt) => Ok(dt.with_timezone(&UTC)), Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), } } else { @@ -220,20 +219,19 @@ impl ToSql for DateTime { /// "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM"/"YYYY-MM-DD HH:MM"/"YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS"/ Julian Day / Unix Time => ISO 8601 date and time with time zone. /// ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM"/"YYYY-MM-DDTHH:MM"/"YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported) -/// When the timezone is not specified, Local is used. +/// When the timezone is not specified, UTC is used. impl FromSql for DateTime { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result> { match sqlite3_column_type(stmt, col) { ffi::SQLITE_TEXT => { - let s = try!(String::column_result(stmt, col)); + let mut s = try!(String::column_result(stmt, col)); if s.len() > 23 { - let fmt = if s.as_bytes()[10] == b'T' { - "%Y-%m-%dT%H:%M:%S%.f%:z" - } else { - "%Y-%m-%d %H:%M:%S%.f%:z" + if s.as_bytes()[10] == b' ' { + s.as_mut_vec()[10] = b'T'; }; - match Local.datetime_from_str(&s, fmt) { - Ok(dt) => Ok(dt), + // It cannot be used when the offset can be missing. + match DateTime::parse_from_rfc3339(&s) { + Ok(dt) => Ok(dt.with_timezone(&Local)), Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), } } else { @@ -371,4 +369,49 @@ mod test { let i: DateTime = db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(local, i); } + + #[test] + fn test_timezone() { + // Worst + UTC.datetime_from_str("2016-05-04 17:00:42.862471+08:00", + "%Y-%m-%d %H:%M:%S%.f%:z") + .unwrap_err(); + UTC.datetime_from_str("2016-05-04 17:00:42.862471Z", "%Y-%m-%d %H:%M:%S%.f%:z") + .unwrap_err(); + UTC.datetime_from_str("2016-05-04 17:00:42.862471", "%Y-%m-%d %H:%M:%S%.f%:z").unwrap_err(); + + UTC.datetime_from_str("2016-05-04 17:00:42.862471+08:00", "%Y-%m-%d %H:%M:%S%.f%z") + .unwrap_err(); + UTC.datetime_from_str("2016-05-04 17:00:42.862471Z", "%Y-%m-%d %H:%M:%S%.f%z").unwrap_err(); + UTC.datetime_from_str("2016-05-04 17:00:42.862471", "%Y-%m-%d %H:%M:%S%.f%z").unwrap_err(); + + // Better but... + DateTime::parse_from_str("2016-05-04 17:00:42.862471+08:00", "%Y-%m-%d %H:%M:%S%.f%z") + .unwrap() + .with_timezone(&UTC); + DateTime::parse_from_str("2016-05-04 17:00:42.862471Z", "%Y-%m-%d %H:%M:%S%.f%z") + .unwrap_err(); // Invalid + DateTime::parse_from_str("2016-05-04 17:00:42.862471", "%Y-%m-%d %H:%M:%S%.f%z") + .unwrap_err(); // TooShort + + DateTime::parse_from_str("2016-05-04 17:00:42.862471+08:00", + "%Y-%m-%d %H:%M:%S%.f%:z") + .unwrap() + .with_timezone(&UTC); + DateTime::parse_from_str("2016-05-04 17:00:42.862471Z", "%Y-%m-%d %H:%M:%S%.f%:z") + .unwrap_err(); // Invalid + DateTime::parse_from_str("2016-05-04 17:00:42.862471", "%Y-%m-%d %H:%M:%S%.f%:z") + .unwrap_err(); // TooShort + + // Best but in SQLite, the timezone indicator is optional + DateTime::parse_from_rfc3339("2016-05-04T17:00:42.862471+08:00") + .unwrap() + .with_timezone(&UTC); + DateTime::parse_from_rfc3339("2016-05-04T17:00:42.862471Z").unwrap().with_timezone(&UTC); + DateTime::parse_from_rfc3339("2016-05-04T17:00:42.862471").unwrap_err(); // TooShort + + "2016-05-04T17:00:42.862471+08:00".parse::>().unwrap(); + "2016-05-04T17:00:42.862471Z".parse::>().unwrap(); + "2016-05-04T17:00:42.862471".parse::>().unwrap_err(); // TooShort + } } From 350dc59bb964095c7040b39e58a4c5b1d5d5b2a4 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sun, 15 May 2016 15:32:59 -0400 Subject: [PATCH 09/17] Remove unnecessary column_has_valid_sqlite_type impls --- src/types/chrono.rs | 16 ---------------- src/types/mod.rs | 4 ---- src/types/time.rs | 4 ---- 3 files changed, 24 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 41871d2..bd23f34 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -54,10 +54,6 @@ impl FromSql for NaiveDate { _ => Err(Error::InvalidColumnType), } } - - unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { - true // to avoid double check - } } /// ISO 8601 time without timezone => "HH:MM:SS.SSS" @@ -158,10 +154,6 @@ impl FromSql for NaiveDateTime { _ => Err(Error::InvalidColumnType), } } - - unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { - true // to avoid double check - } } /// ISO 8601 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM" @@ -202,10 +194,6 @@ impl FromSql for DateTime { _ => Err(Error::InvalidColumnType), } } - - unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { - true // to avoid double check - } } @@ -247,10 +235,6 @@ impl FromSql for DateTime { _ => Err(Error::InvalidColumnType), } } - - unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { - true // to avoid double check - } } // struct UnixTime(NaiveDateTime); diff --git a/src/types/mod.rs b/src/types/mod.rs index 4cffd50..46a5c54 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -298,10 +298,6 @@ impl FromSql for Value { _ => Err(Error::InvalidColumnType), } } - - unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { - true - } } #[cfg(test)] diff --git a/src/types/time.rs b/src/types/time.rs index 30886a4..2fe19c5 100644 --- a/src/types/time.rs +++ b/src/types/time.rs @@ -42,10 +42,6 @@ impl FromSql for time::Timespec { _ => Err(Error::InvalidColumnType), } } - - unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { - true // to avoid double check - } } #[cfg(test)] From 42bc173009082eb403089970b72a4a26ad3e5173 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sun, 15 May 2016 19:56:57 -0500 Subject: [PATCH 10/17] Only use strings for NaiveDate's ToSql/FromSql impl --- src/types/chrono.rs | 41 ++++++++++------------------------------- 1 file changed, 10 insertions(+), 31 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index bd23f34..023dfed 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -14,7 +14,6 @@ use ffi::sqlite3_column_type; const JULIAN_DAY: f64 = 2440587.5; // 1970-01-01 00:00:00 is JD 2440587.5 const DAY_IN_SECONDS: f64 = 86400.0; -const JULIAN_DAY_GREGORIAN: f64 = 1721424.5; // Jan 1, 1 proleptic Gregorian calendar /// ISO 8601 calendar date without timezone => "YYYY-MM-DD" impl ToSql for NaiveDate { @@ -24,36 +23,19 @@ impl ToSql for NaiveDate { } } -/// "YYYY-MM-DD" or Julian Day => ISO 8601 calendar date without timezone. +/// "YYYY-MM-DD" => ISO 8601 calendar date without timezone. impl FromSql for NaiveDate { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { - match sqlite3_column_type(stmt, col) { - ffi::SQLITE_TEXT => { - let s = try!(String::column_result(stmt, col)); - match NaiveDate::parse_from_str(&s, "%Y-%m-%d") { - Ok(dt) => Ok(dt), - Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), - } - } - ffi::SQLITE_FLOAT => { - // if column affinity is REAL and an integer/unix timestamp is inserted => unexpected result - let mut jd = ffi::sqlite3_column_double(stmt, col); - jd -= JULIAN_DAY_GREGORIAN; - if jd < i32::min_value() as f64 || jd > i32::max_value() as f64 { - let err: Box = "out-of-range date".into(); - return Err(Error::FromSqlConversionFailure(err)); - } - match NaiveDate::from_num_days_from_ce_opt(jd as i32) { - Some(dt) => Ok(dt), - None => { - let err: Box = "out-of-range date".into(); - Err(Error::FromSqlConversionFailure(err)) - } - } - } - _ => Err(Error::InvalidColumnType), + let s = try!(String::column_result(stmt, col)); + match NaiveDate::parse_from_str(&s, "%Y-%m-%d") { + Ok(dt) => Ok(dt), + Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), } } + + unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { + String::column_has_valid_sqlite_type(stmt, col) + } } /// ISO 8601 time without timezone => "HH:MM:SS.SSS" @@ -80,7 +62,7 @@ impl FromSql for NaiveTime { } unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { - sqlite3_column_type(stmt, col) == ffi::SQLITE_TEXT + String::column_has_valid_sqlite_type(stmt, col) } } @@ -256,14 +238,11 @@ mod test { let db = checked_memory_handle(); let date = NaiveDate::from_ymd(2016, 2, 23); db.execute("INSERT INTO foo (t) VALUES (?)", &[&date]).unwrap(); - db.execute("UPDATE foo SET f = julianday(t)", &[]).unwrap(); let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!("2016-02-23", s); let t: NaiveDate = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(date, t); - let f: NaiveDate = db.query_row("SELECT f FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(date, f); } #[test] From 07801ca3709d6baa92155bb1ff2c12de1d548db7 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sun, 15 May 2016 22:23:02 -0500 Subject: [PATCH 11/17] Greatly reduce implementation of chrono types. Limit ToSql/FromSql to string representations, and limit allowed string representations to RFC3339 (if a timezone is expected) and SQLite's `datetime()` format (if not). --- src/types/chrono.rs | 254 ++++++++------------------------------------ 1 file changed, 44 insertions(+), 210 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 023dfed..98ed77e 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -1,19 +1,13 @@ //! Convert most of the [Time Strings](http://sqlite.org/lang_datefunc.html) to chrono types. extern crate chrono; -use std::error; use self::chrono::{NaiveDate, NaiveTime, NaiveDateTime, DateTime, TimeZone, UTC, Local}; use libc::c_int; use {Error, Result}; use types::{FromSql, ToSql}; -use ffi; use ffi::sqlite3_stmt; -use ffi::sqlite3_column_type; - -const JULIAN_DAY: f64 = 2440587.5; // 1970-01-01 00:00:00 is JD 2440587.5 -const DAY_IN_SECONDS: f64 = 86400.0; /// ISO 8601 calendar date without timezone => "YYYY-MM-DD" impl ToSql for NaiveDate { @@ -69,159 +63,68 @@ impl FromSql for NaiveTime { /// ISO 8601 combined date and time without timezone => "YYYY-MM-DD HH:MM:SS.SSS" impl ToSql for NaiveDateTime { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let date_str = self.format("%Y-%m-%d %H:%M:%S%.f").to_string(); + let date_str = self.format("%Y-%m-%dT%H:%M:%S%.f").to_string(); date_str.bind_parameter(stmt, col) } } -/// "YYYY-MM-DD HH:MM"/"YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS"/ Julian Day / Unix Time => ISO 8601 combined date and time without timezone. -/// ("YYYY-MM-DDTHH:MM"/"YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported) +/// "YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS" => ISO 8601 combined date and time without timezone. +/// ("YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported) impl FromSql for NaiveDateTime { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { - match sqlite3_column_type(stmt, col) { - ffi::SQLITE_TEXT => { - let s = try!(String::column_result(stmt, col)); - let fmt = match s.len() { - 16 => { - match s.as_bytes()[10] { - b'T' => "%Y-%m-%dT%H:%M", - _ => "%Y-%m-%d %H:%M", - } - } - 19 => { - match s.as_bytes()[10] { - b'T' => "%Y-%m-%dT%H:%M:%S", - _ => "%Y-%m-%d %H:%M:%S", - } - } - _ => { - match s.as_bytes()[10] { - b'T' => "%Y-%m-%dT%H:%M:%S%.f", - _ => "%Y-%m-%d %H:%M:%S%.f", - } - } - }; - match NaiveDateTime::parse_from_str(&s, fmt) { - Ok(dt) => Ok(dt), - Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), - } - } - ffi::SQLITE_INTEGER => { - match NaiveDateTime::from_timestamp_opt(ffi::sqlite3_column_int64(stmt, col), 0) { - Some(dt) => Ok(dt), - None => { - let err: Box = "out-of-range number of seconds" - .into(); - Err(Error::FromSqlConversionFailure(err)) - } - } - } - ffi::SQLITE_FLOAT => { - // if column affinity is REAL and an integer/unix timestamp is inserted => unexpected result - let mut jd = ffi::sqlite3_column_double(stmt, col); - jd -= JULIAN_DAY; - jd *= DAY_IN_SECONDS; - let ns = jd.fract() * 10f64.powi(9); - match NaiveDateTime::from_timestamp_opt(jd as i64, ns as u32) { - Some(dt) => Ok(dt), - None => { - let err: Box = "out-of-range number of \ - seconds and/or invalid \ - nanosecond" - .into(); - Err(Error::FromSqlConversionFailure(err)) - } - } - } - _ => Err(Error::InvalidColumnType), + let s = try!(String::column_result(stmt, col)); + + let fmt = if s.len() >= 11 && s.as_bytes()[10] == b'T' { + "%Y-%m-%dT%H:%M:%S%.f" + } else { + "%Y-%m-%d %H:%M:%S%.f" + }; + + match NaiveDateTime::parse_from_str(&s, fmt) { + Ok(dt) => Ok(dt), + Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), } } -} -/// ISO 8601 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM" -impl ToSql for DateTime { - unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let date_str = self.format("%Y-%m-%d %H:%M:%S%.f%:z").to_string(); - date_str.bind_parameter(stmt, col) + unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { + String::column_has_valid_sqlite_type(stmt, col) } } -/// "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM"/"YYYY-MM-DD HH:MM"/"YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS"/ Julian Day / Unix Time => ISO 8601 date and time with time zone. -/// ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM"/"YYYY-MM-DDTHH:MM"/"YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported) -/// When the timezone is not specified, UTC is used. +/// Date and time with time zone => RFC3339 timestamp ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM"). +impl ToSql for DateTime where Tz::Offset: ::std::fmt::Display { + unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { + self.to_rfc3339().bind_parameter(stmt, col) + } +} + +/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime. impl FromSql for DateTime { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result> { - match sqlite3_column_type(stmt, col) { - ffi::SQLITE_TEXT => { - let mut s = try!(String::column_result(stmt, col)); - if s.len() > 23 { - if s.as_bytes()[10] == b' ' { - s.as_mut_vec()[10] = b'T'; - }; - // It cannot be used when the offset can be missing. - match DateTime::parse_from_rfc3339(&s) { - Ok(dt) => Ok(dt.with_timezone(&UTC)), - Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), - } - } else { - NaiveDateTime::column_result(stmt, col).map(|dt| UTC.from_utc_datetime(&dt)) - } - } - ffi::SQLITE_INTEGER => { - NaiveDateTime::column_result(stmt, col).map(|dt| UTC.from_utc_datetime(&dt)) - } - ffi::SQLITE_FLOAT => { - NaiveDateTime::column_result(stmt, col).map(|dt| UTC.from_utc_datetime(&dt)) - } - _ => Err(Error::InvalidColumnType), + let s = try!(String::column_result(stmt, col)); + match DateTime::parse_from_rfc3339(&s) { + Ok(dt) => Ok(dt.with_timezone(&UTC)), + Err(_) => NaiveDateTime::column_result(stmt, col).map(|dt| UTC.from_utc_datetime(&dt)), } } -} - -/// ISO 8601 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM" -impl ToSql for DateTime { - unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - let date_str = self.format("%Y-%m-%d %H:%M:%S%.f%:z").to_string(); - date_str.bind_parameter(stmt, col) + unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { + String::column_has_valid_sqlite_type(stmt, col) } } -/// "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM"/"YYYY-MM-DD HH:MM"/"YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS"/ Julian Day / Unix Time => ISO 8601 date and time with time zone. -/// ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM"/"YYYY-MM-DDTHH:MM"/"YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported) -/// When the timezone is not specified, UTC is used. +/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime. impl FromSql for DateTime { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result> { - match sqlite3_column_type(stmt, col) { - ffi::SQLITE_TEXT => { - let mut s = try!(String::column_result(stmt, col)); - if s.len() > 23 { - if s.as_bytes()[10] == b' ' { - s.as_mut_vec()[10] = b'T'; - }; - // It cannot be used when the offset can be missing. - match DateTime::parse_from_rfc3339(&s) { - Ok(dt) => Ok(dt.with_timezone(&Local)), - Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), - } - } else { - NaiveDateTime::column_result(stmt, col).map(|dt| Local.from_utc_datetime(&dt)) - } - } - ffi::SQLITE_INTEGER => { - NaiveDateTime::column_result(stmt, col).map(|dt| Local.from_utc_datetime(&dt)) - } - ffi::SQLITE_FLOAT => { - NaiveDateTime::column_result(stmt, col).map(|dt| Local.from_utc_datetime(&dt)) - } - _ => Err(Error::InvalidColumnType), - } + let utc_dt = try!(DateTime::::column_result(stmt, col)); + Ok(utc_dt.with_timezone(&Local)) + } + + unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { + DateTime::::column_has_valid_sqlite_type(stmt, col) } } -// struct UnixTime(NaiveDateTime); -// struct JulianTime(NaiveDateTime) - #[cfg(test)] mod test { use Connection; @@ -264,117 +167,48 @@ mod test { let time = NaiveTime::from_hms(23, 56, 4); let dt = NaiveDateTime::new(date, time); - let di = NaiveDateTime::new(date, NaiveTime::from_hms(23, 56, 3)); - let ds = NaiveDateTime::new(date, NaiveTime::from_hms(23, 56, 5)); - db.execute("INSERT INTO foo (t) VALUES (?)", &[&dt]).unwrap(); - db.execute("UPDATE foo SET f = julianday(t), i = strftime('%s', t)", - &[]) - .unwrap(); let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!("2016-02-23 23:56:04", s); + assert_eq!("2016-02-23T23:56:04", s); let v: NaiveDateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(dt, v); - let f: NaiveDateTime = db.query_row("SELECT f FROM foo", &[], |r| r.get(0)).unwrap(); - // `2016-02-23T23:56:04` vs `2016-02-23T23:56:03.999992609` - assert!(f.ge(&di) && f.le(&ds)); - let i: NaiveDateTime = db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(dt, i); db.execute("UPDATE foo set b = datetime(t)", &[]).unwrap(); // "YYYY-MM-DD HH:MM:SS" let hms: NaiveDateTime = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(dt, hms); - - db.execute("UPDATE foo set b = strftime('%Y-%m-%dT%H:%M', t)", &[]).unwrap(); - let hm: NaiveDateTime = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(NaiveDateTime::new(date, NaiveTime::from_hms(23, 56, 0)), hm); } #[test] fn test_date_time_utc() { let db = checked_memory_handle(); let date = NaiveDate::from_ymd(2016, 2, 23); - let time = NaiveTime::from_hms(23, 56, 4); + let time = NaiveTime::from_hms_milli(23, 56, 4, 789); let dt = NaiveDateTime::new(date, time); let utc = UTC.from_utc_datetime(&dt); db.execute("INSERT INTO foo (t) VALUES (?)", &[&utc]).unwrap(); - db.execute("UPDATE foo SET f = julianday(t), i = strftime('%s', t)", - &[]) - .unwrap(); let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!("2016-02-23 23:56:04+00:00", s); + assert_eq!("2016-02-23T23:56:04.789+00:00", s); let v: DateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(utc, v); - let i: DateTime = db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(utc, i); } #[test] fn test_date_time_local() { let db = checked_memory_handle(); let date = NaiveDate::from_ymd(2016, 2, 23); - let time = NaiveTime::from_hms(23, 56, 4); + let time = NaiveTime::from_hms_milli(23, 56, 4, 789); let dt = NaiveDateTime::new(date, time); let local = Local.from_local_datetime(&dt).single().unwrap(); db.execute("INSERT INTO foo (t) VALUES (?)", &[&local]).unwrap(); - db.execute("UPDATE foo SET f = julianday(t), i = strftime('%s', t)", - &[]) - .unwrap(); - // let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); - // assert_eq!("2016-02-23 23:56:04.000+01:00", s); + let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); + let offset = Local.offset_from_utc_datetime(&dt); + assert_eq!(format!("2016-02-23T23:56:04.789{:}", offset), s); let v: DateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(local, v); - let i: DateTime = db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(local, i); - } - - #[test] - fn test_timezone() { - // Worst - UTC.datetime_from_str("2016-05-04 17:00:42.862471+08:00", - "%Y-%m-%d %H:%M:%S%.f%:z") - .unwrap_err(); - UTC.datetime_from_str("2016-05-04 17:00:42.862471Z", "%Y-%m-%d %H:%M:%S%.f%:z") - .unwrap_err(); - UTC.datetime_from_str("2016-05-04 17:00:42.862471", "%Y-%m-%d %H:%M:%S%.f%:z").unwrap_err(); - - UTC.datetime_from_str("2016-05-04 17:00:42.862471+08:00", "%Y-%m-%d %H:%M:%S%.f%z") - .unwrap_err(); - UTC.datetime_from_str("2016-05-04 17:00:42.862471Z", "%Y-%m-%d %H:%M:%S%.f%z").unwrap_err(); - UTC.datetime_from_str("2016-05-04 17:00:42.862471", "%Y-%m-%d %H:%M:%S%.f%z").unwrap_err(); - - // Better but... - DateTime::parse_from_str("2016-05-04 17:00:42.862471+08:00", "%Y-%m-%d %H:%M:%S%.f%z") - .unwrap() - .with_timezone(&UTC); - DateTime::parse_from_str("2016-05-04 17:00:42.862471Z", "%Y-%m-%d %H:%M:%S%.f%z") - .unwrap_err(); // Invalid - DateTime::parse_from_str("2016-05-04 17:00:42.862471", "%Y-%m-%d %H:%M:%S%.f%z") - .unwrap_err(); // TooShort - - DateTime::parse_from_str("2016-05-04 17:00:42.862471+08:00", - "%Y-%m-%d %H:%M:%S%.f%:z") - .unwrap() - .with_timezone(&UTC); - DateTime::parse_from_str("2016-05-04 17:00:42.862471Z", "%Y-%m-%d %H:%M:%S%.f%:z") - .unwrap_err(); // Invalid - DateTime::parse_from_str("2016-05-04 17:00:42.862471", "%Y-%m-%d %H:%M:%S%.f%:z") - .unwrap_err(); // TooShort - - // Best but in SQLite, the timezone indicator is optional - DateTime::parse_from_rfc3339("2016-05-04T17:00:42.862471+08:00") - .unwrap() - .with_timezone(&UTC); - DateTime::parse_from_rfc3339("2016-05-04T17:00:42.862471Z").unwrap().with_timezone(&UTC); - DateTime::parse_from_rfc3339("2016-05-04T17:00:42.862471").unwrap_err(); // TooShort - - "2016-05-04T17:00:42.862471+08:00".parse::>().unwrap(); - "2016-05-04T17:00:42.862471Z".parse::>().unwrap(); - "2016-05-04T17:00:42.862471".parse::>().unwrap_err(); // TooShort } } From 88fb175b40e529ad31c8878d139e198e2c9edcf4 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sun, 15 May 2016 22:30:11 -0500 Subject: [PATCH 12/17] Limit Timespec representation to strings. --- src/types/time.rs | 39 +++++++++------------------------------ 1 file changed, 9 insertions(+), 30 deletions(-) diff --git a/src/types/time.rs b/src/types/time.rs index 2fe19c5..fe77956 100644 --- a/src/types/time.rs +++ b/src/types/time.rs @@ -4,13 +4,9 @@ use libc::c_int; use {Error, Result}; use types::{FromSql, ToSql}; -use ffi; use ffi::sqlite3_stmt; -use ffi::sqlite3_column_type; const SQLITE_DATETIME_FMT: &'static str = "%Y-%m-%d %H:%M:%S"; -const JULIAN_DAY: f64 = 2440587.5; // 1970-01-01 00:00:00 is JD 2440587.5 -const DAY_IN_SECONDS: f64 = 86400.0; impl ToSql for time::Timespec { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { @@ -21,27 +17,16 @@ impl ToSql for time::Timespec { impl FromSql for time::Timespec { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { - match sqlite3_column_type(stmt, col) { - ffi::SQLITE_TEXT => { - let col_str = FromSql::column_result(stmt, col); - col_str.and_then(|txt: String| { - match time::strptime(&txt, SQLITE_DATETIME_FMT) { - Ok(tm) => Ok(tm.to_timespec()), - Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), - } - }) - } - ffi::SQLITE_INTEGER => Ok(time::Timespec::new(ffi::sqlite3_column_int64(stmt, col), 0)), - ffi::SQLITE_FLOAT => { - let mut jd = ffi::sqlite3_column_double(stmt, col); - jd -= JULIAN_DAY; - jd *= DAY_IN_SECONDS; - let ns = jd.fract() * 10f64.powi(9); - Ok(time::Timespec::new(jd as i64, ns as i32)) - } - _ => Err(Error::InvalidColumnType), + let s = try!(String::column_result(stmt, col)); + match time::strptime(&s, SQLITE_DATETIME_FMT) { + Ok(tm) => Ok(tm.to_timespec()), + Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), } } + + unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool { + String::column_has_valid_sqlite_type(stmt, col) + } } #[cfg(test)] @@ -63,15 +48,9 @@ mod test { sec: 10_000, nsec: 0, }; - db.execute("INSERT INTO foo(t, i) VALUES (?, ?)", &[&ts, &ts.sec]).unwrap(); - db.execute("UPDATE foo SET f = julianday(t)", &[]).unwrap(); + db.execute("INSERT INTO foo(t) VALUES (?)", &[&ts]).unwrap(); let from: time::Timespec = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(from, ts); - let from: time::Timespec = db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(from, ts); - // `Timespec { sec: 9999, nsec: 999994039 }` vs `Timespec{ sec: 10000, nsec: 0 }` - let from: time::Timespec = db.query_row("SELECT f FROM foo", &[], |r| r.get(0)).unwrap(); - assert!((from.sec - ts.sec).abs() <= 1); } } From aa2b3b26bd11492572a9d63369df8e6cd3300333 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sun, 15 May 2016 22:39:18 -0500 Subject: [PATCH 13/17] Add chrono note to Changelog --- Changelog.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Changelog.md b/Changelog.md index ad5ca25..e000549 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,6 @@ # Version UPCOMING (...) +* Adds support for serializing types from the `chrono` crate. Requires the `chrono` feature. * Removes `load_extension` feature from `libsqlite3-sys`. `load_extension` is still available on rusqlite itself. * Fixes crash on nightly Rust when using the `trace` feature. From 34d5e2db2467cd81fbddaff8ea8996a2f93b8adc Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Mon, 16 May 2016 09:08:31 -0500 Subject: [PATCH 14/17] Always store DateTimes in UTC --- src/types/chrono.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 98ed77e..dd63c40 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -91,10 +91,11 @@ impl FromSql for NaiveDateTime { } } -/// Date and time with time zone => RFC3339 timestamp ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM"). -impl ToSql for DateTime where Tz::Offset: ::std::fmt::Display { +/// Date and time with time zone => UTC RFC3339 timestamp ("YYYY-MM-DDTHH:MM:SS.SSS+00:00"). +impl ToSql for DateTime { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { - self.to_rfc3339().bind_parameter(stmt, col) + let utc_dt = self.with_timezone(&UTC); + utc_dt.to_rfc3339().bind_parameter(stmt, col) } } @@ -205,9 +206,10 @@ mod test { db.execute("INSERT INTO foo (t) VALUES (?)", &[&local]).unwrap(); + // Stored string should be in UTC let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); - let offset = Local.offset_from_utc_datetime(&dt); - assert_eq!(format!("2016-02-23T23:56:04.789{:}", offset), s); + assert!(s.ends_with("+00:00")); + let v: DateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(local, v); } From 6d9b268776bb87f9057139c4869b741a1a6999cd Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Mon, 16 May 2016 09:13:45 -0500 Subject: [PATCH 15/17] Add tests confirming DateTime works with " " seperator instead of "T" --- src/types/chrono.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index dd63c40..39a7093 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -129,7 +129,7 @@ impl FromSql for DateTime { #[cfg(test)] mod test { use Connection; - use super::chrono::{DateTime, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, UTC}; + use super::chrono::{DateTime, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, UTC, Duration}; fn checked_memory_handle() -> Connection { let db = Connection::open_in_memory().unwrap(); @@ -192,8 +192,15 @@ mod test { let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!("2016-02-23T23:56:04.789+00:00", s); - let v: DateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); - assert_eq!(utc, v); + + let v1: DateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); + assert_eq!(utc, v1); + + let v2: DateTime = db.query_row("SELECT '2016-02-23 23:56:04.789'", &[], |r| r.get(0)).unwrap(); + assert_eq!(utc, v2); + + let v3: DateTime = db.query_row("SELECT '2016-02-23 23:56:04'", &[], |r| r.get(0)).unwrap(); + assert_eq!(utc - Duration::milliseconds(789), v3); } #[test] From 6a4abff462ff8442a682400831ffa6654a6208d9 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Mon, 16 May 2016 09:27:50 -0500 Subject: [PATCH 16/17] Restore support for full RFC3339 timestamps with a space seperator --- src/types/chrono.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 39a7093..4aaa63d 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -102,7 +102,16 @@ impl ToSql for DateTime { /// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime. impl FromSql for DateTime { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result> { - let s = try!(String::column_result(stmt, col)); + let s = { + let mut s = try!(String::column_result(stmt, col)); + if s.len() >= 11 { + let sbytes = s.as_mut_vec(); + if sbytes[10] == b' ' { + sbytes[10] = b'T'; + } + } + s + }; match DateTime::parse_from_rfc3339(&s) { Ok(dt) => Ok(dt.with_timezone(&UTC)), Err(_) => NaiveDateTime::column_result(stmt, col).map(|dt| UTC.from_utc_datetime(&dt)), @@ -201,6 +210,9 @@ mod test { let v3: DateTime = db.query_row("SELECT '2016-02-23 23:56:04'", &[], |r| r.get(0)).unwrap(); assert_eq!(utc - Duration::milliseconds(789), v3); + + let v4: DateTime = db.query_row("SELECT '2016-02-23 23:56:04.789+00:00'", &[], |r| r.get(0)).unwrap(); + assert_eq!(utc, v4); } #[test] From 4924c0b38b134b498ec12f0e58f9eb115837a2dd Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Mon, 16 May 2016 10:02:07 -0500 Subject: [PATCH 17/17] rustfmt --- src/types/chrono.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 4aaa63d..a9e0bea 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -68,8 +68,8 @@ impl ToSql for NaiveDateTime { } } -/// "YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS" => ISO 8601 combined date and time without timezone. -/// ("YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported) +/// "YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS" => ISO 8601 combined date and time +/// without timezone. ("YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported) impl FromSql for NaiveDateTime { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { let s = try!(String::column_result(stmt, col)); @@ -138,7 +138,8 @@ impl FromSql for DateTime { #[cfg(test)] mod test { use Connection; - use super::chrono::{DateTime, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, UTC, Duration}; + use super::chrono::{DateTime, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, UTC, + Duration}; fn checked_memory_handle() -> Connection { let db = Connection::open_in_memory().unwrap(); @@ -205,13 +206,16 @@ mod test { let v1: DateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); assert_eq!(utc, v1); - let v2: DateTime = db.query_row("SELECT '2016-02-23 23:56:04.789'", &[], |r| r.get(0)).unwrap(); + let v2: DateTime = db.query_row("SELECT '2016-02-23 23:56:04.789'", &[], |r| r.get(0)) + .unwrap(); assert_eq!(utc, v2); - let v3: DateTime = db.query_row("SELECT '2016-02-23 23:56:04'", &[], |r| r.get(0)).unwrap(); + let v3: DateTime = db.query_row("SELECT '2016-02-23 23:56:04'", &[], |r| r.get(0)) + .unwrap(); assert_eq!(utc - Duration::milliseconds(789), v3); - let v4: DateTime = db.query_row("SELECT '2016-02-23 23:56:04.789+00:00'", &[], |r| r.get(0)).unwrap(); + let v4: DateTime = + db.query_row("SELECT '2016-02-23 23:56:04.789+00:00'", &[], |r| r.get(0)).unwrap(); assert_eq!(utc, v4); }