| 1 | use crate::decode::Decode; |
| 2 | use crate::encode::{Encode, IsNull}; |
| 3 | use crate::error::BoxDynError; |
| 4 | use crate::types::time::PG_EPOCH; |
| 5 | use crate::types::Type; |
| 6 | use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres}; |
| 7 | use std::mem; |
| 8 | use time::macros::format_description; |
| 9 | use time::{Date, Duration}; |
| 10 | |
| 11 | impl Type<Postgres> for Date { |
| 12 | fn type_info() -> PgTypeInfo { |
| 13 | PgTypeInfo::DATE |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | impl PgHasArrayType for Date { |
| 18 | fn array_type_info() -> PgTypeInfo { |
| 19 | PgTypeInfo::DATE_ARRAY |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | impl Encode<'_, Postgres> for Date { |
| 24 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> { |
| 25 | // DATE is encoded as number of days since epoch (2000-01-01) |
| 26 | let days: i32 = (*self - PG_EPOCH).whole_days().try_into().map_err(|_| { |
| 27 | format!("value {self:?} would overflow binary encoding for Postgres DATE") |
| 28 | })?; |
| 29 | Encode::<Postgres>::encode(days, buf) |
| 30 | } |
| 31 | |
| 32 | fn size_hint(&self) -> usize { |
| 33 | mem::size_of::<i32>() |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | impl<'r> Decode<'r, Postgres> for Date { |
| 38 | fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> { |
| 39 | Ok(match value.format() { |
| 40 | PgValueFormat::Binary => { |
| 41 | // DATE is encoded as the days since epoch |
| 42 | let days: i32 = Decode::<Postgres>::decode(value)?; |
| 43 | PG_EPOCH + Duration::days(days.into()) |
| 44 | } |
| 45 | |
| 46 | PgValueFormat::Text => Date::parse( |
| 47 | value.as_str()?, |
| 48 | &format_description!("[year]-[month]-[day]"), |
| 49 | )?, |
| 50 | }) |
| 51 | } |
| 52 | } |