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,
days,
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<dyn Error + Send + Sync>> {
let mut bytes = <&[u8]>::clone(&bytes);
let ms = bytes.read_i64::<BigEndian>()?;
let days = bytes.read_i32::<BigEndian>()?;
let months = bytes.read_i32::<BigEndian>()?;
Ok(PgInterval::new(ms, days, months))
}
fn accepts(ty: &Type) -> bool {
match *ty {
types::INTERVAL => true,
_ => false,
}
}
}