1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
use crate::decode::Decode;
use crate::encode::{Encode, IsNull};
use crate::error::BoxDynError;
use crate::postgres::{PgArgumentBuffer, PgTypeInfo, PgValueFormat, PgValueRef, Postgres};
use crate::types::Type;
use byteorder::{BigEndian, ReadBytesExt};
use std::io::Cursor;
use std::mem;

#[cfg(feature = "time")]
type DefaultTime = ::time::Time;

#[cfg(all(not(feature = "time"), feature = "chrono"))]
type DefaultTime = ::chrono::NaiveTime;

#[cfg(feature = "time")]
type DefaultOffset = ::time::UtcOffset;

#[cfg(all(not(feature = "time"), feature = "chrono"))]
type DefaultOffset = ::chrono::FixedOffset;

/// Represents a moment of time, in a specified timezone.
///
/// # Warning
///
/// `PgTimeTz` provides `TIMETZ` and is supported only for reading from legacy databases.
/// [PostgreSQL recommends] to use `TIMESTAMPTZ` instead.
///
/// [PostgreSQL recommends]: https://wiki.postgresql.org/wiki/Don't_Do_This#Don.27t_use_timetz
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct PgTimeTz<Time = DefaultTime, Offset = DefaultOffset> {
    pub time: Time,
    pub offset: Offset,
}

impl<Time, Offset> Type<Postgres> for [PgTimeTz<Time, Offset>]
where
    PgTimeTz<Time, Offset>: Type<Postgres>,
{
    fn type_info() -> PgTypeInfo {
        PgTypeInfo::TIMETZ_ARRAY
    }
}

impl<Time, Offset> Type<Postgres> for Vec<PgTimeTz<Time, Offset>>
where
    PgTimeTz<Time, Offset>: Type<Postgres>,
{
    fn type_info() -> PgTypeInfo {
        PgTypeInfo::TIMETZ_ARRAY
    }
}

#[cfg(feature = "chrono")]
mod chrono {
    use super::*;
    use ::chrono::{DateTime, Duration, FixedOffset, NaiveTime};

    impl Type<Postgres> for PgTimeTz<NaiveTime, FixedOffset> {
        fn type_info() -> PgTypeInfo {
            PgTypeInfo::TIMETZ
        }
    }

    impl Encode<'_, Postgres> for PgTimeTz<NaiveTime, FixedOffset> {
        fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
            let _ = <NaiveTime as Encode<'_, Postgres>>::encode(self.time, buf);
            let _ = <i32 as Encode<'_, Postgres>>::encode(self.offset.utc_minus_local(), buf);

            IsNull::No
        }

        fn size_hint(&self) -> usize {
            mem::size_of::<i64>() + mem::size_of::<i32>()
        }
    }

    impl<'r> Decode<'r, Postgres> for PgTimeTz<NaiveTime, FixedOffset> {
        fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
            match value.format() {
                PgValueFormat::Binary => {
                    let mut buf = Cursor::new(value.as_bytes()?);

                    // TIME is encoded as the microseconds since midnight
                    let us = buf.read_i64::<BigEndian>()?;
                    let time = NaiveTime::from_hms(0, 0, 0) + Duration::microseconds(us);

                    // OFFSET is encoded as seconds from UTC
                    let seconds = buf.read_i32::<BigEndian>()?;

                    Ok(PgTimeTz {
                        time,
                        offset: FixedOffset::west(seconds),
                    })
                }

                PgValueFormat::Text => {
                    let s = value.as_str()?;

                    let mut tmp = String::with_capacity(11 + s.len());
                    tmp.push_str("2001-07-08 ");
                    tmp.push_str(s);

                    let dt = 'out: loop {
                        let mut err = None;

                        for fmt in &["%Y-%m-%d %H:%M:%S%.f%#z", "%Y-%m-%d %H:%M:%S%.f"] {
                            match DateTime::parse_from_str(&tmp, fmt) {
                                Ok(dt) => {
                                    break 'out dt;
                                }

                                Err(error) => {
                                    err = Some(error);
                                }
                            }
                        }

                        return Err(err.unwrap().into());
                    };

                    let time = dt.time();
                    let offset = *dt.offset();

                    Ok(PgTimeTz { time, offset })
                }
            }
        }
    }
}

#[cfg(feature = "time")]
mod time {
    use super::*;
    use ::time::{Duration, Time, UtcOffset};

    impl Type<Postgres> for PgTimeTz<Time, UtcOffset> {
        fn type_info() -> PgTypeInfo {
            PgTypeInfo::TIMETZ
        }
    }

    impl Encode<'_, Postgres> for PgTimeTz<Time, UtcOffset> {
        fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
            let _ = <Time as Encode<'_, Postgres>>::encode(self.time, buf);
            let _ = <i32 as Encode<'_, Postgres>>::encode(-self.offset.as_seconds(), buf);

            IsNull::No
        }

        fn size_hint(&self) -> usize {
            mem::size_of::<i64>() + mem::size_of::<i32>()
        }
    }

    impl<'r> Decode<'r, Postgres> for PgTimeTz<Time, UtcOffset> {
        fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
            match value.format() {
                PgValueFormat::Binary => {
                    let mut buf = Cursor::new(value.as_bytes()?);

                    // TIME is encoded as the microseconds since midnight
                    let us = buf.read_i64::<BigEndian>()?;
                    let time = Time::midnight() + Duration::microseconds(us);

                    // OFFSET is encoded as seconds from UTC
                    let seconds = buf.read_i32::<BigEndian>()?;

                    Ok(PgTimeTz {
                        time,
                        offset: UtcOffset::west_seconds(seconds as u32),
                    })
                }

                PgValueFormat::Text => {
                    // the `time` crate has a limited ability to parse and can't parse the
                    // timezone format
                    Err("reading a `TIMETZ` value in text format is not supported.".into())
                }
            }
        }
    }
}