| 1 | use std::mem; |
| 2 | |
| 3 | use chrono::{NaiveDate, TimeDelta}; |
| 4 | |
| 5 | use crate::decode::Decode; |
| 6 | use crate::encode::{Encode, IsNull}; |
| 7 | use crate::error::BoxDynError; |
| 8 | use crate::types::Type; |
| 9 | use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres}; |
| 10 | |
| 11 | impl Type<Postgres> for NaiveDate { |
| 12 | fn type_info() -> PgTypeInfo { |
| 13 | PgTypeInfo::DATE |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | impl PgHasArrayType for NaiveDate { |
| 18 | fn array_type_info() -> PgTypeInfo { |
| 19 | PgTypeInfo::DATE_ARRAY |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | impl Encode<'_, Postgres> for NaiveDate { |
| 24 | fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> { |
| 25 | // DATE is encoded as the days since epoch |
| 26 | let days: i32 = (*self - postgres_epoch_date()) |
| 27 | .num_days() |
| 28 | .try_into() |
| 29 | .map_err(|_| { |
| 30 | format!("value {self:?} would overflow binary encoding for Postgres DATE") |
| 31 | })?; |
| 32 | |
| 33 | Encode::<Postgres>::encode(days, buf) |
| 34 | } |
| 35 | |
| 36 | fn size_hint(&self) -> usize { |
| 37 | mem::size_of::<i32>() |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | impl<'r> Decode<'r, Postgres> for NaiveDate { |
| 42 | fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> { |
| 43 | Ok(match value.format() { |
| 44 | PgValueFormat::Binary => { |
| 45 | // DATE is encoded as the days since epoch |
| 46 | let days: i32 = Decode::<Postgres>::decode(value)?; |
| 47 | |
| 48 | let days = TimeDelta::try_days(days.into()) |
| 49 | .unwrap_or_else(|| { |
| 50 | unreachable!("BUG: days ({days}) as `i32` multiplied into seconds should not overflow `i64`") |
| 51 | }); |
| 52 | |
| 53 | postgres_epoch_date() + days |
| 54 | } |
| 55 | |
| 56 | PgValueFormat::Text => NaiveDate::parse_from_str(value.as_str()?, "%Y-%m-%d")?, |
| 57 | }) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | #[inline] |
| 62 | fn postgres_epoch_date() -> NaiveDate { |
| 63 | NaiveDate::from_ymd_opt(2000, 1, 1).expect("expected 2000-01-01 to be a valid NaiveDate") |
| 64 | } |