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
//! Extra types that represent SQL data values but with extra from/to implementations for `OdbcType` so they can be bound to query parameter

use std::fmt;

// Allow for custom type implementation
pub use odbc::{ffi, OdbcType};

#[cfg(feature = "chrono")]
mod sql_timestamp {
    use super::*;
    use chrono::naive::{NaiveDate, NaiveDateTime};
    use chrono::{Datelike, Timelike};
    use odbc::SqlTimestamp;

    /// `SqlTimestamp` type that can be created from number of seconds since epoch as represented by `f64` value.
    #[derive(Debug)]
    pub struct UnixTimestamp(SqlTimestamp);

    impl UnixTimestamp {
        pub fn as_naive_date_time(&self) -> NaiveDateTime {
            NaiveDate::from_ymd(
                i32::from(self.0.year),
                u32::from(self.0.month),
                u32::from(self.0.day),
            )
            .and_hms_nano(
                u32::from(self.0.hour),
                u32::from(self.0.minute),
                u32::from(self.0.second),
                self.0.fraction,
            )
        }

        pub fn into_inner(self) -> SqlTimestamp {
            self.0
        }
    }

    impl From<f64> for UnixTimestamp {
        fn from(ts: f64) -> UnixTimestamp {
            let ts =
                NaiveDateTime::from_timestamp(ts as i64, (ts.fract() * 1_000_000_000.0) as u32);
            ts.into()
        }
    }

    impl From<NaiveDateTime> for UnixTimestamp {
        fn from(value: NaiveDateTime) -> UnixTimestamp {
            UnixTimestamp(SqlTimestamp {
                day: value.day() as u16,
                month: value.month() as u16,
                year: value.year() as i16,
                hour: value.hour() as u16,
                minute: value.minute() as u16,
                second: value.second() as u16,
                fraction: value.nanosecond(),
            })
        }
    }

    unsafe impl<'a> OdbcType<'a> for UnixTimestamp {
        fn sql_data_type() -> ffi::SqlDataType {
            SqlTimestamp::sql_data_type()
        }
        fn c_data_type() -> ffi::SqlCDataType {
            SqlTimestamp::c_data_type()
        }

        fn convert(buffer: &'a [u8]) -> Self {
            UnixTimestamp(SqlTimestamp::convert(buffer))
        }

        fn column_size(&self) -> ffi::SQLULEN {
            self.0.column_size()
        }
        fn value_ptr(&self) -> ffi::SQLPOINTER {
            self.0.value_ptr()
        }
    }

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

        #[test]
        fn test_timestamp() {
            let ts: UnixTimestamp = 1547115460.2291234.into();

            assert_eq!(ts.0.year, 2019);
            assert_eq!(ts.0.month, 1);
            assert_eq!(ts.0.day, 10);
            assert_eq!(ts.0.hour, 10);
            assert_eq!(ts.0.minute, 17);
            assert_eq!(ts.0.second, 40);
            assert_eq!(ts.0.fraction / 1000, 229123); // need to round it up as precision is not best
        }

        #[test]
        fn test_timestamp_as_date_time() {
            let ts: UnixTimestamp = 1547115460.2291234.into();
            assert_eq!(ts.as_naive_date_time().timestamp_millis(), 1547115460229);
        }
    }
}

#[cfg(feature = "chrono")]
pub use sql_timestamp::*;

use std::borrow::Cow;

/// Owned or borrowed string that can be bound as statement parameter.
#[derive(PartialEq, Eq, Debug)]
pub struct CowString<'s>(pub Cow<'s, str>);

impl<'s> From<String> for CowString<'s> {
    fn from(s: String) -> CowString<'static> {
        CowString(Cow::Owned(s))
    }
}

impl<'s> From<&'s str> for CowString<'s> {
    fn from(s: &'s str) -> CowString<'s> {
        CowString(Cow::Borrowed(s))
    }
}

impl<'s> From<Cow<'s, str>> for CowString<'s> {
    fn from(s: Cow<'s, str>) -> CowString<'s> {
        CowString(s)
    }
}

unsafe impl<'s> OdbcType<'s> for CowString<'s> {
    fn sql_data_type() -> ffi::SqlDataType {
        String::sql_data_type()
    }
    fn c_data_type() -> ffi::SqlCDataType {
        String::c_data_type()
    }

    fn convert(buffer: &'s [u8]) -> Self {
        CowString(Cow::Owned(String::convert(buffer)))
    }

    fn column_size(&self) -> ffi::SQLULEN {
        self.0.as_ref().column_size()
    }

    fn value_ptr(&self) -> ffi::SQLPOINTER {
        self.0.as_ref().value_ptr()
    }
}

/// UTF-16 encoded string that can be bound as statement parameter.
#[derive(PartialEq, Eq)]
pub struct StringUtf16(pub Vec<u16>);

impl fmt::Debug for StringUtf16 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "N{:?}", String::from_utf16(&self.0).expect("StringUtf16 is not valid UTF-16 encoded string"))
    }
}

impl From<String> for StringUtf16 {
    fn from(s: String) -> StringUtf16 {
        s.as_str().into()
    }
}

impl From<&str> for StringUtf16 {
    fn from(s: &str) -> StringUtf16 {
        StringUtf16(s.encode_utf16().collect())
    }
}

unsafe impl<'a> OdbcType<'a> for StringUtf16 {
    fn sql_data_type() -> ffi::SqlDataType {
        <&[u16]>::sql_data_type()
    }
    fn c_data_type() -> ffi::SqlCDataType {
        <&[u16]>::c_data_type()
    }

    fn convert(buffer: &[u8]) -> Self {
        StringUtf16(<&[u16]>::convert(buffer).to_owned())
    }

    fn column_size(&self) -> ffi::SQLULEN {
        <&[u16]>::column_size(&self.0.as_slice())
    }

    fn value_ptr(&self) -> ffi::SQLPOINTER {
        self.0.as_ptr() as *const &[u16] as ffi::SQLPOINTER
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::de::Deserialize<'de> for StringUtf16 {
    fn deserialize<D>(deserializer: D) -> std::result::Result<StringUtf16, D::Error>
    where
        D: serde::de::Deserializer<'de>,
    {
        String::deserialize(deserializer)
            .map(From::from)
    }
}