odbc_api/handles/
connection.rs

1use super::{
2    OutputStringBuffer, SqlResult,
3    any_handle::AnyHandle,
4    buffer::mut_buf_ptr,
5    drop_handle,
6    sql_char::{
7        SqlChar, SqlText, binary_length, is_truncated_bin, resize_to_fit_with_tz,
8        resize_to_fit_without_tz,
9    },
10    sql_result::ExtSqlReturn,
11    statement::StatementImpl,
12};
13use log::debug;
14use odbc_sys::{
15    CompletionType, ConnectionAttribute, DriverConnectOption, HDbc, HEnv, HWnd, Handle, HandleType,
16    IS_UINTEGER, InfoType, Pointer, SQLAllocHandle, SQLDisconnect, SQLEndTran,
17};
18use std::{ffi::c_void, marker::PhantomData, mem::size_of, ptr::null_mut};
19
20#[cfg(not(any(feature = "wide", all(not(feature = "narrow"), target_os = "windows"))))]
21use odbc_sys::{
22    SQLConnect as sql_connect, SQLDriverConnect as sql_driver_connect,
23    SQLGetConnectAttr as sql_get_connect_attr, SQLGetInfo as sql_get_info,
24    SQLSetConnectAttr as sql_set_connect_attr,
25};
26
27#[cfg(any(feature = "wide", all(not(feature = "narrow"), target_os = "windows")))]
28use odbc_sys::{
29    SQLConnectW as sql_connect, SQLDriverConnectW as sql_driver_connect,
30    SQLGetConnectAttrW as sql_get_connect_attr, SQLGetInfoW as sql_get_info,
31    SQLSetConnectAttrW as sql_set_connect_attr,
32};
33
34/// The connection handle references storage of all information about the connection to the data
35/// source, including status, transaction state, and error information.
36///
37/// Connection is not `Sync`, this implies that many methods which one would suspect should take
38/// `&mut self` are actually `&self`. This is important if several statement exists which borrow
39/// the same connection.
40pub struct Connection<'c> {
41    parent: PhantomData<&'c HEnv>,
42    handle: HDbc,
43}
44
45unsafe impl AnyHandle for Connection<'_> {
46    fn as_handle(&self) -> Handle {
47        self.handle.as_handle()
48    }
49
50    fn handle_type(&self) -> HandleType {
51        HandleType::Dbc
52    }
53}
54
55impl Drop for Connection<'_> {
56    fn drop(&mut self) {
57        unsafe {
58            drop_handle(self.handle.as_handle(), HandleType::Dbc);
59        }
60    }
61}
62
63/// According to the ODBC documentation this is safe. See:
64/// <https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/multithreading>
65///
66/// Operations to a connection imply that interior state of the connection might be mutated, yet we
67/// use a `&self` reference for most methods rather than `&mut self`. This means [`Connection`] must
68/// not be `Sync`. `Send` however is fine, due to the guarantees given by the ODBC interface.
69/// However, there might be a difference, between what ODBC demands from drivers and how they are
70/// actually implemented. However, even in practice the situation seems to have improved enuough to
71/// allow for [`Connection`]s to be regarded as `Send` without alerting the author of the ODBC
72/// application. If the driver has a bug, it is just that.
73///
74/// In addition to that, this has not caused trouble in a while. So we mark sending connections to
75/// other threads as safe. Reading through the documentation, one might get the impression that
76/// Connections are also `Sync`. This could be theoretically true on the level of the handle, but at
77/// the latest once the interior mutability due to error handling comes in to play, higher level
78/// abstraction have to content themselves with `Send`. This is currently how far my trust with most
79/// ODBC drivers.
80///
81/// Note to users of `unixodbc`: You may configure the threading level to make unixodbc
82/// synchronize access to the driver (and thereby making them thread safe if they are not thread
83/// safe by themself. This may however hurt your performance if the driver would actually be able to
84/// perform operations in parallel.
85///
86/// See:
87/// <https://stackoverflow.com/questions/4207458/using-unixodbc-in-a-multithreaded-concurrent-setting>
88unsafe impl Send for Connection<'_> {}
89
90impl Connection<'_> {
91    /// # Safety
92    ///
93    /// Call this method only with a valid (successfully allocated) ODBC connection handle.
94    pub unsafe fn new(handle: HDbc) -> Self {
95        Self {
96            handle,
97            parent: PhantomData,
98        }
99    }
100
101    /// Directly acces the underlying ODBC handle.
102    pub fn as_sys(&self) -> HDbc {
103        self.handle
104    }
105
106    /// Establishes connections to a driver and a data source.
107    ///
108    /// * See [Connecting with SQLConnect][1]
109    /// * See [SQLConnectFunction][2]
110    ///
111    /// # Arguments
112    ///
113    /// * `data_source_name` - Data source name. The data might be located on the same computer as
114    ///   the program, or on another computer somewhere on a network.
115    /// * `user` - User identifier.
116    /// * `pwd` - Authentication string (typically the password).
117    ///
118    /// [1]: https://docs.microsoft.com//sql/odbc/reference/develop-app/connecting-with-sqlconnect
119    /// [2]: https://docs.microsoft.com/sql/odbc/reference/syntax/sqlconnect-function
120    pub fn connect(
121        &mut self,
122        data_source_name: &SqlText,
123        user: &SqlText,
124        pwd: &SqlText,
125    ) -> SqlResult<()> {
126        unsafe {
127            sql_connect(
128                self.handle,
129                data_source_name.ptr(),
130                data_source_name.len_char().try_into().unwrap(),
131                user.ptr(),
132                user.len_char().try_into().unwrap(),
133                pwd.ptr(),
134                pwd.len_char().try_into().unwrap(),
135            )
136            .into_sql_result("SQLConnect")
137        }
138    }
139
140    /// An alternative to `connect`. It supports data sources that require more connection
141    /// information than the three arguments in `connect` and data sources that are not defined in
142    /// the system information.
143    pub fn connect_with_connection_string(&mut self, connection_string: &SqlText) -> SqlResult<()> {
144        unsafe {
145            let parent_window = null_mut();
146            let mut completed_connection_string = OutputStringBuffer::empty();
147
148            self.driver_connect(
149                connection_string,
150                parent_window,
151                &mut completed_connection_string,
152                DriverConnectOption::NoPrompt,
153            )
154            // Since we did pass NoPrompt we know the user can not abort the prompt.
155            .map(|_connection_string_is_complete| ())
156        }
157    }
158
159    /// An alternative to `connect` for connecting with a connection string. Allows for completing
160    /// a connection string with a GUI prompt on windows.
161    ///
162    /// # Return
163    ///
164    /// [`SqlResult::NoData`] in case the prompt completing the connection string has been aborted.
165    ///
166    /// # Safety
167    ///
168    /// `parent_window` must either be a valid window handle or `NULL`.
169    pub unsafe fn driver_connect(
170        &mut self,
171        connection_string: &SqlText,
172        parent_window: HWnd,
173        completed_connection_string: &mut OutputStringBuffer,
174        driver_completion: DriverConnectOption,
175    ) -> SqlResult<()> {
176        unsafe {
177            sql_driver_connect(
178                self.handle,
179                parent_window,
180                connection_string.ptr(),
181                connection_string.len_char().try_into().unwrap(),
182                completed_connection_string.mut_buf_ptr(),
183                completed_connection_string.buf_len(),
184                completed_connection_string.mut_actual_len_ptr(),
185                driver_completion,
186            )
187            .into_sql_result("SQLDriverConnect")
188        }
189    }
190
191    /// Disconnect from an ODBC data source.
192    pub fn disconnect(&mut self) -> SqlResult<()> {
193        unsafe { SQLDisconnect(self.handle).into_sql_result("SQLDisconnect") }
194    }
195
196    /// Allocate a new statement handle. The `Statement` must not outlive the `Connection`.
197    pub fn allocate_statement(&self) -> SqlResult<StatementImpl<'_>> {
198        let mut out = Handle::null();
199        unsafe {
200            SQLAllocHandle(HandleType::Stmt, self.as_handle(), &mut out)
201                .into_sql_result("SQLAllocHandle")
202                .on_success(|| StatementImpl::new(out.as_hstmt()))
203        }
204    }
205
206    /// Specify the transaction mode. By default, ODBC transactions are in auto-commit mode (unless
207    /// SQLSetConnectAttr and SQLSetConnectOption are not supported, which is unlikely). Switching
208    /// from manual-commit mode to auto-commit mode automatically commits any open transaction on
209    /// the connection.
210    pub fn set_autocommit(&self, enabled: bool) -> SqlResult<()> {
211        let val = enabled as u32;
212        unsafe {
213            sql_set_connect_attr(
214                self.handle,
215                ConnectionAttribute::AutoCommit,
216                val as Pointer,
217                0, // will be ignored according to ODBC spec
218            )
219            .into_sql_result("SQLSetConnectAttr")
220        }
221    }
222
223    /// Number of seconds to wait for a login request to complete before returning to the
224    /// application. The default is driver-dependent. If `0` the timeout is dasabled and a
225    /// connection attempt will wait indefinitely.
226    ///
227    /// If the specified timeout exceeds the maximum login timeout in the data source, the driver
228    /// substitutes that value and uses the maximum login timeout instead.
229    ///
230    /// This corresponds to the `SQL_ATTR_LOGIN_TIMEOUT` attribute in the ODBC specification.
231    ///
232    /// See:
233    /// <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetconnectattr-function>
234    pub fn set_login_timeout_sec(&self, timeout: u32) -> SqlResult<()> {
235        unsafe {
236            sql_set_connect_attr(
237                self.handle,
238                ConnectionAttribute::LoginTimeout,
239                timeout as Pointer,
240                0,
241            )
242            .into_sql_result("SQLSetConnectAttr")
243        }
244    }
245
246    /// Specifying the network packet size in bytes. Note: Many data sources either do not support
247    /// this option or only can return but not set the network packet size. If the specified size
248    /// exceeds the maximum packet size or is smaller than the minimum packet size, the driver
249    /// substitutes that value and returns SQLSTATE 01S02 (Option value changed). If the application
250    /// sets packet size after a connection has already been made, the driver will return SQLSTATE
251    /// HY011 (Attribute cannot be set now).
252    ///
253    /// See:
254    /// <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetconnectattr-function>
255    pub fn set_packet_size(&self, packet_size: u32) -> SqlResult<()> {
256        unsafe {
257            sql_set_connect_attr(
258                self.handle,
259                ConnectionAttribute::PacketSize,
260                packet_size as Pointer,
261                0,
262            )
263            .into_sql_result("SQLSetConnectAttr")
264        }
265    }
266
267    /// To commit a transaction in manual-commit mode.
268    pub fn commit(&self) -> SqlResult<()> {
269        unsafe {
270            SQLEndTran(HandleType::Dbc, self.as_handle(), CompletionType::Commit)
271                .into_sql_result("SQLEndTran")
272        }
273    }
274
275    /// Roll back a transaction in manual-commit mode.
276    pub fn rollback(&self) -> SqlResult<()> {
277        unsafe {
278            SQLEndTran(HandleType::Dbc, self.as_handle(), CompletionType::Rollback)
279                .into_sql_result("SQLEndTran")
280        }
281    }
282
283    /// Fetch the name of the database management system used by the connection and store it into
284    /// the provided `buf`.
285    pub fn fetch_database_management_system_name(&self, buf: &mut Vec<SqlChar>) -> SqlResult<()> {
286        // String length in bytes, not characters. Terminating zero is excluded.
287        let mut string_length_in_bytes: i16 = 0;
288        // Let's utilize all of `buf`s capacity.
289        buf.resize(buf.capacity(), 0);
290
291        unsafe {
292            let mut res = sql_get_info(
293                self.handle,
294                InfoType::DbmsName,
295                mut_buf_ptr(buf) as Pointer,
296                binary_length(buf).try_into().unwrap(),
297                &mut string_length_in_bytes as *mut i16,
298            )
299            .into_sql_result("SQLGetInfo");
300
301            if res.is_err() {
302                return res;
303            }
304
305            // Call has been a success but let's check if the buffer had been large enough.
306            if is_truncated_bin(buf, string_length_in_bytes.try_into().unwrap()) {
307                // It seems we must try again with a large enough buffer.
308                resize_to_fit_with_tz(buf, string_length_in_bytes.try_into().unwrap());
309                res = sql_get_info(
310                    self.handle,
311                    InfoType::DbmsName,
312                    mut_buf_ptr(buf) as Pointer,
313                    binary_length(buf).try_into().unwrap(),
314                    &mut string_length_in_bytes as *mut i16,
315                )
316                .into_sql_result("SQLGetInfo");
317
318                if res.is_err() {
319                    return res;
320                }
321            }
322
323            // Resize buffer to exact string length without terminal zero
324            resize_to_fit_without_tz(buf, string_length_in_bytes.try_into().unwrap());
325            res
326        }
327    }
328
329    fn info_u16(&self, info_type: InfoType) -> SqlResult<u16> {
330        unsafe {
331            let mut value = 0u16;
332            sql_get_info(
333                self.handle,
334                info_type,
335                &mut value as *mut u16 as Pointer,
336                // Buffer length should not be required in this case, according to the ODBC
337                // documentation at https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlgetinfo-function?view=sql-server-ver15#arguments
338                // However, in practice some drivers (such as Microsoft Access) require it to be
339                // specified explicitly here, otherwise they return an error without diagnostics.
340                size_of::<*mut u16>() as i16,
341                null_mut(),
342            )
343            .into_sql_result("SQLGetInfo")
344            .on_success(|| value)
345        }
346    }
347
348    /// Maximum length of catalog names.
349    pub fn max_catalog_name_len(&self) -> SqlResult<u16> {
350        self.info_u16(InfoType::MaxCatalogNameLen)
351    }
352
353    /// Maximum length of schema names.
354    pub fn max_schema_name_len(&self) -> SqlResult<u16> {
355        self.info_u16(InfoType::MaxSchemaNameLen)
356    }
357
358    /// Maximum length of table names.
359    pub fn max_table_name_len(&self) -> SqlResult<u16> {
360        self.info_u16(InfoType::MaxTableNameLen)
361    }
362
363    /// Maximum length of column names.
364    pub fn max_column_name_len(&self) -> SqlResult<u16> {
365        self.info_u16(InfoType::MaxColumnNameLen)
366    }
367
368    /// Fetch the name of the current catalog being used by the connection and store it into the
369    /// provided `buf`.
370    pub fn fetch_current_catalog(&self, buffer: &mut Vec<SqlChar>) -> SqlResult<()> {
371        // String length in bytes, not characters. Terminating zero is excluded.
372        let mut string_length_in_bytes: i32 = 0;
373        // Let's utilize all of `buf`s capacity.
374        buffer.resize(buffer.capacity(), 0);
375
376        unsafe {
377            let mut res = sql_get_connect_attr(
378                self.handle,
379                ConnectionAttribute::CurrentCatalog,
380                mut_buf_ptr(buffer) as Pointer,
381                binary_length(buffer).try_into().unwrap(),
382                &mut string_length_in_bytes as *mut i32,
383            )
384            .into_sql_result("SQLGetConnectAttr");
385
386            if res.is_err() {
387                return res;
388            }
389
390            if is_truncated_bin(buffer, string_length_in_bytes.try_into().unwrap()) {
391                resize_to_fit_with_tz(buffer, string_length_in_bytes.try_into().unwrap());
392                res = sql_get_connect_attr(
393                    self.handle,
394                    ConnectionAttribute::CurrentCatalog,
395                    mut_buf_ptr(buffer) as Pointer,
396                    binary_length(buffer).try_into().unwrap(),
397                    &mut string_length_in_bytes as *mut i32,
398                )
399                .into_sql_result("SQLGetConnectAttr");
400            }
401
402            if res.is_err() {
403                return res;
404            }
405
406            // Resize buffer to exact string length without terminal zero
407            resize_to_fit_without_tz(buffer, string_length_in_bytes.try_into().unwrap());
408            res
409        }
410    }
411
412    /// Indicates the state of the connection. If `true` the connection has been lost. If `false`,
413    /// the connection is still active.
414    pub fn is_dead(&self) -> SqlResult<bool> {
415        unsafe {
416            self.attribute_u32(ConnectionAttribute::ConnectionDead)
417                .map(|v| match v {
418                    0 => false,
419                    1 => true,
420                    other => panic!("Unexpected result value from SQLGetConnectAttr: {other}"),
421                })
422        }
423    }
424
425    /// Networ packet size in bytes.
426    pub fn packet_size(&self) -> SqlResult<u32> {
427        unsafe { self.attribute_u32(ConnectionAttribute::PacketSize) }
428    }
429
430    /// # Safety
431    ///
432    /// Caller must ensure connection attribute is numeric.
433    unsafe fn attribute_u32(&self, attribute: ConnectionAttribute) -> SqlResult<u32> {
434        let mut out: u32 = 0;
435        unsafe {
436            sql_get_connect_attr(
437                self.handle,
438                attribute,
439                &mut out as *mut u32 as *mut c_void,
440                IS_UINTEGER,
441                null_mut(),
442            )
443        }
444        .into_sql_result("SQLGetConnectAttr")
445        .on_success(|| {
446            let handle = self.handle;
447            debug!(
448                "SQLGetConnectAttr called with attribute '{attribute:?}' for connection \
449                '{handle:?}' reported '{out}'."
450            );
451            out
452        })
453    }
454}