sqlx_postgres/types/chrono/
date.rs

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