use byteorder::{BigEndian, ReadBytesExt};
use postgres::types::{self, FromSql, Type};
use std::error::Error;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PgInterval {
pub microseconds: i64,
pub days: i32,
pub months: i32,
}
impl PgInterval {
pub fn new(microseconds: i64, days: i32, months: i32) -> Self {
PgInterval {
microseconds: microseconds,
days: days,
months: months,
}
}
pub fn from_microseconds(microseconds: i64) -> Self {
Self::new(microseconds, 0, 0)
}
pub fn from_days(days: i32) -> Self {
Self::new(0, days, 0)
}
pub fn from_months(months: i32) -> Self {
Self::new(0, 0, months)
}
}
impl FromSql for PgInterval {
fn from_sql(_ty: &Type, bytes: &[u8]) -> Result<Self, Box<Error + Send + Sync>> {
let mut bytes = bytes.clone();
let ms = try!(bytes.read_i64::<BigEndian>());
let days = try!(bytes.read_i32::<BigEndian>());
let months = try!(bytes.read_i32::<BigEndian>());
Ok(PgInterval::new(ms, days, months))
}
fn accepts(ty: &Type) -> bool {
match *ty {
types::INTERVAL => true,
_ => false,
}
}
}