sea_query/extension/postgres/
interval.rs

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
use std::convert::TryFrom;
use std::fmt;

use crate::PgInterval;

impl fmt::Display for PgInterval {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let fields = match self {
            PgInterval::Year => "YEAR",
            PgInterval::Month => "MONTH",
            PgInterval::Day => "DAY",
            PgInterval::Hour => "HOUR",
            PgInterval::Minute => "MINUTE",
            PgInterval::Second => "SECOND",
            PgInterval::YearToMonth => "YEAR TO MONTH",
            PgInterval::DayToHour => "DAY TO HOUR",
            PgInterval::DayToMinute => "DAY TO MINUTE",
            PgInterval::DayToSecond => "DAY TO SECOND",
            PgInterval::HourToMinute => "HOUR TO MINUTE",
            PgInterval::HourToSecond => "HOUR TO SECOND",
            PgInterval::MinuteToSecond => "MINUTE TO SECOND",
        };
        write!(f, "{fields}")
    }
}

impl TryFrom<String> for PgInterval {
    type Error = String;

    fn try_from(field: String) -> Result<Self, Self::Error> {
        PgInterval::try_from(field.as_str())
    }
}

impl TryFrom<&String> for PgInterval {
    type Error = String;

    fn try_from(field: &String) -> Result<Self, Self::Error> {
        PgInterval::try_from(field.as_str())
    }
}

impl TryFrom<&str> for PgInterval {
    type Error = String;

    fn try_from(field: &str) -> Result<Self, Self::Error> {
        match field.trim_start().trim_end().to_uppercase().as_ref() {
            "YEAR" => Ok(PgInterval::Year),
            "MONTH" => Ok(PgInterval::Month),
            "DAY" => Ok(PgInterval::Day),
            "HOUR" => Ok(PgInterval::Hour),
            "MINUTE" => Ok(PgInterval::Minute),
            "SECOND" => Ok(PgInterval::Second),
            "YEAR TO MONTH" => Ok(PgInterval::YearToMonth),
            "DAY TO HOUR" => Ok(PgInterval::DayToHour),
            "DAY TO MINUTE" => Ok(PgInterval::DayToMinute),
            "DAY TO SECOND" => Ok(PgInterval::DayToSecond),
            "HOUR TO MINUTE" => Ok(PgInterval::HourToMinute),
            "HOUR TO SECOND" => Ok(PgInterval::HourToSecond),
            "MINUTE TO SECOND" => Ok(PgInterval::MinuteToSecond),
            field => Err(format!(
                "Cannot turn \"{field}\" into a Postgres interval field",
            )),
        }
    }
}