Merge branch 'gwenn-chrono' into json

This commit is contained in:
John Gallagher 2016-05-15 22:41:06 -05:00
commit b68e9e8a6f
4 changed files with 54 additions and 245 deletions

View File

@ -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.

View File

@ -1,20 +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;
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,39 +17,18 @@ 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<NaiveDate> {
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<error::Error + Sync + Send> = "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<error::Error + Sync + Send> = "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(_: *mut sqlite3_stmt, _: c_int) -> bool {
true // to avoid double check
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
String::column_has_valid_sqlite_type(stmt, col)
}
}
@ -84,183 +56,75 @@ 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)
}
}
/// 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<NaiveDateTime> {
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<error::Error + Sync + Send> = "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<error::Error + Sync + Send> = "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))),
}
}
unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool {
true // to avoid double check
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 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM"
impl ToSql for DateTime<UTC> {
/// Date and time with time zone => RFC3339 timestamp ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM").
impl<Tz: TimeZone> ToSql for DateTime<Tz> where Tz::Offset: ::std::fmt::Display {
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)
self.to_rfc3339().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.
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<UTC>.
impl FromSql for DateTime<UTC> {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<DateTime<UTC>> {
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%.f%:z"
} else {
"%Y-%m-%d %H:%M:%S%.f%:z"
};
match UTC.datetime_from_str(&s, fmt) {
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),
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)),
}
}
unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool {
true // to avoid double check
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 date and time with time zone => "YYYY-MM-DD HH:MM:SS.SSS[+-]HH:MM"
impl ToSql for DateTime<Local> {
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)
}
}
/// "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.
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<Local>.
impl FromSql for DateTime<Local> {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<DateTime<Local>> {
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%.f%:z"
} else {
"%Y-%m-%d %H:%M:%S%.f%:z"
};
match Local.datetime_from_str(&s, fmt) {
Ok(dt) => Ok(dt),
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
}
} else {
// TODO from_utc_datetime versus from from_local_datetime
NaiveDateTime::column_result(stmt, col).map(|dt| Local.from_utc_datetime(&dt))
}
}
ffi::SQLITE_INTEGER => {
// TODO from_utc_datetime versus from from_local_datetime
NaiveDateTime::column_result(stmt, col).map(|dt| Local.from_utc_datetime(&dt))
}
ffi::SQLITE_FLOAT => {
// TODO from_utc_datetime versus from from_local_datetime
NaiveDateTime::column_result(stmt, col).map(|dt| Local.from_utc_datetime(&dt))
}
_ => Err(Error::InvalidColumnType),
}
let utc_dt = try!(DateTime::<UTC>::column_result(stmt, col));
Ok(utc_dt.with_timezone(&Local))
}
unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool {
true // to avoid double check
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
DateTime::<UTC>::column_has_valid_sqlite_type(stmt, col)
}
}
// struct UnixTime(NaiveDateTime);
// struct JulianTime(NaiveDateTime)
#[cfg(test)]
mod test {
use Connection;
@ -277,14 +141,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]
@ -306,72 +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<UTC> = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(utc, v);
let i: DateTime<UTC> = 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<Local> = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(local, v);
let i: DateTime<Local> = db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(local, i);
}
}

View File

@ -300,10 +300,6 @@ impl FromSql for Value {
_ => Err(Error::InvalidColumnType),
}
}
unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool {
true
}
}
#[cfg(test)]

View File

@ -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,30 +17,15 @@ impl ToSql for time::Timespec {
impl FromSql for time::Timespec {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<time::Timespec> {
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(_: *mut sqlite3_stmt, _: c_int) -> bool {
true // to avoid double check
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
String::column_has_valid_sqlite_type(stmt, col)
}
}
@ -67,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);
}
}