proof_of_sql_parser/posql_time/
unit.rs

1use super::PoSQLTimestampError;
2use core::fmt;
3use serde::{Deserialize, Serialize};
4
5/// An intermediate type representing the time units from a parsed query
6#[allow(clippy::module_name_repetitions)]
7#[derive(Debug, Clone, Copy, Hash, Serialize, Deserialize, PartialEq, Eq)]
8pub enum PoSQLTimeUnit {
9    /// Represents seconds with precision 0: ex "2024-06-20 12:34:56"
10    Second,
11    /// Represents milliseconds with precision 3: ex "2024-06-20 12:34:56.123"
12    Millisecond,
13    /// Represents microseconds with precision 6: ex "2024-06-20 12:34:56.123456"
14    Microsecond,
15    /// Represents nanoseconds with precision 9: ex "2024-06-20 12:34:56.123456789"
16    Nanosecond,
17}
18
19impl From<PoSQLTimeUnit> for u64 {
20    fn from(value: PoSQLTimeUnit) -> u64 {
21        match value {
22            PoSQLTimeUnit::Second => 0,
23            PoSQLTimeUnit::Millisecond => 3,
24            PoSQLTimeUnit::Microsecond => 6,
25            PoSQLTimeUnit::Nanosecond => 9,
26        }
27    }
28}
29
30impl TryFrom<&str> for PoSQLTimeUnit {
31    type Error = PoSQLTimestampError;
32    fn try_from(value: &str) -> Result<Self, PoSQLTimestampError> {
33        match value {
34            "0" => Ok(PoSQLTimeUnit::Second),
35            "3" => Ok(PoSQLTimeUnit::Millisecond),
36            "6" => Ok(PoSQLTimeUnit::Microsecond),
37            "9" => Ok(PoSQLTimeUnit::Nanosecond),
38            _ => Err(PoSQLTimestampError::UnsupportedPrecision {
39                error: value.into(),
40            }),
41        }
42    }
43}
44
45impl fmt::Display for PoSQLTimeUnit {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            PoSQLTimeUnit::Second => write!(f, "seconds (precision: 0)"),
49            PoSQLTimeUnit::Millisecond => write!(f, "milliseconds (precision: 3)"),
50            PoSQLTimeUnit::Microsecond => write!(f, "microseconds (precision: 6)"),
51            PoSQLTimeUnit::Nanosecond => write!(f, "nanoseconds (precision: 9)"),
52        }
53    }
54}
55
56// allow(deprecated) for the sole purpose of testing that
57// timestamp precision is parsed correctly.
58#[cfg(test)]
59#[allow(deprecated, clippy::missing_panics_doc)]
60mod time_unit_tests {
61    use super::*;
62    use crate::posql_time::{PoSQLTimestamp, PoSQLTimestampError};
63    use chrono::{TimeZone, Utc};
64
65    #[test]
66    fn test_valid_precisions() {
67        assert_eq!(PoSQLTimeUnit::try_from("0"), Ok(PoSQLTimeUnit::Second));
68        assert_eq!(PoSQLTimeUnit::try_from("3"), Ok(PoSQLTimeUnit::Millisecond));
69        assert_eq!(PoSQLTimeUnit::try_from("6"), Ok(PoSQLTimeUnit::Microsecond));
70        assert_eq!(PoSQLTimeUnit::try_from("9"), Ok(PoSQLTimeUnit::Nanosecond));
71    }
72
73    #[test]
74    fn test_invalid_precision() {
75        let invalid_precisions = [
76            "1", "2", "4", "5", "7", "8", "10", "zero", "three", "cat", "-1", "-2",
77        ]; // Testing all your various invalid inputs
78        for &value in &invalid_precisions {
79            let result = PoSQLTimeUnit::try_from(value);
80            assert!(matches!(
81                result,
82                Err(PoSQLTimestampError::UnsupportedPrecision { .. })
83            ));
84        }
85    }
86
87    #[test]
88    fn test_rfc3339_timestamp_with_milliseconds() {
89        let input = "2023-06-26T12:34:56.123Z";
90        let expected = Utc.ymd(2023, 6, 26).and_hms_milli(12, 34, 56, 123);
91        let result = PoSQLTimestamp::try_from(input).unwrap();
92        assert_eq!(result.timeunit(), PoSQLTimeUnit::Millisecond);
93        assert_eq!(
94            result.timestamp().timestamp_millis(),
95            expected.timestamp_millis()
96        );
97    }
98
99    #[test]
100    fn test_rfc3339_timestamp_with_microseconds() {
101        let input = "2023-06-26T12:34:56.123456Z";
102        let expected = Utc.ymd(2023, 6, 26).and_hms_micro(12, 34, 56, 123_456);
103        let result = PoSQLTimestamp::try_from(input).unwrap();
104        assert_eq!(result.timeunit(), PoSQLTimeUnit::Microsecond);
105        assert_eq!(
106            result.timestamp().timestamp_micros(),
107            expected.timestamp_micros()
108        );
109    }
110    #[test]
111    fn test_rfc3339_timestamp_with_nanoseconds() {
112        let input = "2023-06-26T12:34:56.123456789Z";
113        let expected = Utc.ymd(2023, 6, 26).and_hms_nano(12, 34, 56, 123_456_789);
114        let result = PoSQLTimestamp::try_from(input).unwrap();
115        assert_eq!(result.timeunit(), PoSQLTimeUnit::Nanosecond);
116        assert_eq!(
117            result.timestamp().timestamp_nanos_opt().unwrap(),
118            expected.timestamp_nanos_opt().unwrap()
119        );
120    }
121}