tdm_server_rust/utils/
legacy_time.rs1use chrono::{DateTime, NaiveDateTime, Utc};
15use sqlx::{postgres::PgRow, Row};
16
17pub fn db_to_api_utc(stored: DateTime<Utc>) -> DateTime<Utc> {
19 stored
20}
21
22pub fn db_to_api_utc_opt(stored: Option<DateTime<Utc>>) -> Option<DateTime<Utc>> {
24 stored
25}
26
27pub fn naive_db_to_api_utc(naive: NaiveDateTime) -> DateTime<Utc> {
29 naive.and_utc()
30}
31
32pub fn naive_db_to_api_utc_opt(naive: Option<NaiveDateTime>) -> Option<DateTime<Utc>> {
34 naive.map(naive_db_to_api_utc)
35}
36
37pub fn api_to_db_utc(instant: DateTime<Utc>) -> DateTime<Utc> {
39 instant
40}
41
42pub fn api_to_db_naive(instant: DateTime<Utc>) -> NaiveDateTime {
44 instant.naive_utc()
45}
46
47pub fn try_dt(row: &PgRow, col: &str) -> Option<DateTime<Utc>> {
49 if let Ok(n) = row.try_get::<NaiveDateTime, _>(col) {
50 return Some(n.and_utc());
51 }
52 row.try_get::<DateTime<Utc>, _>(col).ok()
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58 use chrono::TimeZone;
59
60 #[test]
61 fn db_to_api_utc_is_identity() {
62 let t = Utc.with_ymd_and_hms(2024, 6, 1, 10, 0, 0).unwrap();
63 assert_eq!(db_to_api_utc(t), t);
64 }
65
66 #[test]
67 fn naive_db_to_api_utc_treats_naive_as_utc() {
68 let naive = chrono::NaiveDate::from_ymd_opt(2024, 6, 1)
69 .unwrap()
70 .and_hms_opt(10, 0, 0)
71 .unwrap();
72 let expected = Utc.with_ymd_and_hms(2024, 6, 1, 10, 0, 0).unwrap();
73 assert_eq!(naive_db_to_api_utc(naive), expected);
74 }
75}