Skip to main content

sqlx_postgres/types/
interval.rs

1use std::mem;
2
3use byteorder::{NetworkEndian, ReadBytesExt};
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
11// `PgInterval` is available for direct access to the INTERVAL type
12
13#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash, Default)]
14pub struct PgInterval {
15    pub months: i32,
16    pub days: i32,
17    pub microseconds: i64,
18}
19
20impl PgInterval {
21    pub const INFINITY: Self = Self {
22        months: i32::MAX,
23        days: i32::MAX,
24        microseconds: i64::MAX,
25    };
26
27    pub const NEG_INFINITY: Self = Self {
28        months: i32::MIN,
29        days: i32::MIN,
30        microseconds: i64::MIN,
31    };
32
33    pub fn is_infinite(&self) -> bool {
34        *self == Self::INFINITY || *self == Self::NEG_INFINITY
35    }
36
37    pub fn is_positive_infinity(&self) -> bool {
38        *self == Self::INFINITY
39    }
40
41    pub fn is_negative_infinity(&self) -> bool {
42        *self == Self::NEG_INFINITY
43    }
44}
45
46impl Type<Postgres> for PgInterval {
47    fn type_info() -> PgTypeInfo {
48        PgTypeInfo::INTERVAL
49    }
50}
51
52impl PgHasArrayType for PgInterval {
53    fn array_type_info() -> PgTypeInfo {
54        PgTypeInfo::INTERVAL_ARRAY
55    }
56}
57
58impl<'de> Decode<'de, Postgres> for PgInterval {
59    fn decode(value: PgValueRef<'de>) -> Result<Self, BoxDynError> {
60        match value.format() {
61            PgValueFormat::Binary => {
62                let mut buf = value.as_bytes()?;
63                let microseconds = buf.read_i64::<NetworkEndian>()?;
64                let days = buf.read_i32::<NetworkEndian>()?;
65                let months = buf.read_i32::<NetworkEndian>()?;
66
67                Ok(PgInterval {
68                    months,
69                    days,
70                    microseconds,
71                })
72            }
73
74            // TODO: Implement parsing of text mode
75            PgValueFormat::Text => {
76                Err("not implemented: decode `INTERVAL` in text mode (unprepared queries)".into())
77            }
78        }
79    }
80}
81
82impl Encode<'_, Postgres> for PgInterval {
83    fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
84        buf.extend(&self.microseconds.to_be_bytes());
85        buf.extend(&self.days.to_be_bytes());
86        buf.extend(&self.months.to_be_bytes());
87
88        Ok(IsNull::No)
89    }
90
91    fn size_hint(&self) -> usize {
92        2 * mem::size_of::<i64>()
93    }
94}
95
96// We then implement Encode + Type for std Duration, chrono Duration, and time Duration
97// This is to enable ease-of-use for encoding when its simple
98
99impl Type<Postgres> for std::time::Duration {
100    fn type_info() -> PgTypeInfo {
101        PgTypeInfo::INTERVAL
102    }
103}
104
105impl PgHasArrayType for std::time::Duration {
106    fn array_type_info() -> PgTypeInfo {
107        PgTypeInfo::INTERVAL_ARRAY
108    }
109}
110
111impl Encode<'_, Postgres> for std::time::Duration {
112    fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
113        PgInterval::try_from(*self)?.encode_by_ref(buf)
114    }
115
116    fn size_hint(&self) -> usize {
117        2 * mem::size_of::<i64>()
118    }
119}
120
121impl TryFrom<std::time::Duration> for PgInterval {
122    type Error = BoxDynError;
123
124    /// Convert a `std::time::Duration` to a `PgInterval`
125    ///
126    /// This returns an error if there is a loss of precision using nanoseconds or if there is a
127    /// microsecond overflow.
128    fn try_from(value: std::time::Duration) -> Result<Self, BoxDynError> {
129        if !value.as_nanos().is_multiple_of(1000) {
130            return Err("PostgreSQL `INTERVAL` does not support nanoseconds precision".into());
131        }
132
133        Ok(Self {
134            months: 0,
135            days: 0,
136            microseconds: value.as_micros().try_into()?,
137        })
138    }
139}
140
141#[cfg(feature = "chrono")]
142impl Type<Postgres> for chrono::Duration {
143    fn type_info() -> PgTypeInfo {
144        PgTypeInfo::INTERVAL
145    }
146}
147
148#[cfg(feature = "chrono")]
149impl PgHasArrayType for chrono::Duration {
150    fn array_type_info() -> PgTypeInfo {
151        PgTypeInfo::INTERVAL_ARRAY
152    }
153}
154
155#[cfg(feature = "chrono")]
156impl Encode<'_, Postgres> for chrono::Duration {
157    fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
158        let pg_interval = PgInterval::try_from(*self)?;
159        pg_interval.encode_by_ref(buf)
160    }
161
162    fn size_hint(&self) -> usize {
163        2 * mem::size_of::<i64>()
164    }
165}
166
167#[cfg(feature = "chrono")]
168impl TryFrom<chrono::Duration> for PgInterval {
169    type Error = BoxDynError;
170
171    /// Convert a `chrono::Duration` to a `PgInterval`.
172    ///
173    /// This returns an error if there is a loss of precision using nanoseconds or if there is a
174    /// nanosecond overflow.
175    fn try_from(value: chrono::Duration) -> Result<Self, BoxDynError> {
176        value
177            .num_nanoseconds()
178            .map_or::<Result<_, Self::Error>, _>(
179                Err("Overflow has occurred for PostgreSQL `INTERVAL`".into()),
180                |nanoseconds| {
181                    if nanoseconds % 1000 != 0 {
182                        return Err(
183                            "PostgreSQL `INTERVAL` does not support nanoseconds precision".into(),
184                        );
185                    }
186                    Ok(())
187                },
188            )?;
189
190        value.num_microseconds().map_or(
191            Err("Overflow has occurred for PostgreSQL `INTERVAL`".into()),
192            |microseconds| {
193                Ok(Self {
194                    months: 0,
195                    days: 0,
196                    microseconds,
197                })
198            },
199        )
200    }
201}
202
203#[cfg(feature = "time")]
204impl Type<Postgres> for time::Duration {
205    fn type_info() -> PgTypeInfo {
206        PgTypeInfo::INTERVAL
207    }
208}
209
210#[cfg(feature = "time")]
211impl PgHasArrayType for time::Duration {
212    fn array_type_info() -> PgTypeInfo {
213        PgTypeInfo::INTERVAL_ARRAY
214    }
215}
216
217#[cfg(feature = "time")]
218impl Encode<'_, Postgres> for time::Duration {
219    fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
220        let pg_interval = PgInterval::try_from(*self)?;
221        pg_interval.encode_by_ref(buf)
222    }
223
224    fn size_hint(&self) -> usize {
225        2 * mem::size_of::<i64>()
226    }
227}
228
229#[cfg(feature = "time")]
230impl TryFrom<time::Duration> for PgInterval {
231    type Error = BoxDynError;
232
233    /// Convert a `time::Duration` to a `PgInterval`.
234    ///
235    /// This returns an error if there is a loss of precision using nanoseconds or if there is a
236    /// microsecond overflow.
237    fn try_from(value: time::Duration) -> Result<Self, BoxDynError> {
238        if value.whole_nanoseconds() % 1000 != 0 {
239            return Err("PostgreSQL `INTERVAL` does not support nanoseconds precision".into());
240        }
241
242        Ok(Self {
243            months: 0,
244            days: 0,
245            microseconds: value.whole_microseconds().try_into()?,
246        })
247    }
248}
249
250#[test]
251fn test_encode_interval() {
252    let mut buf = PgArgumentBuffer::default();
253
254    let interval = PgInterval {
255        months: 0,
256        days: 0,
257        microseconds: 0,
258    };
259    assert!(matches!(
260        Encode::<Postgres>::encode(interval, &mut buf),
261        Ok(IsNull::No)
262    ));
263    assert_eq!(&**buf, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
264    buf.clear();
265
266    let interval = PgInterval {
267        months: 0,
268        days: 0,
269        microseconds: 1_000,
270    };
271    assert!(matches!(
272        Encode::<Postgres>::encode(interval, &mut buf),
273        Ok(IsNull::No)
274    ));
275    assert_eq!(&**buf, [0, 0, 0, 0, 0, 0, 3, 232, 0, 0, 0, 0, 0, 0, 0, 0]);
276    buf.clear();
277
278    let interval = PgInterval {
279        months: 0,
280        days: 0,
281        microseconds: 1_000_000,
282    };
283    assert!(matches!(
284        Encode::<Postgres>::encode(interval, &mut buf),
285        Ok(IsNull::No)
286    ));
287    assert_eq!(&**buf, [0, 0, 0, 0, 0, 15, 66, 64, 0, 0, 0, 0, 0, 0, 0, 0]);
288    buf.clear();
289
290    let interval = PgInterval {
291        months: 0,
292        days: 0,
293        microseconds: 3_600_000_000,
294    };
295    assert!(matches!(
296        Encode::<Postgres>::encode(interval, &mut buf),
297        Ok(IsNull::No)
298    ));
299    assert_eq!(
300        &**buf,
301        [0, 0, 0, 0, 214, 147, 164, 0, 0, 0, 0, 0, 0, 0, 0, 0]
302    );
303    buf.clear();
304
305    let interval = PgInterval {
306        months: 0,
307        days: 1,
308        microseconds: 0,
309    };
310    assert!(matches!(
311        Encode::<Postgres>::encode(interval, &mut buf),
312        Ok(IsNull::No)
313    ));
314    assert_eq!(&**buf, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]);
315    buf.clear();
316
317    let interval = PgInterval {
318        months: 1,
319        days: 0,
320        microseconds: 0,
321    };
322    assert!(matches!(
323        Encode::<Postgres>::encode(interval, &mut buf),
324        Ok(IsNull::No)
325    ));
326    assert_eq!(&**buf, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
327    buf.clear();
328
329    assert_eq!(
330        PgInterval::default(),
331        PgInterval {
332            months: 0,
333            days: 0,
334            microseconds: 0,
335        }
336    );
337}
338
339#[test]
340fn test_pginterval_std() {
341    // Case for positive duration
342    let interval = PgInterval {
343        days: 0,
344        months: 0,
345        microseconds: 27_000,
346    };
347    assert_eq!(
348        &PgInterval::try_from(std::time::Duration::from_micros(27_000)).unwrap(),
349        &interval
350    );
351
352    // Case when precision loss occurs
353    assert!(PgInterval::try_from(std::time::Duration::from_nanos(27_000_001)).is_err());
354
355    // Case when microsecond overflow occurs
356    assert!(PgInterval::try_from(std::time::Duration::from_secs(20_000_000_000_000)).is_err());
357}
358
359#[test]
360fn test_pginterval_infinity() {
361    assert!(PgInterval::INFINITY.is_infinite());
362    assert!(PgInterval::NEG_INFINITY.is_infinite());
363    assert!(PgInterval::INFINITY.is_positive_infinity());
364    assert!(!PgInterval::NEG_INFINITY.is_positive_infinity());
365    assert!(!PgInterval::INFINITY.is_negative_infinity());
366    assert!(PgInterval::NEG_INFINITY.is_negative_infinity());
367    assert!(!PgInterval::default().is_infinite());
368
369    // verify values match what PostgreSQL expects
370    assert_eq!(PgInterval::INFINITY.microseconds, i64::MAX);
371    assert_eq!(PgInterval::INFINITY.days, i32::MAX);
372    assert_eq!(PgInterval::INFINITY.months, i32::MAX);
373    assert_eq!(PgInterval::NEG_INFINITY.microseconds, i64::MIN);
374    assert_eq!(PgInterval::NEG_INFINITY.days, i32::MIN);
375    assert_eq!(PgInterval::NEG_INFINITY.months, i32::MIN);
376}
377
378#[test]
379#[cfg(feature = "chrono")]
380fn test_pginterval_chrono() {
381    // Case for positive duration
382    let interval = PgInterval {
383        days: 0,
384        months: 0,
385        microseconds: 27_000,
386    };
387    assert_eq!(
388        &PgInterval::try_from(chrono::Duration::microseconds(27_000)).unwrap(),
389        &interval
390    );
391
392    // Case for negative duration
393    let interval = PgInterval {
394        days: 0,
395        months: 0,
396        microseconds: -27_000,
397    };
398    assert_eq!(
399        &PgInterval::try_from(chrono::Duration::microseconds(-27_000)).unwrap(),
400        &interval
401    );
402
403    // Case when precision loss occurs
404    assert!(PgInterval::try_from(chrono::Duration::nanoseconds(27_000_001)).is_err());
405    assert!(PgInterval::try_from(chrono::Duration::nanoseconds(-27_000_001)).is_err());
406
407    // Case when nanosecond overflow occurs
408    assert!(PgInterval::try_from(chrono::Duration::seconds(10_000_000_000)).is_err());
409    assert!(PgInterval::try_from(chrono::Duration::seconds(-10_000_000_000)).is_err());
410}
411
412#[test]
413#[cfg(feature = "time")]
414fn test_pginterval_time() {
415    // Case for positive duration
416    let interval = PgInterval {
417        days: 0,
418        months: 0,
419        microseconds: 27_000,
420    };
421    assert_eq!(
422        &PgInterval::try_from(time::Duration::microseconds(27_000)).unwrap(),
423        &interval
424    );
425
426    // Case for negative duration
427    let interval = PgInterval {
428        days: 0,
429        months: 0,
430        microseconds: -27_000,
431    };
432    assert_eq!(
433        &PgInterval::try_from(time::Duration::microseconds(-27_000)).unwrap(),
434        &interval
435    );
436
437    // Case when precision loss occurs
438    assert!(PgInterval::try_from(time::Duration::nanoseconds(27_000_001)).is_err());
439    assert!(PgInterval::try_from(time::Duration::nanoseconds(-27_000_001)).is_err());
440
441    // Case when microsecond overflow occurs
442    assert!(PgInterval::try_from(time::Duration::seconds(10_000_000_000_000)).is_err());
443    assert!(PgInterval::try_from(time::Duration::seconds(-10_000_000_000_000)).is_err());
444}