sqlx_postgres/types/chrono/
time.rs

1use crate::decode::Decode;
2use crate::encode::{Encode, IsNull};
3use crate::error::BoxDynError;
4use crate::types::Type;
5use crate::{PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueFormat, PgValueRef, Postgres};
6use chrono::{Duration, NaiveTime};
7use std::mem;
8
9impl Type<Postgres> for NaiveTime {
10    fn type_info() -> PgTypeInfo {
11        PgTypeInfo::TIME
12    }
13}
14
15impl PgHasArrayType for NaiveTime {
16    fn array_type_info() -> PgTypeInfo {
17        PgTypeInfo::TIME_ARRAY
18    }
19}
20
21impl Encode<'_, Postgres> for NaiveTime {
22    fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
23        // TIME is encoded as the microseconds since midnight
24        // NOTE: panic! is on overflow and 1 day does not have enough micros to overflow
25        let us = (*self - NaiveTime::default()).num_microseconds().unwrap();
26
27        Encode::<Postgres>::encode(&us, buf)
28    }
29
30    fn size_hint(&self) -> usize {
31        mem::size_of::<u64>()
32    }
33}
34
35impl<'r> Decode<'r, Postgres> for NaiveTime {
36    fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
37        Ok(match value.format() {
38            PgValueFormat::Binary => {
39                // TIME is encoded as the microseconds since midnight
40                let us: i64 = Decode::<Postgres>::decode(value)?;
41                NaiveTime::default() + Duration::microseconds(us)
42            }
43
44            PgValueFormat::Text => NaiveTime::parse_from_str(value.as_str()?, "%H:%M:%S%.f")?,
45        })
46    }
47}
48
49#[test]
50fn check_naive_time_default_is_midnight() {
51    // Just a canary in case this changes.
52    assert_eq!(
53        NaiveTime::from_hms_opt(0, 0, 0),
54        Some(NaiveTime::default()),
55        "implementation assumes `NaiveTime::default()` equals midnight"
56    );
57}