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
224
225
226
227
228
229
230
use async::*;
use error::*;
use futures::*;
use handle::SqlHandle;
use odbc_sys::*;
use util::VecCapacityExt;
use {std, util};

pub(crate) trait SqlAttribute: Copy + Send + 'static {
    fn buffer_length(&self) -> Option<SqlAttributeStringLength>;
}

pub(crate) unsafe trait SqlAttributes: SqlHandle {
    type AttributeType: SqlAttribute;
    const GETTER_NAME: &'static str;
    const GETTER: unsafe extern "system" fn(
        Self::Type,
        Self::AttributeType,
        SQLPOINTER,
        SQLINTEGER,
        *mut SQLINTEGER,
    ) -> SQLRETURN;
    const SETTER: unsafe extern "system" fn(
        Self::Type,
        Self::AttributeType,
        SQLPOINTER,
        SQLINTEGER,
    ) -> SQLRETURN;
    const SETTER_NAME: &'static str;

    unsafe fn get_attribute<T>(&self, attribute: Self::AttributeType) -> SqlResult<T>
    where
        T: Copy + Send + 'static,
    {
        get_attribute_impl(self, attribute).unwrap_async()
    }

    unsafe fn get_attribute_async<T>(
        self,
        attribute: Self::AttributeType,
    ) -> SqlValueFuture<Self, T>
    where
        T: Copy + Send + 'static,
    {
        SqlValueFuture::new(self, move |handle| get_attribute_impl(handle, attribute))
    }

    unsafe fn get_attribute_string(&self, attribute: Self::AttributeType) -> SqlResult<String> {
        let mut buffer: Vec<u16> = Vec::with_capacity(SQL_MAX_MESSAGE_LENGTH as usize);
        let mut len: SQLINTEGER = 0;

        get_attribute_string_impl(self, attribute, &mut buffer, &mut len).unwrap_async()
    }

    unsafe fn get_attribute_string_async(
        self,
        attribute: Self::AttributeType,
    ) -> SqlValueFuture<Self, String> {
        let mut buffer: Vec<u16> = Vec::with_capacity(SQL_MAX_MESSAGE_LENGTH as usize);
        let mut len: SQLINTEGER = 0;

        SqlValueFuture::new(self, move |handle| {
            get_attribute_string_impl(handle, attribute, &mut buffer, &mut len)
        })
    }

    unsafe fn set_attribute(&mut self, attribute: Self::AttributeType, value: usize) -> SqlResult {
        set_attribute_impl(self, attribute, value).unwrap_async()
    }

    unsafe fn set_attribute_async(
        self,
        attribute: Self::AttributeType,
        value: usize,
    ) -> SqlFuture<Self> {
        let f = SqlValueFuture::new(self, move |handle| {
            set_attribute_impl(handle, attribute, value)
        });

        flatten_value_future(f)
    }

    unsafe fn set_attribute_string(
        &mut self,
        attribute: Self::AttributeType,
        value: &str,
    ) -> SqlResult {
        let buffer: Vec<u16> = value.encode_utf16().collect();

        set_attribute_string_impl(self, attribute, &buffer).unwrap_async()
    }

    unsafe fn set_attribute_string_async(
        self,
        attribute: Self::AttributeType,
        value: &str,
    ) -> SqlFuture<Self> {
        let buffer: Vec<u16> = value.encode_utf16().collect();

        let f = SqlValueFuture::new(self, move |handle| {
            set_attribute_string_impl(handle, attribute, &buffer)
        });

        flatten_value_future(f)
    }
}

unsafe fn get_attribute_impl<T, H>(handle: &H, attribute: H::AttributeType) -> SqlPoll<T>
where
    H: SqlAttributes,
    T: Copy + Send + 'static,
{
    let mut value: T = std::mem::uninitialized();
    let value_ptr: *mut T = &mut value;
    let buffer_length = attribute
        .buffer_length()
        .expect("buffer_length() should be not empty for non-string values");

    let ret = H::GETTER(
        handle.typed_handle(),
        attribute,
        value_ptr as SQLPOINTER,
        buffer_length as i32,
        std::ptr::null_mut(),
    );
    match ret {
        SQL_SUCCESS | SQL_SUCCESS_WITH_INFO => Ok(Async::Ready(value)),
        SQL_STILL_EXECUTING => Ok(Async::NotReady),
        SQL_ERROR => {
            let e = handle.get_detailed_error(ret);
            Err(e)
        }
        _ => panic!("Unexpected {} return code: {:?}", H::GETTER_NAME, ret),
    }
}

unsafe fn get_attribute_string_impl<H: SqlAttributes>(
    handle: &H,
    attribute: H::AttributeType,
    buffer: &mut Vec<u16>,
    len: &mut SQLINTEGER,
) -> SqlPoll<String> {
    assert!(
        attribute.buffer_length().is_none(),
        "buffer_length() should be empty for string values"
    );
    loop {
        let ret = H::GETTER(
            handle.typed_handle(),
            attribute,
            buffer.as_mut_ptr() as SQLPOINTER,
            buffer.capacity_bytes() as SQLINTEGER,
            len,
        );

        match ret {
            SQL_SUCCESS | SQL_SUCCESS_WITH_INFO => {
                assert!(*len >= 0);
                let mut len = *len as usize;
                let size = std::mem::size_of::<u16>();
                assert_eq!(0, len % size);
                len /= size;

                if util::is_string_data_right_truncated(handle, ret)? {
                    buffer.reserve_capacity(len + 1)
                } else {
                    buffer.set_len_checked(len);
                    return util::from_utf_16_null_terminated(&buffer)
                        .map(Async::Ready)
                        .map_err(SqlError::from);
                }
            }
            SQL_STILL_EXECUTING => return Ok(Async::NotReady),
            SQL_ERROR => return Err(handle.get_detailed_error(ret)),
            _ => panic!("Unexpected {} return code: {:?}", H::GETTER_NAME, ret),
        }
    }
}

unsafe fn set_attribute_impl<H: SqlAttributes>(
    handle: &mut H,
    attribute: H::AttributeType,
    value: usize,
) -> SqlPoll {
    let buffer_length = attribute
        .buffer_length()
        .expect("buffer_length() should be not empty for non-string values");
    let ret = H::SETTER(
        handle.typed_handle(),
        attribute,
        value as SQLPOINTER,
        buffer_length as i32,
    );
    match ret {
        SQL_SUCCESS | SQL_SUCCESS_WITH_INFO => Ok(Async::Ready(())),
        SQL_STILL_EXECUTING => Ok(Async::NotReady),
        SQL_ERROR => {
            let e = handle.get_detailed_error(ret);
            Err(e)
        }
        _ => panic!("Unexpected {} return code: {:?}", H::SETTER_NAME, ret),
    }
}

unsafe fn set_attribute_string_impl<H: SqlAttributes>(
    handle: &mut H,
    attribute: H::AttributeType,
    buffer: &[u16],
) -> SqlPoll {
    assert!(
        attribute.buffer_length().is_none(),
        "buffer_length() should be empty for string values"
    );
    let ret = H::SETTER(
        handle.typed_handle(),
        attribute,
        buffer.as_ptr() as SQLPOINTER,
        std::mem::size_of_val(buffer) as SQLINTEGER,
    );

    match ret {
        SQL_SUCCESS | SQL_SUCCESS_WITH_INFO => Ok(Async::Ready(())),
        SQL_STILL_EXECUTING => Ok(Async::NotReady),
        SQL_ERROR => {
            let e = handle.get_detailed_error(ret);
            Err(e)
        }
        _ => panic!("Unexpected {} return code: {:?}", H::SETTER_NAME, ret),
    }
}