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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use crate::attr::*;
use crate::error::SqlResult;
use crate::handle::{SqlHandle, SqlRawHandle};
use crate::tran::SqlEndTransaction;
use crate::util;
use crate::util::VecCapacityExt;
use odbc_sys::*;
use std::fmt;

#[derive(Debug, Eq, PartialEq, Hash)]
pub struct SqlEnvironment {
    handle: SQLHENV,
}

impl SqlAttribute for EnvironmentAttribute {
    fn buffer_length(&self) -> Option<SqlAttributeStringLength> {
        let value = match self {
            SQL_ATTR_CONNECTION_POOLING | SQL_ATTR_CP_MATCH => SQL_IS_UINTEGER,
            _ => SQL_IS_INTEGER,
        };
        Some(value)
    }
}

unsafe impl SqlAttributes for SqlEnvironment {
    type AttributeType = EnvironmentAttribute;

    const GETTER_NAME: &'static str = "SQLGetEnvAttr";
    const GETTER: unsafe extern "system" fn(
        SQLHENV,
        EnvironmentAttribute,
        SQLPOINTER,
        SQLINTEGER,
        *mut SQLINTEGER,
    ) -> SQLRETURN = SQLGetEnvAttr;
    const SETTER: unsafe extern "system" fn(
        SQLHENV,
        EnvironmentAttribute,
        SQLPOINTER,
        SQLINTEGER,
    ) -> SQLRETURN = SQLSetEnvAttr;
    const SETTER_NAME: &'static str = "SQLSetEnvAttr";
}

impl SqlEndTransaction for SqlEnvironment {}

impl SqlHandle for SqlEnvironment {
    const TYPE: HandleType = SQL_HANDLE_ENV;
    type Type = SQLHENV;

    unsafe fn typed_handle(&self) -> SQLHENV {
        self.handle
    }

    unsafe fn handle(&self) -> SQLHANDLE {
        self.handle as SQLHANDLE
    }
}

unsafe impl SqlRawHandle for SqlEnvironment {}

impl Drop for SqlEnvironment {
    fn drop(&mut self) {
        unsafe { self.dealloc_handle().unwrap() }
    }
}

unsafe impl Send for SqlEnvironment {}

unsafe impl Sync for SqlEnvironment {}

use std::collections::HashMap;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct SqlDriver {
    pub description: String,
    pub attributes: HashMap<String, String>,
}

#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct SqlDataSource {
    pub server_name: String,
    pub description: String,
}

#[repr(u32)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum SqlConnectionPooling {
    Off,
    OnePerDriver,
    OnePerEnvironment,
    DriverAware,
}

#[repr(u32)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum SqlConnectionPoolingMatch {
    Strict,
    Relaxed,
}

#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum SqlDataSourceFilter {
    Both,
    User,
    System,
}

impl Default for SqlDataSourceFilter {
    fn default() -> SqlDataSourceFilter {
        SqlDataSourceFilter::Both
    }
}

impl fmt::Display for SqlDriver {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} (\"{:?}\")", self.description, self.attributes)
    }
}

impl fmt::Display for SqlDataSource {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} \"{}\"", self.server_name, self.description)
    }
}

impl SqlEnvironment {
    pub fn new() -> SqlResult<SqlEnvironment> {
        let handle = unsafe { Self::alloc_handle()? as SQLHENV };
        Ok(SqlEnvironment { handle })
    }

    pub fn set_version(&mut self, version: OdbcVersion) -> SqlResult {
        unsafe { self.set_attribute(SQL_ATTR_ODBC_VERSION, version as usize) }
    }

    pub fn get_version(&mut self) -> SqlResult<OdbcVersion> {
        unsafe {
            self.get_attribute::<SQLINTEGER>(SQL_ATTR_ODBC_VERSION)
                .map(|value| std::mem::transmute(value))
        }
    }

    pub fn set_connection_pooling(&mut self, setting: SqlConnectionPooling) -> SqlResult {
        unsafe { self.set_attribute(SQL_ATTR_CONNECTION_POOLING, setting as usize) }
    }

    pub fn get_connection_pooling(&mut self) -> SqlResult<SqlConnectionPooling> {
        unsafe {
            self.get_attribute::<SQLUINTEGER>(SQL_ATTR_CONNECTION_POOLING)
                .map(|value| std::mem::transmute(value))
        }
    }

    pub fn set_connection_pooling_match(
        &mut self,
        setting: SqlConnectionPoolingMatch,
    ) -> SqlResult {
        unsafe { self.set_attribute(SQL_ATTR_CP_MATCH, setting as usize) }
    }

    pub fn get_connection_pooling_match(&mut self) -> SqlResult<SqlConnectionPoolingMatch> {
        unsafe {
            self.get_attribute::<SQLUINTEGER>(SQL_ATTR_CP_MATCH)
                .map(|value| std::mem::transmute(value))
        }
    }

    pub fn drivers(&self) -> SqlResult<Vec<SqlDriver>> {
        let mut drivers: Vec<SqlDriver> = vec![];
        let mut description: Vec<u16> = Vec::with_capacity(SQL_MAX_MESSAGE_LENGTH as usize);
        let mut description_len: SQLSMALLINT = 0;
        let mut attributes: Vec<u16> = Vec::with_capacity(SQL_MAX_MESSAGE_LENGTH as usize);
        let mut attributes_len: SQLSMALLINT = 0;

        let mut direction = SQL_FETCH_FIRST;

        loop {
            let ret = unsafe {
                SQLDriversW(
                    self.handle,
                    direction,
                    description.as_mut_ptr(),
                    description.capacity() as SQLSMALLINT,
                    &mut description_len,
                    attributes.as_mut_ptr(),
                    attributes.capacity() as SQLSMALLINT,
                    &mut attributes_len,
                )
            };

            match ret {
                SQL_ERROR => return Err(self.get_detailed_error(ret)),
                SQL_NO_DATA => break,
                SQL_SUCCESS | SQL_SUCCESS_WITH_INFO => {
                    assert!(description_len >= 0);
                    let description_len = description_len as usize;

                    assert!(attributes_len >= 0);
                    let attributes_len = attributes_len as usize;

                    if util::is_string_data_right_truncated(self, ret)? {
                        description.reserve_capacity(description_len + 1);
                        attributes.reserve_capacity(attributes_len + 1);
                        direction = SQL_FETCH_FIRST;
                        drivers.clear();
                    } else {
                        unsafe {
                            description.set_len_checked(description_len);
                            attributes.set_len_checked(attributes_len);
                        }

                        let description_text = util::from_utf_16_null_terminated(&description)?;
                        let attributes_text = util::from_utf_16_null_terminated(&attributes)?;
                        let attributes: HashMap<String, String> = attributes_text
                            .split('\0')
                            .filter_map(|pair: &str| {
                                if let Some(pos) = pair.bytes().position(|c| c == b'=') {
                                    let (key, value) = pair.split_at(pos);
                                    Some((key.to_owned(), value[1..].to_owned()))
                                } else {
                                    None
                                }
                            })
                            .collect();

                        let driver = SqlDriver {
                            description: description_text,
                            attributes,
                        };
                        drivers.push(driver);
                        direction = SQL_FETCH_NEXT;
                    }
                }
                _ => panic!("Unexpected SQLDriversW return code: {:?}", ret),
            }
        }
        Ok(drivers)
    }

    pub fn data_sources(&self, filter: SqlDataSourceFilter) -> SqlResult<Vec<SqlDataSource>> {
        use self::SqlDataSourceFilter::*;

        let mut data_sources: Vec<SqlDataSource> = vec![];
        let initial_direction = match filter {
            Both => SQL_FETCH_FIRST,
            User => SQL_FETCH_FIRST_USER,
            System => SQL_FETCH_FIRST_SYSTEM,
        };

        let mut server_name: Vec<u16> = Vec::with_capacity(SQL_MAX_MESSAGE_LENGTH as usize);
        let mut server_name_len: SQLSMALLINT = 0;
        let mut description: Vec<u16> = Vec::with_capacity(SQL_MAX_MESSAGE_LENGTH as usize);
        let mut description_len: SQLSMALLINT = 0;

        let mut direction = initial_direction;

        loop {
            let ret = unsafe {
                SQLDataSourcesW(
                    self.handle,
                    direction,
                    server_name.as_mut_ptr(),
                    server_name.capacity() as SQLSMALLINT,
                    &mut server_name_len,
                    description.as_mut_ptr(),
                    description.capacity() as SQLSMALLINT,
                    &mut description_len,
                )
            };

            match ret {
                SQL_ERROR => return Err(self.get_detailed_error(ret)),
                SQL_NO_DATA => break,
                SQL_SUCCESS | SQL_SUCCESS_WITH_INFO => {
                    assert!(server_name_len >= 0);
                    let server_name_len = server_name_len as usize;

                    assert!(description_len >= 0);
                    let description_len = description_len as usize;

                    if util::is_string_data_right_truncated(self, ret)? {
                        server_name.reserve_capacity(server_name_len + 1);
                        description.reserve_capacity(description_len + 1);
                        data_sources.clear();
                        direction = initial_direction;
                    } else {
                        unsafe {
                            server_name.set_len_checked(server_name_len);
                            description.set_len_checked(description_len);
                        }

                        let server_name_text = util::from_utf_16_null_terminated(&server_name)?;
                        let description_text = util::from_utf_16_null_terminated(&description)?;

                        let data_source = SqlDataSource {
                            server_name: server_name_text,
                            description: description_text,
                        };
                        data_sources.push(data_source);
                        direction = SQL_FETCH_NEXT;
                    }
                }
                _ => panic!("Unexpected SQLDataSourcesW return code: {:?}", ret),
            }
        }

        Ok(data_sources)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::print_diagnostics;

    #[test]
    fn new_environment() {
        SqlEnvironment::new().unwrap();
    }

    #[test]
    fn get_set_version() {
        let mut env = SqlEnvironment::new().unwrap();
        print_diagnostics(&env);
        env.set_version(OdbcVersion::SQL_OV_ODBC3_80).unwrap();
        print_diagnostics(&env);

        let ver = env.get_version().unwrap();
        print_diagnostics(&env);
        assert_eq!(OdbcVersion::SQL_OV_ODBC3_80, ver);
    }

    #[cfg(windows)]
    #[test]
    fn get_set_connection_pooling() {
        let mut env = SqlEnvironment::new().unwrap();
        print_diagnostics(&env);
        env.set_version(OdbcVersion::SQL_OV_ODBC3_80).unwrap();
        print_diagnostics(&env);

        env.set_connection_pooling(SqlConnectionPooling::DriverAware)
            .unwrap();

        let cp = env.get_connection_pooling().unwrap();
        print_diagnostics(&env);
        assert_eq!(SqlConnectionPooling::DriverAware, cp);
    }

    #[cfg(windows)]
    #[test]
    fn get_set_connection_pooling_match() {
        let mut env = SqlEnvironment::new().unwrap();
        print_diagnostics(&env);
        env.set_version(OdbcVersion::SQL_OV_ODBC3_80).unwrap();
        print_diagnostics(&env);

        env.set_connection_pooling_match(SqlConnectionPoolingMatch::Relaxed)
            .unwrap();
        let m = env.get_connection_pooling_match().unwrap();
        print_diagnostics(&env);
        assert_eq!(SqlConnectionPoolingMatch::Relaxed, m);
    }

    #[test]
    fn drivers() {
        let mut env = SqlEnvironment::new().unwrap();
        print_diagnostics(&env);

        env.set_version(OdbcVersion::SQL_OV_ODBC3_80).unwrap();
        print_diagnostics(&env);

        let drivers = env.drivers().unwrap();
        print_diagnostics(&env);

        for driver in drivers.iter() {
            println!("{}", driver);
        }
    }

    #[test]
    fn data_sources() {
        let mut env = SqlEnvironment::new().unwrap();
        print_diagnostics(&env);

        env.set_version(OdbcVersion::SQL_OV_ODBC3_80).unwrap();
        print_diagnostics(&env);

        let data_sources = env.data_sources(SqlDataSourceFilter::Both).unwrap();
        print_diagnostics(&env);

        for dsn in data_sources.iter() {
            println!("{}", dsn);
        }
    }
}