summaryrefslogtreecommitdiff
path: root/schist_models/src/datetime_utc.rs
blob: 9b63145a72338fadda08ad184b789e12013cae74 (plain)
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use std::{fmt::Display, str::FromStr};

use anyhow::{Context, Result};
use chrono::{DateTime, Datelike as ChronoDatelike, NaiveDate, Timelike as ChronoTimelike, Utc};
use diesel::{
    backend::Backend,
    deserialize::{self, FromSql, FromSqlRow},
    expression::AsExpression,
    serialize::{self, ToSql},
    sql_types::Text,
    sqlite::Sqlite,
};
use serde::{Deserialize, Serialize};

use schist_traits::{dateable::Dateable, nowlike::Nowlike, timeable::Timeable};

#[derive(
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Serialize,
    Deserialize,
    Clone,
    Debug,
    AsExpression,
    FromSqlRow,
)]
#[diesel(sql_type=Text)]
pub struct DatetimeUtc {
    chrono_datetime_utc: DateTime<Utc>,
}

impl DatetimeUtc {
    pub fn from_ymd_and_hms(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32) -> Result<Self> {
        Ok(Self { chrono_datetime_utc: NaiveDate
            ::from_ymd_opt(year, month, day)
            .with_context(|| format!("failed to construct datetime from ymd {:04}-{:02}-{:02}", year, month, day))?
            .and_hms_opt(hour, min, sec)
            .with_context(|| format!("failed to construct datetime from hms {:02}:{:02}:{:02}", hour, min, sec))?
            .and_utc()
        })
    }
}

impl FromStr for DatetimeUtc {
    type Err = anyhow::Error;

    /// Constructs DatetimeUtc from a date string in ISO format, in UTC
    /// Example: "2024-10-24T10:30:00.000" -> 10.30am 24 Oct 2024 UTC
    fn from_str(datetime_str: &str) -> Result<Self> {
        let chrono_datetime_utc = datetime_str.parse::<DateTime<Utc>>()?;
        Ok(Self {
            chrono_datetime_utc,
        })
    }
}

impl Display for DatetimeUtc {
    /// Converts to a date string in ISO format, in UTC
    /// Example: 10.30am 24 Oct 2024 UTC -> "2024-10-24T10:30:00.000Z"
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.chrono_datetime_utc.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
    }
}

impl Nowlike for DatetimeUtc {
    fn now() -> Self {
        let now = Utc::now();
        Self::from_ymd_and_hms(
            now.year(),
            now.month(),
            now.day(),
            now.hour(),
            now.minute(),
            now.second(),
        ).unwrap()
    }
}

impl Dateable for DatetimeUtc {
    fn year(&self) -> i32 {
        self.chrono_datetime_utc.year()
    }

    fn month(&self) -> u32 {
        self.chrono_datetime_utc.month()
    }

    fn day(&self) -> u32 {
        self.chrono_datetime_utc.day()
    }
}

impl Timeable for DatetimeUtc {
    fn hour(&self) -> u32 {
        self.chrono_datetime_utc.hour()
    }

    fn minute(&self) -> u32 {
        self.chrono_datetime_utc.minute()
    }

    fn second(&self) -> u32 {
        self.chrono_datetime_utc.second()
    }
}

impl ToSql<Text, Sqlite> for DatetimeUtc {
    fn to_sql<'b>(
        &'b self,
        out: &mut diesel::serialize::Output<'b, '_, Sqlite>,
    ) -> serialize::Result {
        out.set_value::<String>(self.to_string());
        Ok(serialize::IsNull::No)
    }
}

impl FromSql<Text, Sqlite> for DatetimeUtc {
    fn from_sql(bytes: <Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<DatetimeUtc> {
        let str = <String as FromSql<Text, Sqlite>>::from_sql(bytes)?;
        Ok(str.parse()?)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn when_from_ymd_and_hms_then_ymd_and_hms_are_as_expected() {
        let datetime_utc = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 12, 55, 16);

        assert!(datetime_utc.is_ok());
        let date_utc = datetime_utc.unwrap();
        assert_eq!(date_utc.year(), 1970);
        assert_eq!(date_utc.month(), 11);
        assert_eq!(date_utc.day(), 23);
        assert_eq!(date_utc.hour(), 12);
        assert_eq!(date_utc.minute(), 55);
        assert_eq!(date_utc.second(), 16);
    }

    #[test]
    fn when_from_ymd_and_hms_then_to_string_as_expected() {
        let date_utc = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 12, 55, 16);

        assert!(date_utc.is_ok());
        assert_eq!(date_utc.unwrap().to_string(), "1970-11-23T12:55:16.000Z")
    }

    #[test]
    fn when_with_invalid_ymd_and_hms_then_err() {
        let datetime_utc_1 = DatetimeUtc::from_ymd_and_hms(1970, 0, 23, 12, 55, 16);
        let datetime_utc_2 = DatetimeUtc::from_ymd_and_hms(1970, 13, 23, 12, 55, 16);
        let datetime_utc_3 = DatetimeUtc::from_ymd_and_hms(1970, 11, 0, 12, 55, 16);
        let datetime_utc_4 = DatetimeUtc::from_ymd_and_hms(1970, 11, 31, 12, 55, 16);
        let datetime_utc_5 = DatetimeUtc::from_ymd_and_hms(1971, 2, 29, 12, 55, 16);
        let datetime_utc_6 = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 25, 0, 0);
        let datetime_utc_7 = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 0, 61, 0);
        let datetime_utc_8 = DatetimeUtc::from_ymd_and_hms(1970, 11, 23, 0, 0, 61);

        assert!(datetime_utc_1.is_err());
        assert_eq!(datetime_utc_1.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-00-23");
        assert!(datetime_utc_2.is_err());
        assert_eq!(datetime_utc_2.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-13-23");
        assert!(datetime_utc_3.is_err());
        assert_eq!(datetime_utc_3.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-11-00");
        assert!(datetime_utc_4.is_err());
        assert_eq!(datetime_utc_4.unwrap_err().to_string(), "failed to construct datetime from ymd 1970-11-31");
        assert!(datetime_utc_5.is_err());
        assert_eq!(datetime_utc_5.unwrap_err().to_string(), "failed to construct datetime from ymd 1971-02-29");
        assert!(datetime_utc_6.is_err());
        assert_eq!(datetime_utc_6.unwrap_err().to_string(), "failed to construct datetime from hms 25:00:00");
        assert!(datetime_utc_7.is_err());
        assert_eq!(datetime_utc_7.unwrap_err().to_string(), "failed to construct datetime from hms 00:61:00");
        assert!(datetime_utc_8.is_err());
        assert_eq!(datetime_utc_8.unwrap_err().to_string(), "failed to construct datetime from hms 00:00:61");
    }

    #[test]
    fn when_from_string_then_ymd_and_hms_are_as_expected() {
        let date_utc: Result<DatetimeUtc> = "1970-11-23T12:55:16.000Z".parse();

        assert!(date_utc.is_ok());
        let datetime_utc = date_utc.unwrap();
        assert_eq!(datetime_utc.year(), 1970);
        assert_eq!(datetime_utc.month(), 11);
        assert_eq!(datetime_utc.day(), 23);
        assert_eq!(datetime_utc.hour(), 12);
        assert_eq!(datetime_utc.minute(), 55);
        assert_eq!(datetime_utc.second(), 16);
    }

    #[test]
    fn when_from_string_then_to_string_as_expected() {
        let datetime_utc: Result<DatetimeUtc> = "1970-11-23T12:55:16.000Z".parse();

        assert!(datetime_utc.is_ok());
        assert_eq!(datetime_utc.unwrap().to_string(), "1970-11-23T12:55:16.000Z")
    }

    #[test]
    fn when_from_invalid_string_then_err() {
        let datetime_utc_1: Result<DatetimeUtc> = "1970-00-23T00:00:00.000Z".parse();
        let datetime_utc_2: Result<DatetimeUtc> = "1970-13-23T00:00:00.000Z".parse();
        let datetime_utc_3: Result<DatetimeUtc> = "1970-11-0T00:00:00.000Z".parse();
        let datetime_utc_4: Result<DatetimeUtc> = "1970-11-31T00:00:00.000Z".parse();
        let datetime_utc_5: Result<DatetimeUtc> = "1971-02-29T00:00:00.000Z".parse();
        let datetime_utc_6: Result<DatetimeUtc> = "1970-11-23T25:00:00.000Z".parse();
        let datetime_utc_7: Result<DatetimeUtc> = "1970-11-23T00:61:00.000Z".parse();
        let datetime_utc_8: Result<DatetimeUtc> = "1970-11-23T00:00:61.000Z".parse();

        assert!(datetime_utc_1.is_err());
        assert!(datetime_utc_2.is_err());
        assert!(datetime_utc_3.is_err());
        assert!(datetime_utc_4.is_err());
        assert!(datetime_utc_5.is_err());
        assert!(datetime_utc_6.is_err());
        assert!(datetime_utc_7.is_err());
        assert!(datetime_utc_8.is_err());
    }
}