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
use std::alloc::Layout;
use std::ops::{Deref, DerefMut};
use rbson::Bson;
use rbson::spec::BinarySubtype;
use serde::{Deserializer, Serializer};
use serde::de::Error;
use sqlx_core::types::time;

/// Rbatis Timestamp
/// Rust type                Postgres type(s)
/// time::OffsetDateTime      TIMESTAMPTZ
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct TimestampZ {
    pub inner: time::OffsetDateTime,
}

impl From<time::OffsetDateTime> for TimestampZ {
    fn from(arg: time::OffsetDateTime) -> Self {
        Self {
            inner: arg
        }
    }
}

impl From<&time::OffsetDateTime> for TimestampZ {
    fn from(arg: &time::OffsetDateTime) -> Self {
        Self {
            inner: arg.clone()
        }
    }
}

impl serde::Serialize for TimestampZ {
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
        return serializer.serialize_str(&format!("TimestampZ({})", self.inner.unix_timestamp()));
    }
}

impl<'de> serde::Deserialize<'de> for TimestampZ {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
        match Bson::deserialize(deserializer)? {
            Bson::String(s) => {
                if s.starts_with("TimestampZ(") && s.ends_with(")") {
                    let inner_data = &s["TimestampZ(".len()..(s.len() - 1)];
                    let timestamp = inner_data.parse::<i64>().or_else(|e| Err(D::Error::custom(e.to_string())))?;
                    return Ok(Self {
                        inner: time::OffsetDateTime::from_unix_timestamp(timestamp),
                    });
                } else {
                    let timestamp = s.parse::<i64>().or_else(|e| Err(D::Error::custom(e.to_string())))?;
                    return Ok(Self {
                        inner: time::OffsetDateTime::from_unix_timestamp(timestamp),
                    });
                }
            }
            Bson::Int64(data) => {
                return Ok(Self::from_unix_timestamp(data));
            }
            _ => {
                Err(D::Error::custom("deserialize un supported bson type!"))
            }
        }
    }
}

impl TimestampZ {
    pub fn as_timestamp(arg: &rbson::Timestamp) -> i64 {
        let upper = (arg.time.to_le() as u64) << 32;
        let lower = arg.increment.to_le() as u64;
        (upper | lower) as i64
    }

    pub fn from_le_i64(val: i64) -> rbson::Timestamp {
        let ts = val.to_le();
        rbson::Timestamp {
            time: ((ts as u64) >> 32) as u32,
            increment: (ts & 0xFFFF_FFFF) as u32,
        }
    }
}

impl From<rbson::Timestamp> for TimestampZ {
    fn from(data: rbson::Timestamp) -> Self {
        let offset = time::OffsetDateTime::from_unix_timestamp(TimestampZ::as_timestamp(&data));
        Self {
            inner: offset
        }
    }
}

impl std::fmt::Display for TimestampZ {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl std::fmt::Debug for TimestampZ {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.inner.fmt(f)
    }
}

impl Deref for TimestampZ {
    type Target = time::OffsetDateTime;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for TimestampZ {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl TimestampZ {
    pub fn now() -> Self {
        Self {
            inner: time::OffsetDateTime::from_unix_timestamp(time::OffsetDateTime::now().unix_timestamp())
        }
    }

    pub fn now_utc() -> Self {
        Self {
            inner: time::OffsetDateTime::from_unix_timestamp(time::OffsetDateTime::now_utc().unix_timestamp())
        }
    }

    pub fn now_local() -> Self {
        Self {
            inner: time::OffsetDateTime::from_unix_timestamp(time::OffsetDateTime::now_local().unix_timestamp())
        }
    }

    /// create from str
    pub fn from_str(arg: &str) -> Result<Self, crate::error::Error> {
        let inner = time::OffsetDateTime::parse(arg, "%F %T %z")?;
        Ok(Self {
            inner: inner
        })
    }


    pub fn timestamp_millis(&self) -> i64 {
        self.inner.unix_timestamp()
    }

    pub fn from_unix_timestamp(arg: i64) -> TimestampZ {
        Self {
            inner: time::OffsetDateTime::from_unix_timestamp(arg)
        }
    }
}

#[cfg(test)]
mod test {
    use crate::types::TimestampZ;

    #[test]
    fn test_native() {
        let dt = TimestampZ::now_utc();
        let s = rbson::to_bson(&dt).unwrap();
        let dt_new: TimestampZ = rbson::from_bson(s).unwrap();
        println!("{},{}", dt.timestamp_millis(), dt_new.timestamp_millis());
        assert_eq!(dt, dt_new);
    }

    #[test]
    fn test_ser_de() {
        let b = TimestampZ::now();
        let bsons = rbson::to_bson(&b).unwrap();
        let b_de: TimestampZ = rbson::from_bson(bsons).unwrap();
        assert_eq!(b, b_de);
    }
}