mirror of
https://github.com/isar/rusqlite.git
synced 2024-11-23 00:39:20 +08:00
Limit Timespec representation to strings.
This commit is contained in:
parent
07801ca370
commit
88fb175b40
@ -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<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(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);
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user