odbc_api/connection.rs
1use crate::{
2 CursorImpl, CursorPolling, Error, ParameterCollectionRef, Preallocated, Prepared, Sleep,
3 buffers::BufferDesc,
4 execute::{
5 execute_columns, execute_foreign_keys, execute_tables, execute_with_parameters_polling,
6 },
7 handles::{
8 self, SqlText, State, Statement, StatementConnection, StatementImpl, StatementParent,
9 slice_to_utf8,
10 },
11};
12use log::error;
13use std::{
14 borrow::Cow,
15 fmt::{self, Debug, Display},
16 mem::{ManuallyDrop, MaybeUninit},
17 ptr, str,
18 sync::Arc,
19 thread::panicking,
20};
21
22impl Drop for Connection<'_> {
23 fn drop(&mut self) {
24 match self.connection.disconnect().into_result(&self.connection) {
25 Ok(()) => (),
26 Err(Error::Diagnostics {
27 record,
28 function: _,
29 }) if record.state == State::INVALID_STATE_TRANSACTION => {
30 // Invalid transaction state. Let's rollback the current transaction and try again.
31 if let Err(e) = self.rollback() {
32 // Connection might be in a suspended state. See documentation about suspended
33 // state here:
34 // <https://learn.microsoft.com/sql/odbc/reference/syntax/sqlendtran-function>
35 //
36 // See also issue:
37 // <https://github.com/pacman82/odbc-api/issues/574#issuecomment-2286449125>
38
39 error!(
40 "Error during rolling back transaction (In order to recover from \
41 invalid transaction state during disconnect {}",
42 e
43 );
44 }
45 // Transaction might be rolled back or suspended. Now let's try again to disconnect.
46 if let Err(e) = self.connection.disconnect().into_result(&self.connection) {
47 // Avoid panicking, if we already have a panic. We don't want to mask the
48 // original error.
49 if !panicking() {
50 panic!("Unexpected error disconnecting (after rollback attempt): {e:?}")
51 }
52 }
53 }
54 Err(e) => {
55 // Avoid panicking, if we already have a panic. We don't want to mask the original
56 // error.
57 if !panicking() {
58 panic!("Unexpected error disconnecting: {e:?}")
59 }
60 }
61 }
62 }
63}
64
65/// The connection handle references storage of all information about the connection to the data
66/// source, including status, transaction state, and error information.
67///
68/// If you want to enable the connection pooling support build into the ODBC driver manager have a
69/// look at [`crate::Environment::set_connection_pooling`].
70///
71/// In order to create multiple statements with the same connection and for other use cases,
72/// operations like [`Self::execute`] or [`Self::prepare`] are taking a shared reference of `self`
73/// rather than `&mut self`. However, since error handling is done through state changes of the
74/// underlying connection managed by the ODBC driver, this implies that `Connection` must not be
75/// `Sync`.
76pub struct Connection<'c> {
77 connection: handles::Connection<'c>,
78}
79
80impl<'c> Connection<'c> {
81 pub(crate) fn new(connection: handles::Connection<'c>) -> Self {
82 Self { connection }
83 }
84
85 /// Transfer ownership of this open connection to a wrapper around the raw ODBC pointer. The
86 /// wrapper allows you to call ODBC functions on the handle, but doesn't care if the connection
87 /// is in the right state.
88 ///
89 /// You should not have a need to call this method if your use case is covered by this library,
90 /// but, in case it is not, this may help you to break out of the type structure which might be
91 /// to rigid for you, while simultaneously abondoning its safeguards.
92 pub fn into_handle(self) -> handles::Connection<'c> {
93 // We do not want the compiler to invoke `Drop`, since drop would disconnect, yet we want to
94 // transfer ownership to the connection handle.
95 let dont_drop_me = MaybeUninit::new(self);
96 let self_ptr = dont_drop_me.as_ptr();
97
98 // Safety: We know `dont_drop_me` is (still) valid at this point so reading the ptr is okay
99 unsafe { ptr::read(&(*self_ptr).connection) }
100 }
101
102 /// Executes an SQL statement. This is the fastest way to submit an SQL statement for one-time
103 /// execution. In case you do **not** want to execute more statements on this connection, you
104 /// may want to use [`Self::into_cursor`] instead, which would create a cursor taking ownership
105 /// of the connection.
106 ///
107 /// # Parameters
108 ///
109 /// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;".
110 /// * `params`: `?` may be used as a placeholder in the statement text. You can use `()` to
111 /// represent no parameters. See the [`crate::parameter`] module level documentation for more
112 /// information on how to pass parameters.
113 /// * `query_timeout_sec`: Use this to limit the time the query is allowed to take, before
114 /// responding with data to the application. The driver may replace the number of seconds you
115 /// provide with a minimum or maximum value.
116 ///
117 /// For the timeout to work the driver must support this feature. E.g. PostgreSQL, and
118 /// Microsoft SQL Server do, but SQLite or MariaDB do not.
119 ///
120 /// You can specify ``0``, to deactivate the timeout, this is the default. So if you want no
121 /// timeout, just leave it at `None`. Only reason to specify ``0`` is if for some reason your
122 /// datasource does not have ``0`` as default.
123 ///
124 /// This corresponds to `SQL_ATTR_QUERY_TIMEOUT` in the ODBC C API.
125 ///
126 /// See: <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetstmtattr-function>
127 ///
128 /// # Return
129 ///
130 /// Returns `Some` if a cursor is created. If `None` is returned no cursor has been created (
131 /// e.g. the query came back empty). Note that an empty query may also create a cursor with zero
132 /// rows.
133 ///
134 /// # Example
135 ///
136 /// ```no_run
137 /// use odbc_api::{Environment, ConnectionOptions};
138 ///
139 /// let env = Environment::new()?;
140 ///
141 /// let mut conn = env.connect(
142 /// "YourDatabase", "SA", "My@Test@Password1",
143 /// ConnectionOptions::default()
144 /// )?;
145 /// // This query does not use any parameters.
146 /// let query_params = ();
147 /// let timeout_sec = None;
148 /// if let Some(cursor) = conn.execute(
149 /// "SELECT year, name FROM Birthdays;",
150 /// query_params,
151 /// timeout_sec)?
152 /// {
153 /// // Use cursor to process query results.
154 /// }
155 /// # Ok::<(), odbc_api::Error>(())
156 /// ```
157 pub fn execute(
158 &self,
159 query: &str,
160 params: impl ParameterCollectionRef,
161 query_timeout_sec: Option<usize>,
162 ) -> Result<Option<CursorImpl<StatementImpl<'_>>>, Error> {
163 // Only allocate the statement, if we know we are going to execute something.
164 if params.parameter_set_size() == 0 {
165 return Ok(None);
166 }
167 let mut statement = self.preallocate()?;
168 if let Some(seconds) = query_timeout_sec {
169 statement.set_query_timeout_sec(seconds)?;
170 }
171 statement.into_cursor(query, params)
172 }
173
174 /// Executes an SQL statement asynchronously using polling mode. ⚠️**Attention**⚠️: Please read
175 /// [Asynchronous execution using polling mode](crate::guide#asynchronous-execution-using-polling-mode)
176 /// before using this functions.
177 ///
178 /// Asynchronous sibling of [`Self::execute`]. Each time the driver returns control to your
179 /// application the future returned by `sleep` is awaited, before the driver is polled again.
180 /// This avoids a busy loop. `sleep` is a synchronous factor for a future which is awaited.
181 /// `sleep` should not be implemented using a sleep which blocks the system thread, but rather
182 /// use methods provided by your asynchronous runtime. E.g.:
183 ///
184 /// ```
185 /// use odbc_api::{Connection, IntoParameter, Error};
186 /// use std::time::Duration;
187 ///
188 /// async fn insert_post<'a>(
189 /// connection: &'a Connection<'a>,
190 /// user: &str,
191 /// post: &str,
192 /// ) -> Result<(), Error> {
193 /// // Poll every 50 ms.
194 /// let sleep = || tokio::time::sleep(Duration::from_millis(50));
195 /// let sql = "INSERT INTO POSTS (user, post) VALUES (?, ?)";
196 /// // Execute query using ODBC polling method
197 /// let params = (&user.into_parameter(), &post.into_parameter());
198 /// connection.execute_polling(&sql, params, sleep).await?;
199 /// Ok(())
200 /// }
201 /// ```
202 ///
203 /// **Attention**: This feature requires driver support, otherwise the calls will just block
204 /// until they are finished. At the time of writing this out of Microsoft SQL Server,
205 /// PostgerSQL, SQLite and MariaDB this worked only with Microsoft SQL Server. For code generic
206 /// over every driver you may still use this. The functions will return with the correct results
207 /// just be aware that may block until they are finished.
208 ///
209 /// This uses the ODBC polling mode under the hood. See:
210 /// <https://learn.microsoft.com/sql/odbc/reference/develop-app/asynchronous-execution-polling-method>
211 pub async fn execute_polling(
212 &self,
213 query: &str,
214 params: impl ParameterCollectionRef,
215 sleep: impl Sleep,
216 ) -> Result<Option<CursorPolling<StatementImpl<'_>>>, Error> {
217 // Only allocate the statement, if we know we are going to execute something.
218 if params.parameter_set_size() == 0 {
219 return Ok(None);
220 }
221 let query = SqlText::new(query);
222 let mut statement = self.allocate_statement()?;
223 statement.set_async_enable(true).into_result(&statement)?;
224 execute_with_parameters_polling(statement, Some(&query), params, sleep).await
225 }
226
227 /// Similar to [`Self::execute`], but takes ownership of the connection. This is useful if e.g.
228 /// youwant to open a connection and execute a query in a function and return a self containing
229 /// cursor.
230 ///
231 /// # Parameters
232 ///
233 /// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;".
234 /// * `params`: `?` may be used as a placeholder in the statement text. You can use `()` to
235 /// represent no parameters. See the [`crate::parameter`] module level documentation for more
236 /// information on how to pass parameters.
237 /// * `query_timeout_sec`: Use this to limit the time the query is allowed to take, before
238 /// responding with data to the application. The driver may replace the number of seconds you
239 /// provide with a minimum or maximum value.
240 ///
241 /// For the timeout to work the driver must support this feature. E.g. PostgreSQL, and
242 /// Microsoft SQL Server do, but SQLite or MariaDB do not.
243 ///
244 /// You can specify ``0``, to deactivate the timeout, this is the default. So if you want no
245 /// timeout, just leave it at `None`. Only reason to specify ``0`` is if for some reason your
246 /// datasource does not have ``0`` as default.
247 ///
248 /// This corresponds to `SQL_ATTR_QUERY_TIMEOUT` in the ODBC C API.
249 ///
250 /// See: <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetstmtattr-function>
251 ///
252 /// ```no_run
253 /// use odbc_api::{environment, Error, Cursor, ConnectionOptions};
254 ///
255 ///
256 /// const CONNECTION_STRING: &str =
257 /// "Driver={ODBC Driver 18 for SQL Server};\
258 /// Server=localhost;UID=SA;\
259 /// PWD=My@Test@Password1;";
260 ///
261 /// fn execute_query(query: &str) -> Result<Option<impl Cursor>, Error> {
262 /// let env = environment()?;
263 /// let conn = env.connect_with_connection_string(
264 /// CONNECTION_STRING,
265 /// ConnectionOptions::default()
266 /// )?;
267 ///
268 /// // connect.execute(&query, (), None) // Compiler error: Would return local ref to
269 /// // `conn`.
270 ///
271 /// let maybe_cursor = conn.into_cursor(&query, (), None)?;
272 /// Ok(maybe_cursor)
273 /// }
274 /// ```
275 pub fn into_cursor(
276 self,
277 query: &str,
278 params: impl ParameterCollectionRef,
279 query_timeout_sec: Option<usize>,
280 ) -> Result<Option<CursorImpl<StatementConnection<Connection<'c>>>>, ConnectionAndError<'c>>
281 {
282 // With the current Rust version the borrow checker needs some convincing, so that it allows
283 // us to return the Connection, even though the Result of execute borrows it.
284 let mut error = None;
285 let mut cursor = None;
286 match self.execute(query, params, query_timeout_sec) {
287 Ok(Some(c)) => cursor = Some(c),
288 Ok(None) => return Ok(None),
289 Err(e) => error = Some(e),
290 };
291 if let Some(e) = error {
292 drop(cursor);
293 return Err(ConnectionAndError {
294 error: e,
295 previous: self,
296 });
297 }
298 let cursor = cursor.unwrap();
299 // The rust compiler needs some help here. It assumes otherwise that the lifetime of the
300 // resulting cursor would depend on the lifetime of `params`.
301 let mut cursor = ManuallyDrop::new(cursor);
302 let handle = cursor.as_sys();
303 // Safe: `handle` is a valid statement, and we are giving up ownership of `self`.
304 let statement = unsafe { StatementConnection::new(handle, self) };
305 // Safe: `statement is in the cursor state`.
306 let cursor = unsafe { CursorImpl::new(statement) };
307 Ok(Some(cursor))
308 }
309
310 /// Prepares an SQL statement. This is recommended for repeated execution of similar queries.
311 ///
312 /// Should your use case require you to execute the same query several times with different
313 /// parameters, prepared queries are the way to go. These give the database a chance to cache
314 /// the access plan associated with your SQL statement. It is not unlike compiling your program
315 /// once and executing it several times.
316 ///
317 /// ```
318 /// use odbc_api::{Connection, Error, IntoParameter};
319 /// use std::io::{self, stdin, Read};
320 ///
321 /// fn interactive(conn: &Connection) -> io::Result<()>{
322 /// let mut prepared = conn.prepare("SELECT * FROM Movies WHERE title=?;").unwrap();
323 /// let mut title = String::new();
324 /// stdin().read_line(&mut title)?;
325 /// while !title.is_empty() {
326 /// match prepared.execute(&title.as_str().into_parameter()) {
327 /// Err(e) => println!("{}", e),
328 /// // Most drivers would return a result set even if no Movie with the title is found,
329 /// // the result set would just be empty. Well, most drivers.
330 /// Ok(None) => println!("No result set generated."),
331 /// Ok(Some(cursor)) => {
332 /// // ...print cursor contents...
333 /// }
334 /// }
335 /// stdin().read_line(&mut title)?;
336 /// }
337 /// Ok(())
338 /// }
339 /// ```
340 ///
341 /// # Parameters
342 ///
343 /// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;". `?`
344 /// may be used as a placeholder in the statement text, to be replaced with parameters during
345 /// execution.
346 pub fn prepare(&self, query: &str) -> Result<Prepared<StatementImpl<'_>>, Error> {
347 let query = SqlText::new(query);
348 let mut stmt = self.allocate_statement()?;
349 stmt.prepare(&query).into_result(&stmt)?;
350 Ok(Prepared::new(stmt))
351 }
352
353 /// Prepares an SQL statement which takes ownership of the connection. The advantage over
354 /// [`Self::prepare`] is, that you do not need to keep track of the lifetime of the connection
355 /// seperatly and can create types which do own the prepared query and only depend on the
356 /// lifetime of the environment. The downside is that you can not use the connection for
357 /// anything else anymore.
358 ///
359 /// # Parameters
360 ///
361 /// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;". `?`
362 /// may be used as a placeholder in the statement text, to be replaced with parameters during
363 /// execution.
364 ///
365 /// ```no_run
366 /// use odbc_api::{
367 /// environment, Error, ColumnarBulkInserter, handles::StatementConnection,
368 /// buffers::{BufferDesc, AnyBuffer}, ConnectionOptions, Connection
369 /// };
370 ///
371 /// const CONNECTION_STRING: &str =
372 /// "Driver={ODBC Driver 18 for SQL Server};\
373 /// Server=localhost;UID=SA;\
374 /// PWD=My@Test@Password1;";
375 ///
376 /// /// Supports columnar bulk inserts on a heterogenous schema (columns have different types),
377 /// /// takes ownership of a connection created using an environment with static lifetime.
378 /// type Inserter = ColumnarBulkInserter<StatementConnection<Connection<'static>>, AnyBuffer>;
379 ///
380 /// /// Creates an inserter which can be reused to bulk insert birthyears with static lifetime.
381 /// fn make_inserter(query: &str) -> Result<Inserter, Error> {
382 /// let env = environment()?;
383 /// let conn = env.connect_with_connection_string(
384 /// CONNECTION_STRING,
385 /// ConnectionOptions::default()
386 /// )?;
387 /// let prepared = conn.into_prepared("INSERT INTO Birthyear (name, year) VALUES (?, ?)")?;
388 /// let buffers = [
389 /// BufferDesc::Text { max_str_len: 255},
390 /// BufferDesc::I16 { nullable: false },
391 /// ];
392 /// let capacity = 400;
393 /// prepared.into_column_inserter(capacity, buffers)
394 /// }
395 /// ```
396 pub fn into_prepared(
397 self,
398 query: &str,
399 ) -> Result<Prepared<StatementConnection<Connection<'c>>>, Error> {
400 let query = SqlText::new(query);
401 let mut stmt = self.allocate_statement()?;
402 stmt.prepare(&query).into_result(&stmt)?;
403 // Safe: `handle` is a valid statement, and we are giving up ownership of `self`.
404 let stmt = unsafe { StatementConnection::new(stmt.into_sys(), self) };
405 Ok(Prepared::new(stmt))
406 }
407
408 /// Allocates an SQL statement handle. This is recommended if you want to sequentially execute
409 /// different queries over the same connection, as you avoid the overhead of allocating a
410 /// statement handle for each query.
411 ///
412 /// Should you want to repeatedly execute the same query with different parameters try
413 /// [`Self::prepare`] instead.
414 ///
415 /// # Example
416 ///
417 /// ```
418 /// use odbc_api::{Connection, Error};
419 /// use std::io::{self, stdin, Read};
420 ///
421 /// fn interactive(conn: &Connection) -> io::Result<()>{
422 /// let mut statement = conn.preallocate().unwrap();
423 /// let mut query = String::new();
424 /// stdin().read_line(&mut query)?;
425 /// while !query.is_empty() {
426 /// match statement.execute(&query, ()) {
427 /// Err(e) => println!("{}", e),
428 /// Ok(None) => println!("No results set generated."),
429 /// Ok(Some(cursor)) => {
430 /// // ...print cursor contents...
431 /// },
432 /// }
433 /// stdin().read_line(&mut query)?;
434 /// }
435 /// Ok(())
436 /// }
437 /// ```
438 pub fn preallocate(&self) -> Result<Preallocated<StatementImpl<'_>>, Error> {
439 let stmt = self.allocate_statement()?;
440 unsafe { Ok(Preallocated::new(stmt)) }
441 }
442
443 /// Creates a preallocated statement handle like [`Self::preallocate`]. Yet the statement handle
444 /// also takes ownership of the connection.
445 pub fn into_preallocated(
446 self,
447 ) -> Result<Preallocated<StatementConnection<Connection<'c>>>, Error> {
448 let stmt = self.allocate_statement()?;
449 // Safe: We know `stmt` is a valid statement handle and self is the connection which has
450 // been used to allocate it.
451 unsafe {
452 let stmt = StatementConnection::new(stmt.into_sys(), self);
453 Ok(Preallocated::new(stmt))
454 }
455 }
456
457 /// Specify the transaction mode. By default, ODBC transactions are in auto-commit mode.
458 /// Switching from manual-commit mode to auto-commit mode automatically commits any open
459 /// transaction on the connection. There is no open or begin transaction method. Each statement
460 /// execution automatically starts a new transaction or adds to the existing one.
461 ///
462 /// In manual commit mode you can use [`Connection::commit`] or [`Connection::rollback`]. Keep
463 /// in mind, that even `SELECT` statements can open new transactions. This library will rollback
464 /// open transactions if a connection goes out of SCOPE. This however will log an error, since
465 /// the transaction state is only discovered during a failed disconnect. It is preferable that
466 /// the application makes sure all transactions are closed if in manual commit mode.
467 pub fn set_autocommit(&self, enabled: bool) -> Result<(), Error> {
468 self.connection
469 .set_autocommit(enabled)
470 .into_result(&self.connection)
471 }
472
473 /// To commit a transaction in manual-commit mode.
474 pub fn commit(&self) -> Result<(), Error> {
475 self.connection.commit().into_result(&self.connection)
476 }
477
478 /// To rollback a transaction in manual-commit mode.
479 pub fn rollback(&self) -> Result<(), Error> {
480 self.connection.rollback().into_result(&self.connection)
481 }
482
483 /// Indicates the state of the connection. If `true` the connection has been lost. If `false`,
484 /// the connection is still active.
485 pub fn is_dead(&self) -> Result<bool, Error> {
486 self.connection.is_dead().into_result(&self.connection)
487 }
488
489 /// Network packet size in bytes. Requries driver support.
490 pub fn packet_size(&self) -> Result<u32, Error> {
491 self.connection.packet_size().into_result(&self.connection)
492 }
493
494 /// Get the name of the database management system used by the connection.
495 pub fn database_management_system_name(&self) -> Result<String, Error> {
496 let mut buf = Vec::new();
497 self.connection
498 .fetch_database_management_system_name(&mut buf)
499 .into_result(&self.connection)?;
500 let name = slice_to_utf8(&buf).unwrap();
501 Ok(name)
502 }
503
504 /// Maximum length of catalog names.
505 pub fn max_catalog_name_len(&self) -> Result<u16, Error> {
506 self.connection
507 .max_catalog_name_len()
508 .into_result(&self.connection)
509 }
510
511 /// Maximum length of schema names.
512 pub fn max_schema_name_len(&self) -> Result<u16, Error> {
513 self.connection
514 .max_schema_name_len()
515 .into_result(&self.connection)
516 }
517
518 /// Maximum length of table names.
519 pub fn max_table_name_len(&self) -> Result<u16, Error> {
520 self.connection
521 .max_table_name_len()
522 .into_result(&self.connection)
523 }
524
525 /// Maximum length of column names.
526 pub fn max_column_name_len(&self) -> Result<u16, Error> {
527 self.connection
528 .max_column_name_len()
529 .into_result(&self.connection)
530 }
531
532 /// Get the name of the current catalog being used by the connection.
533 pub fn current_catalog(&self) -> Result<String, Error> {
534 let mut buf = Vec::new();
535 self.connection
536 .fetch_current_catalog(&mut buf)
537 .into_result(&self.connection)?;
538 let name = slice_to_utf8(&buf).expect("Return catalog must be correctly encoded");
539 Ok(name)
540 }
541
542 /// A cursor describing columns of all tables matching the patterns. Patterns support as
543 /// placeholder `%` for multiple characters or `_` for a single character. Use `\` to escape.The
544 /// returned cursor has the columns:
545 /// `TABLE_CAT`, `TABLE_SCHEM`, `TABLE_NAME`, `COLUMN_NAME`, `DATA_TYPE`, `TYPE_NAME`,
546 /// `COLUMN_SIZE`, `BUFFER_LENGTH`, `DECIMAL_DIGITS`, `NUM_PREC_RADIX`, `NULLABLE`,
547 /// `REMARKS`, `COLUMN_DEF`, `SQL_DATA_TYPE`, `SQL_DATETIME_SUB`, `CHAR_OCTET_LENGTH`,
548 /// `ORDINAL_POSITION`, `IS_NULLABLE`.
549 ///
550 /// In addition to that there may be a number of columns specific to the data source.
551 pub fn columns(
552 &self,
553 catalog_name: &str,
554 schema_name: &str,
555 table_name: &str,
556 column_name: &str,
557 ) -> Result<CursorImpl<StatementImpl<'_>>, Error> {
558 execute_columns(
559 self.allocate_statement()?,
560 &SqlText::new(catalog_name),
561 &SqlText::new(schema_name),
562 &SqlText::new(table_name),
563 &SqlText::new(column_name),
564 )
565 }
566
567 /// List tables, schemas, views and catalogs of a datasource.
568 ///
569 /// # Parameters
570 ///
571 /// * `catalog_name`: Filter result by catalog name. Accept search patterns. Use `%` to match
572 /// any number of characters. Use `_` to match exactly on character. Use `\` to escape
573 /// characeters.
574 /// * `schema_name`: Filter result by schema. Accepts patterns in the same way as
575 /// `catalog_name`.
576 /// * `table_name`: Filter result by table. Accepts patterns in the same way as `catalog_name`.
577 /// * `table_type`: Filters results by table type. E.g: 'TABLE', 'VIEW'. This argument accepts a
578 /// comma separeted list of table types. Omit it to not filter the result by table type at
579 /// all.
580 ///
581 /// # Example
582 ///
583 /// ```
584 /// use odbc_api::{Connection, Cursor, Error, ResultSetMetadata, buffers::TextRowSet};
585 ///
586 /// fn print_all_tables(conn: &Connection<'_>) -> Result<(), Error> {
587 /// // Set all filters to an empty string, to really print all tables
588 /// let mut cursor = conn.tables("", "", "", "")?;
589 ///
590 /// // The column are gonna be TABLE_CAT,TABLE_SCHEM,TABLE_NAME,TABLE_TYPE,REMARKS, but may
591 /// // also contain additional driver specific columns.
592 /// for (index, name) in cursor.column_names()?.enumerate() {
593 /// if index != 0 {
594 /// print!(",")
595 /// }
596 /// print!("{}", name?);
597 /// }
598 ///
599 /// let batch_size = 100;
600 /// let mut buffer = TextRowSet::for_cursor(batch_size, &mut cursor, Some(4096))?;
601 /// let mut row_set_cursor = cursor.bind_buffer(&mut buffer)?;
602 ///
603 /// while let Some(row_set) = row_set_cursor.fetch()? {
604 /// for row_index in 0..row_set.num_rows() {
605 /// if row_index != 0 {
606 /// print!("\n");
607 /// }
608 /// for col_index in 0..row_set.num_cols() {
609 /// if col_index != 0 {
610 /// print!(",");
611 /// }
612 /// let value = row_set
613 /// .at_as_str(col_index, row_index)
614 /// .unwrap()
615 /// .unwrap_or("NULL");
616 /// print!("{}", value);
617 /// }
618 /// }
619 /// }
620 ///
621 /// Ok(())
622 /// }
623 /// ```
624 pub fn tables(
625 &self,
626 catalog_name: &str,
627 schema_name: &str,
628 table_name: &str,
629 table_type: &str,
630 ) -> Result<CursorImpl<StatementImpl<'_>>, Error> {
631 let statement = self.allocate_statement()?;
632
633 execute_tables(
634 statement,
635 &SqlText::new(catalog_name),
636 &SqlText::new(schema_name),
637 &SqlText::new(table_name),
638 &SqlText::new(table_type),
639 )
640 }
641
642 /// This can be used to retrieve either a list of foreign keys in the specified table or a list
643 /// of foreign keys in other table that refer to the primary key of the specified table.
644 ///
645 /// See: <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlforeignkeys-function>
646 pub fn foreign_keys(
647 &self,
648 pk_catalog_name: &str,
649 pk_schema_name: &str,
650 pk_table_name: &str,
651 fk_catalog_name: &str,
652 fk_schema_name: &str,
653 fk_table_name: &str,
654 ) -> Result<CursorImpl<StatementImpl<'_>>, Error> {
655 let statement = self.allocate_statement()?;
656
657 execute_foreign_keys(
658 statement,
659 &SqlText::new(pk_catalog_name),
660 &SqlText::new(pk_schema_name),
661 &SqlText::new(pk_table_name),
662 &SqlText::new(fk_catalog_name),
663 &SqlText::new(fk_schema_name),
664 &SqlText::new(fk_table_name),
665 )
666 }
667
668 /// The buffer descriptions for all standard buffers (not including extensions) returned in the
669 /// columns query (e.g. [`Connection::columns`]).
670 ///
671 /// # Arguments
672 ///
673 /// * `type_name_max_len` - The maximum expected length of type names.
674 /// * `remarks_max_len` - The maximum expected length of remarks.
675 /// * `column_default_max_len` - The maximum expected length of column defaults.
676 pub fn columns_buffer_descs(
677 &self,
678 type_name_max_len: usize,
679 remarks_max_len: usize,
680 column_default_max_len: usize,
681 ) -> Result<Vec<BufferDesc>, Error> {
682 let null_i16 = BufferDesc::I16 { nullable: true };
683
684 let not_null_i16 = BufferDesc::I16 { nullable: false };
685
686 let null_i32 = BufferDesc::I32 { nullable: true };
687
688 // The definitions for these descriptions are taken from the documentation of `SQLColumns`
689 // located at https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlcolumns-function
690 let catalog_name_desc = BufferDesc::Text {
691 max_str_len: self.max_catalog_name_len()? as usize,
692 };
693
694 let schema_name_desc = BufferDesc::Text {
695 max_str_len: self.max_schema_name_len()? as usize,
696 };
697
698 let table_name_desc = BufferDesc::Text {
699 max_str_len: self.max_table_name_len()? as usize,
700 };
701
702 let column_name_desc = BufferDesc::Text {
703 max_str_len: self.max_column_name_len()? as usize,
704 };
705
706 let data_type_desc = not_null_i16;
707
708 let type_name_desc = BufferDesc::Text {
709 max_str_len: type_name_max_len,
710 };
711
712 let column_size_desc = null_i32;
713 let buffer_len_desc = null_i32;
714 let decimal_digits_desc = null_i16;
715 let precision_radix_desc = null_i16;
716 let nullable_desc = not_null_i16;
717
718 let remarks_desc = BufferDesc::Text {
719 max_str_len: remarks_max_len,
720 };
721
722 let column_default_desc = BufferDesc::Text {
723 max_str_len: column_default_max_len,
724 };
725
726 let sql_data_type_desc = not_null_i16;
727 let sql_datetime_sub_desc = null_i16;
728 let char_octet_len_desc = null_i32;
729 let ordinal_pos_desc = BufferDesc::I32 { nullable: false };
730
731 // We expect strings to be `YES`, `NO`, or a zero-length string, so `3` should be
732 // sufficient.
733 const IS_NULLABLE_LEN_MAX_LEN: usize = 3;
734 let is_nullable_desc = BufferDesc::Text {
735 max_str_len: IS_NULLABLE_LEN_MAX_LEN,
736 };
737
738 Ok(vec![
739 catalog_name_desc,
740 schema_name_desc,
741 table_name_desc,
742 column_name_desc,
743 data_type_desc,
744 type_name_desc,
745 column_size_desc,
746 buffer_len_desc,
747 decimal_digits_desc,
748 precision_radix_desc,
749 nullable_desc,
750 remarks_desc,
751 column_default_desc,
752 sql_data_type_desc,
753 sql_datetime_sub_desc,
754 char_octet_len_desc,
755 ordinal_pos_desc,
756 is_nullable_desc,
757 ])
758 }
759
760 fn allocate_statement(&self) -> Result<StatementImpl<'_>, Error> {
761 self.connection
762 .allocate_statement()
763 .into_result(&self.connection)
764 }
765}
766
767/// Implement `Debug` for [`Connection`], in order to play nice with derive Debugs for struct
768/// holding a [`Connection`].
769impl Debug for Connection<'_> {
770 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
771 write!(f, "Connection")
772 }
773}
774
775/// We need to implement [`StatementParent`] for [`Connection`] in order to express ownership of a
776/// connection for a statement handle. This is e.g. needed for [`Connection::into_cursor`].
777///
778/// # Safety:
779///
780/// Connection wraps an open Connection. It keeps the handle alive and valid during its lifetime.
781unsafe impl StatementParent for Connection<'_> {}
782
783/// We need to implement [`StatementParent`] for `Arc<Connection>` in order to be able to express
784/// ownership of a shared connection from a statement handle. This is e.g. needed for
785/// [`ConnectionTransitions::into_cursor`].
786///
787/// # Safety:
788///
789/// `Arc<Connection>` wraps an open Connection. It keeps the handle alive and valid during its
790/// lifetime.
791unsafe impl StatementParent for Arc<Connection<'_>> {}
792
793/// Options to be passed then opening a connection to a datasource.
794#[derive(Default, Clone, Copy)]
795pub struct ConnectionOptions {
796 /// Number of seconds to wait for a login request to complete before returning to the
797 /// application. The default is driver-dependent. If `0` the timeout is disabled and a
798 /// connection attempt will wait indefinitely.
799 ///
800 /// If the specified timeout exceeds the maximum login timeout in the data source, the driver
801 /// substitutes that value and uses the maximum login timeout instead.
802 ///
803 /// This corresponds to the `SQL_ATTR_LOGIN_TIMEOUT` attribute in the ODBC specification.
804 ///
805 /// See:
806 /// <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetconnectattr-function>
807 pub login_timeout_sec: Option<u32>,
808 /// Packet size in bytes. Not all drivers support this option.
809 pub packet_size: Option<u32>,
810}
811
812impl ConnectionOptions {
813 /// Set the attributes corresponding to the connection options to an allocated connection
814 /// handle. Usually you would rather provide the options then creating the connection with e.g.
815 /// [`crate::Environment::connect_with_connection_string`] rather than calling this method
816 /// yourself.
817 pub fn apply(&self, handle: &handles::Connection) -> Result<(), Error> {
818 if let Some(timeout) = self.login_timeout_sec {
819 handle.set_login_timeout_sec(timeout).into_result(handle)?;
820 }
821 if let Some(packet_size) = self.packet_size {
822 handle.set_packet_size(packet_size).into_result(handle)?;
823 }
824 Ok(())
825 }
826}
827
828/// You can use this method to escape a password so it is suitable to be appended to an ODBC
829/// connection string as the value for the `PWD` attribute. This method is only of interest for
830/// application in need to create their own connection strings.
831///
832/// See:
833///
834/// * <https://stackoverflow.com/questions/22398212/escape-semicolon-in-odbc-connection-string-in-app-config-file>
835/// * <https://docs.microsoft.com/en-us/dotnet/api/system.data.odbc.odbcconnection.connectionstring>
836///
837/// # Example
838///
839/// ```
840/// use odbc_api::escape_attribute_value;
841///
842/// let password = "abc;123}";
843/// let user = "SA";
844/// let mut connection_string_without_credentials =
845/// "Driver={ODBC Driver 18 for SQL Server};Server=localhost;";
846///
847/// let connection_string = format!(
848/// "{}UID={};PWD={};",
849/// connection_string_without_credentials,
850/// user,
851/// escape_attribute_value(password)
852/// );
853///
854/// assert_eq!(
855/// "Driver={ODBC Driver 18 for SQL Server};Server=localhost;UID=SA;PWD={abc;123}}};",
856/// connection_string
857/// );
858/// ```
859///
860/// ```
861/// use odbc_api::escape_attribute_value;
862/// assert_eq!("abc", escape_attribute_value("abc"));
863/// assert_eq!("ab}c", escape_attribute_value("ab}c"));
864/// assert_eq!("{ab;c}", escape_attribute_value("ab;c"));
865/// assert_eq!("{a}}b;c}", escape_attribute_value("a}b;c"));
866/// assert_eq!("{ab+c}", escape_attribute_value("ab+c"));
867/// ```
868pub fn escape_attribute_value(unescaped: &str) -> Cow<'_, str> {
869 // Search the string for semicolon (';') if we do not find any, nothing is to do and we can work
870 // without an extra allocation.
871 //
872 // * We escape ';' because it serves as a separator between key=value pairs
873 // * We escape '+' because passwords with `+` must be escaped on PostgreSQL for some reason.
874 if unescaped.contains(&[';', '+'][..]) {
875 // Surround the string with curly braces ('{','}') and escape every closing curly brace by
876 // repeating it.
877 let escaped = unescaped.replace('}', "}}");
878 Cow::Owned(format!("{{{escaped}}}"))
879 } else {
880 Cow::Borrowed(unescaped)
881 }
882}
883
884/// A pair of the error and the previous state, before the operation caused the error.
885///
886/// Some functions in this crate take a `self` and return another type in the result to express a
887/// state transitions in the underlying ODBC handle. In order to make such operations retryable, or
888/// offer other alternatives of recovery, they may return this error type instead of a plain
889/// [`Error`].
890#[derive(Debug)]
891pub struct FailedStateTransition<S> {
892 /// The ODBC error which caused the state transition to fail.
893 pub error: Error,
894 /// The state before the transition failed. This is useful to e.g. retry the operation, or
895 /// recover in another way.
896 pub previous: S,
897}
898
899impl<S> From<FailedStateTransition<S>> for Error {
900 fn from(value: FailedStateTransition<S>) -> Self {
901 value.error
902 }
903}
904
905impl<S> Display for FailedStateTransition<S> {
906 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
907 write!(f, "{}", self.error)
908 }
909}
910
911impl<S> std::error::Error for FailedStateTransition<S>
912where
913 S: Debug,
914{
915 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
916 self.error.source()
917 }
918}
919
920/// An error type wrapping an [`Error`] and a [`Connection`]. It is used by
921/// [`Connection::into_cursor`], so that in case of failure the user can reuse the connection to try
922/// again. [`Connection::into_cursor`] could achieve the same by returning a tuple in case of an
923/// error, but this type causes less friction in most scenarios because [`Error`] implements
924/// [`From`] [`ConnectionAndError`] and it therfore works with the question mark operater (`?`).
925type ConnectionAndError<'conn> = FailedStateTransition<Connection<'conn>>;
926
927/// Ability to transition ownership of the connection to various children which represent statement
928/// handles in various states. E.g. [`crate::Prepared`] or [`crate::Cursor`]. Transfering ownership
929/// of the connection could e.g. be useful if you want to clean the connection after you are done
930/// with the child.
931///
932/// Having this in a trait rather than directly on [`Connection`] allows us to be generic over the
933/// type of ownership we express. E.g. we can express shared ownership of a connection by
934/// using an `Arc<Mutex<Connection>>` or `Arc<Connection>`. Or a still exclusive ownership using
935/// a plain [`Connection`].
936pub trait ConnectionTransitions: Sized {
937 // Note to self. This might eveolve into a `Connection` trait. Which expresses ownership
938 // of a connection (shared or not). It could allow to get a dereferened borrowed conection
939 // which does not allow for state transtions as of now (like StatementRef). I may not want to
940 // rock the boat that much right now.
941
942 /// The type passed to [crate::handles::StatementConnection] to express ownership of the
943 /// connection.
944 type StatementParent: StatementParent;
945
946 /// Similar to [`crate::Connection::into_cursor`], yet it operates on an
947 /// `Arc<Mutex<Connection>>`. `Arc<Connection>` can be used if you want shared ownership of
948 /// connections. However, `Arc<Connection>` is not `Send` due to `Connection` not being `Sync`.
949 /// So sometimes you may want to wrap your `Connection` into an `Arc<Mutex<Connection>>` to
950 /// allow shared ownership of the connection across threads. This function allows you to create
951 /// a cursor from such a shared which also holds a strong reference to it.
952 ///
953 /// # Parameters
954 ///
955 /// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;".
956 /// * `params`: `?` may be used as a placeholder in the statement text. You can use `()` to
957 /// represent no parameters. See the [`crate::parameter`] module level documentation for more
958 /// information on how to pass parameters.
959 /// * `query_timeout_sec`: Use this to limit the time the query is allowed to take, before
960 /// responding with data to the application. The driver may replace the number of seconds you
961 /// provide with a minimum or maximum value.
962 ///
963 /// For the timeout to work the driver must support this feature. E.g. PostgreSQL, and
964 /// Microsoft SQL Server do, but SQLite or MariaDB do not.
965 ///
966 /// You can specify ``0``, to deactivate the timeout, this is the default. So if you want no
967 /// timeout, just leave it at `None`. Only reason to specify ``0`` is if for some reason your
968 /// datasource does not have ``0`` as default.
969 ///
970 /// This corresponds to `SQL_ATTR_QUERY_TIMEOUT` in the ODBC C API.
971 ///
972 /// See: <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetstmtattr-function>
973 fn into_cursor(
974 self,
975 query: &str,
976 params: impl ParameterCollectionRef,
977 query_timeout_sec: Option<usize>,
978 ) -> Result<
979 Option<CursorImpl<StatementConnection<Self::StatementParent>>>,
980 FailedStateTransition<Self>,
981 >;
982
983 /// Prepares an SQL statement which takes ownership of the connection. The advantage over
984 /// [`Connection::prepare`] is, that you do not need to keep track of the lifetime of the
985 /// connection seperatly and can create types which do own the prepared query and only depend on
986 /// the lifetime of the environment.
987 ///
988 /// # Parameters
989 ///
990 /// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;". `?`
991 /// may be used as a placeholder in the statement text, to be replaced with parameters during
992 /// execution.
993 ///
994 /// ```no_run
995 /// use odbc_api::{
996 /// environment, Error, ColumnarBulkInserter, ConnectionTransitions, Connection,
997 /// handles::StatementConnection, buffers::{BufferDesc, AnyBuffer}, ConnectionOptions,
998 /// };
999 ///
1000 /// const CONNECTION_STRING: &str =
1001 /// "Driver={ODBC Driver 18 for SQL Server};\
1002 /// Server=localhost;UID=SA;\
1003 /// PWD=My@Test@Password1;";
1004 ///
1005 /// /// Supports columnar bulk inserts on a heterogenous schema (columns have different types),
1006 /// /// takes ownership of a connection created using an environment with static lifetime.
1007 /// type Inserter = ColumnarBulkInserter<StatementConnection<Connection<'static>>, AnyBuffer>;
1008 ///
1009 /// /// Creates an inserter which can be reused to bulk insert birthyears with static lifetime.
1010 /// fn make_inserter(query: &str) -> Result<Inserter, Error> {
1011 /// let env = environment()?;
1012 /// let conn = env.connect_with_connection_string(
1013 /// CONNECTION_STRING,
1014 /// ConnectionOptions::default()
1015 /// )?;
1016 /// let prepared = conn.into_prepared("INSERT INTO Birthyear (name, year) VALUES (?, ?)")?;
1017 /// let buffers = [
1018 /// BufferDesc::Text { max_str_len: 255},
1019 /// BufferDesc::I16 { nullable: false },
1020 /// ];
1021 /// let capacity = 400;
1022 /// prepared.into_column_inserter(capacity, buffers)
1023 /// }
1024 /// ```
1025 fn into_prepared(
1026 self,
1027 query: &str,
1028 ) -> Result<Prepared<StatementConnection<Self::StatementParent>>, Error>;
1029
1030 /// Creates a preallocated statement handle like [`Connection::preallocate`]. Yet the statement
1031 /// also takes ownership of the connection.
1032 fn into_preallocated(
1033 self,
1034 ) -> Result<Preallocated<StatementConnection<Self::StatementParent>>, Error>;
1035}
1036
1037impl<'env> ConnectionTransitions for Connection<'env> {
1038 type StatementParent = Self;
1039
1040 fn into_cursor(
1041 self,
1042 query: &str,
1043 params: impl ParameterCollectionRef,
1044 query_timeout_sec: Option<usize>,
1045 ) -> Result<Option<CursorImpl<StatementConnection<Self>>>, FailedStateTransition<Self>> {
1046 self.into_cursor(query, params, query_timeout_sec)
1047 }
1048
1049 fn into_prepared(self, query: &str) -> Result<Prepared<StatementConnection<Self>>, Error> {
1050 self.into_prepared(query)
1051 }
1052
1053 fn into_preallocated(self) -> Result<Preallocated<StatementConnection<Self>>, Error> {
1054 self.into_preallocated()
1055 }
1056}
1057
1058impl<'env> ConnectionTransitions for Arc<Connection<'env>> {
1059 type StatementParent = Self;
1060
1061 fn into_cursor(
1062 self,
1063 query: &str,
1064 params: impl ParameterCollectionRef,
1065 query_timeout_sec: Option<usize>,
1066 ) -> Result<Option<CursorImpl<StatementConnection<Self>>>, FailedStateTransition<Self>> {
1067 // Result borrows the connection. We convert the cursor into a raw pointer, to not confuse
1068 // the borrow checker.
1069 let result = self.execute(query, params, query_timeout_sec);
1070 let maybe_stmt_ptr = result
1071 .map(|opt| opt.map(|cursor| cursor.into_stmt().into_sys()))
1072 .map_err(|error| {
1073 // If the execute fails, we return a FailedStateTransition with the error and the
1074 // connection.
1075 FailedStateTransition {
1076 error,
1077 previous: Arc::clone(&self),
1078 }
1079 })?;
1080 let Some(stmt_ptr) = maybe_stmt_ptr else {
1081 return Ok(None);
1082 };
1083 // Safe: The connection is the parent of the statement referenced by `stmt_ptr`.
1084 let stmt = unsafe { StatementConnection::new(stmt_ptr, self) };
1085 // Safe: `stmt` is valid and in cursor state.
1086 let cursor = unsafe { CursorImpl::new(stmt) };
1087 Ok(Some(cursor))
1088 }
1089
1090 fn into_prepared(self, query: &str) -> Result<Prepared<StatementConnection<Self>>, Error> {
1091 let stmt = self.prepare(query)?;
1092 let stmt_ptr = stmt.into_handle().into_sys();
1093 // Safe: The connection is the parent of the statement referenced by `stmt_ptr`.
1094 let stmt = unsafe { StatementConnection::new(stmt_ptr, self) };
1095 // `stmt` is valid and in prepared state.
1096 let prepared = Prepared::new(stmt);
1097 Ok(prepared)
1098 }
1099
1100 fn into_preallocated(self) -> Result<Preallocated<StatementConnection<Self>>, Error> {
1101 let stmt = self.preallocate()?;
1102 let stmt_ptr = stmt.into_handle().into_sys();
1103 // Safe: The connection is the parent of the statement referenced by `stmt_ptr`.
1104 let stmt = unsafe { StatementConnection::new(stmt_ptr, self) };
1105 // Safe: `stmt` is valid and its state is allocated.
1106 let preallocated = unsafe { Preallocated::new(stmt) };
1107 Ok(preallocated)
1108 }
1109}