odbc_api/connection.rs
1use crate::{
2 BlockCursorIterator, CursorImpl, CursorPolling, Error, ParameterCollectionRef, Preallocated,
3 Prepared, PrimaryKeysRow, Sleep,
4 buffers::BufferDesc,
5 execute::execute_with_parameters_polling,
6 handles::{
7 self, SqlText, State, Statement, StatementConnection, StatementImpl, StatementParent,
8 slice_to_utf8,
9 },
10};
11use log::error;
12use std::{
13 borrow::Cow,
14 fmt::{self, Debug, Display},
15 mem::{ManuallyDrop, MaybeUninit},
16 ptr, str,
17 sync::Arc,
18 thread::panicking,
19};
20
21impl Drop for Connection<'_> {
22 fn drop(&mut self) {
23 match self.connection.disconnect().into_result(&self.connection) {
24 Ok(()) => (),
25 Err(Error::Diagnostics {
26 record,
27 function: _,
28 }) if record.state == State::INVALID_STATE_TRANSACTION => {
29 // Invalid transaction state. Let's rollback the current transaction and try again.
30 if let Err(e) = self.rollback() {
31 // Connection might be in a suspended state. See documentation about suspended
32 // state here:
33 // <https://learn.microsoft.com/sql/odbc/reference/syntax/sqlendtran-function>
34 //
35 // See also issue:
36 // <https://github.com/pacman82/odbc-api/issues/574#issuecomment-2286449125>
37
38 error!(
39 "Error during rolling back transaction (In order to recover from \
40 invalid transaction state during disconnect {}",
41 e
42 );
43 }
44 // Transaction might be rolled back or suspended. Now let's try again to disconnect.
45 if let Err(e) = self.connection.disconnect().into_result(&self.connection) {
46 // Avoid panicking, if we already have a panic. We don't want to mask the
47 // original error.
48 if !panicking() {
49 panic!("Unexpected error disconnecting (after rollback attempt): {e:?}")
50 }
51 }
52 }
53 Err(e) => {
54 // Avoid panicking, if we already have a panic. We don't want to mask the original
55 // error.
56 if !panicking() {
57 panic!("Unexpected error disconnecting: {e:?}")
58 }
59 }
60 }
61 }
62}
63
64/// The connection handle references storage of all information about the connection to the data
65/// source, including status, transaction state, and error information.
66///
67/// If you want to enable the connection pooling support build into the ODBC driver manager have a
68/// look at [`crate::Environment::set_connection_pooling`].
69///
70/// In order to create multiple statements with the same connection and for other use cases,
71/// operations like [`Self::execute`] or [`Self::prepare`] are taking a shared reference of `self`
72/// rather than `&mut self`. However, since error handling is done through state changes of the
73/// underlying connection managed by the ODBC driver, this implies that `Connection` must not be
74/// `Sync`.
75pub struct Connection<'c> {
76 connection: handles::Connection<'c>,
77}
78
79impl<'c> Connection<'c> {
80 pub(crate) fn new(connection: handles::Connection<'c>) -> Self {
81 Self { connection }
82 }
83
84 /// Transfer ownership of this open connection to a wrapper around the raw ODBC pointer. The
85 /// wrapper allows you to call ODBC functions on the handle, but doesn't care if the connection
86 /// is in the right state.
87 ///
88 /// You should not have a need to call this method if your use case is covered by this library,
89 /// but, in case it is not, this may help you to break out of the type structure which might be
90 /// to rigid for you, while simultaneously abondoning its safeguards.
91 pub fn into_handle(self) -> handles::Connection<'c> {
92 // We do not want the compiler to invoke `Drop`, since drop would disconnect, yet we want to
93 // transfer ownership to the connection handle.
94 let dont_drop_me = MaybeUninit::new(self);
95 let self_ptr = dont_drop_me.as_ptr();
96
97 // Safety: We know `dont_drop_me` is (still) valid at this point so reading the ptr is okay
98 unsafe { ptr::read(&(*self_ptr).connection) }
99 }
100
101 /// Executes an SQL statement. This is the fastest way to submit an SQL statement for one-time
102 /// execution. In case you do **not** want to execute more statements on this connection, you
103 /// may want to use [`Self::into_cursor`] instead, which would create a cursor taking ownership
104 /// of the connection.
105 ///
106 /// # Parameters
107 ///
108 /// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;".
109 /// * `params`: `?` may be used as a placeholder in the statement text. You can use `()` to
110 /// represent no parameters. See the [`crate::parameter`] module level documentation for more
111 /// information on how to pass parameters.
112 /// * `query_timeout_sec`: Use this to limit the time the query is allowed to take, before
113 /// responding with data to the application. The driver may replace the number of seconds you
114 /// provide with a minimum or maximum value.
115 ///
116 /// For the timeout to work the driver must support this feature. E.g. PostgreSQL, and
117 /// Microsoft SQL Server do, but SQLite or MariaDB do not.
118 ///
119 /// You can specify ``0``, to deactivate the timeout, this is the default. So if you want no
120 /// timeout, just leave it at `None`. Only reason to specify ``0`` is if for some reason your
121 /// datasource does not have ``0`` as default.
122 ///
123 /// This corresponds to `SQL_ATTR_QUERY_TIMEOUT` in the ODBC C API.
124 ///
125 /// See: <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetstmtattr-function>
126 ///
127 /// # Return
128 ///
129 /// Returns `Some` if a cursor is created. If `None` is returned no cursor has been created (
130 /// e.g. the query came back empty). Note that an empty query may also create a cursor with zero
131 /// rows.
132 ///
133 /// # Example
134 ///
135 /// ```no_run
136 /// use odbc_api::{Environment, ConnectionOptions};
137 ///
138 /// let env = Environment::new()?;
139 ///
140 /// let mut conn = env.connect(
141 /// "YourDatabase", "SA", "My@Test@Password1",
142 /// ConnectionOptions::default()
143 /// )?;
144 /// // This query does not use any parameters.
145 /// let query_params = ();
146 /// let timeout_sec = None;
147 /// if let Some(cursor) = conn.execute(
148 /// "SELECT year, name FROM Birthdays;",
149 /// query_params,
150 /// timeout_sec)?
151 /// {
152 /// // Use cursor to process query results.
153 /// }
154 /// # Ok::<(), odbc_api::Error>(())
155 /// ```
156 pub fn execute(
157 &self,
158 query: &str,
159 params: impl ParameterCollectionRef,
160 query_timeout_sec: Option<usize>,
161 ) -> Result<Option<CursorImpl<StatementImpl<'_>>>, Error> {
162 // Only allocate the statement, if we know we are going to execute something.
163 if params.parameter_set_size() == 0 {
164 return Ok(None);
165 }
166 let mut statement = self.preallocate()?;
167 if let Some(seconds) = query_timeout_sec {
168 statement.set_query_timeout_sec(seconds)?;
169 }
170 statement.into_cursor(query, params)
171 }
172
173 /// Executes an SQL statement asynchronously using polling mode. ⚠️**Attention**⚠️: Please read
174 /// [Asynchronous execution using polling
175 /// mode](crate::guide#asynchronous-execution-using-polling-mode) before using this
176 /// 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 let stmt = self.preallocate()?;
559 stmt.into_columns_cursor(catalog_name, schema_name, table_name, column_name)
560 }
561
562 /// List tables, schemas, views and catalogs of a datasource.
563 ///
564 /// # Parameters
565 ///
566 /// * `catalog_name`: Filter result by catalog name. Accept search patterns. Use `%` to match
567 /// any number of characters. Use `_` to match exactly on character. Use `\` to escape
568 /// characeters.
569 /// * `schema_name`: Filter result by schema. Accepts patterns in the same way as
570 /// `catalog_name`.
571 /// * `table_name`: Filter result by table. Accepts patterns in the same way as `catalog_name`.
572 /// * `table_type`: Filters results by table type. E.g: 'TABLE', 'VIEW'. This argument accepts a
573 /// comma separeted list of table types. Omit it to not filter the result by table type at
574 /// all.
575 ///
576 /// # Example
577 ///
578 /// ```
579 /// use odbc_api::{Connection, Cursor, Error, ResultSetMetadata, buffers::TextRowSet};
580 ///
581 /// fn print_all_tables(conn: &Connection<'_>) -> Result<(), Error> {
582 /// // Set all filters to an empty string, to really print all tables
583 /// let mut cursor = conn.tables("", "", "", "")?;
584 ///
585 /// // The column are gonna be TABLE_CAT,TABLE_SCHEM,TABLE_NAME,TABLE_TYPE,REMARKS, but may
586 /// // also contain additional driver specific columns.
587 /// for (index, name) in cursor.column_names()?.enumerate() {
588 /// if index != 0 {
589 /// print!(",")
590 /// }
591 /// print!("{}", name?);
592 /// }
593 ///
594 /// let batch_size = 100;
595 /// let mut buffer = TextRowSet::for_cursor(batch_size, &mut cursor, Some(4096))?;
596 /// let mut row_set_cursor = cursor.bind_buffer(&mut buffer)?;
597 ///
598 /// while let Some(row_set) = row_set_cursor.fetch()? {
599 /// for row_index in 0..row_set.num_rows() {
600 /// if row_index != 0 {
601 /// print!("\n");
602 /// }
603 /// for col_index in 0..row_set.num_cols() {
604 /// if col_index != 0 {
605 /// print!(",");
606 /// }
607 /// let value = row_set
608 /// .at_as_str(col_index, row_index)
609 /// .unwrap()
610 /// .unwrap_or("NULL");
611 /// print!("{}", value);
612 /// }
613 /// }
614 /// }
615 ///
616 /// Ok(())
617 /// }
618 /// ```
619 pub fn tables(
620 &self,
621 catalog_name: &str,
622 schema_name: &str,
623 table_name: &str,
624 table_type: &str,
625 ) -> Result<CursorImpl<StatementImpl<'_>>, Error> {
626 let statement = self.preallocate()?;
627 statement.into_tables_cursor(catalog_name, schema_name, table_name, table_type)
628 }
629
630 /// Create a result set which contains the column names that make up the primary key for the
631 /// table.
632 ///
633 /// # Parameters
634 ///
635 /// * `catalog_name`: Catalog name. If a driver supports catalogs for some tables but not for
636 /// others, such as when the driver retrieves data from different DBMSs, an empty string ("")
637 /// denotes those tables that do not have catalogs. `catalog_name` must not contain a string
638 /// search pattern.
639 /// * `schema_name`: Schema name. If a driver supports schemas for some tables but not for
640 /// others, such as when the driver retrieves data from different DBMSs, an empty string ("")
641 /// denotes those tables that do not have schemas. `schema_name` must not contain a string
642 /// search pattern.
643 /// * `table_name`: Table name. `table_name` must not contain a string search pattern.
644 ///
645 /// The resulting result set contains the following columns:
646 ///
647 /// * `TABLE_CAT`: Primary key table catalog name. NULL if not applicable to the data source. If
648 /// a driver supports catalogs for some tables but not for others, such as when the driver
649 /// retrieves data from different DBMSs, it returns an empty string ("") for those tables that
650 /// do not have catalogs. `VARCHAR`
651 /// * `TABLE_SCHEM`: Primary key table schema name; NULL if not applicable to the data source.
652 /// If a driver supports schemas for some tables but not for others, such as when the driver
653 /// retrieves data from different DBMSs, it returns an empty string ("") for those tables that
654 /// do not have schemas. `VARCHAR`
655 /// * `TABLE_NAME`: Primary key table name. `VARCHAR NOT NULL`
656 /// * `COLUMN_NAME`: Primary key column name. The driver returns an empty string for a column
657 /// that does not have a name. `VARCHAR NOT NULL`
658 /// * `KEY_SEQ`: Column sequence number in key (starting with 1). `SMALLINT NOT NULL`
659 /// * `PK_NAME`: Primary key name. NULL if not applicable to the data source. `VARCHAR`
660 ///
661 /// The maximum length of the VARCHAR columns is driver specific.
662 ///
663 /// If [`crate::sys::StatementAttribute::MetadataId`] statement attribute is set to true,
664 /// catalog, schema and table name parameters are treated as an identifiers and their case is
665 /// not significant. If it is false, they are ordinary arguments. As such they treated literally
666 /// and their case is significant.
667 ///
668 /// See: <https://learn.microsoft.com/sql/odbc/reference/syntax/sqlprimarykeys-function>
669 pub fn primary_keys(
670 &self,
671 catalog_name: Option<&str>,
672 schema_name: Option<&str>,
673 table_name: &str,
674 ) -> Result<BlockCursorIterator<CursorImpl<StatementImpl<'_>>, PrimaryKeysRow>, Error> {
675 let stmt = self.preallocate()?;
676 stmt.into_primary_keys(catalog_name, schema_name, table_name)
677 }
678
679 /// This can be used to retrieve either a list of foreign keys in the specified table or a list
680 /// of foreign keys in other table that refer to the primary key of the specified table.
681 ///
682 /// See: <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlforeignkeys-function>
683 pub fn foreign_keys(
684 &self,
685 pk_catalog_name: &str,
686 pk_schema_name: &str,
687 pk_table_name: &str,
688 fk_catalog_name: &str,
689 fk_schema_name: &str,
690 fk_table_name: &str,
691 ) -> Result<CursorImpl<StatementImpl<'_>>, Error> {
692 let statement = self.preallocate()?;
693 statement.into_foreign_keys_cursor(
694 pk_catalog_name,
695 pk_schema_name,
696 pk_table_name,
697 fk_catalog_name,
698 fk_schema_name,
699 fk_table_name,
700 )
701 }
702
703 /// The buffer descriptions for all standard buffers (not including extensions) returned in the
704 /// columns query (e.g. [`Connection::columns`]).
705 ///
706 /// # Arguments
707 ///
708 /// * `type_name_max_len` - The maximum expected length of type names.
709 /// * `remarks_max_len` - The maximum expected length of remarks.
710 /// * `column_default_max_len` - The maximum expected length of column defaults.
711 pub fn columns_buffer_descs(
712 &self,
713 type_name_max_len: usize,
714 remarks_max_len: usize,
715 column_default_max_len: usize,
716 ) -> Result<Vec<BufferDesc>, Error> {
717 let null_i16 = BufferDesc::I16 { nullable: true };
718
719 let not_null_i16 = BufferDesc::I16 { nullable: false };
720
721 let null_i32 = BufferDesc::I32 { nullable: true };
722
723 // The definitions for these descriptions are taken from the documentation of `SQLColumns`
724 // located at https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlcolumns-function
725 let catalog_name_desc = BufferDesc::Text {
726 max_str_len: self.max_catalog_name_len()? as usize,
727 };
728
729 let schema_name_desc = BufferDesc::Text {
730 max_str_len: self.max_schema_name_len()? as usize,
731 };
732
733 let table_name_desc = BufferDesc::Text {
734 max_str_len: self.max_table_name_len()? as usize,
735 };
736
737 let column_name_desc = BufferDesc::Text {
738 max_str_len: self.max_column_name_len()? as usize,
739 };
740
741 let data_type_desc = not_null_i16;
742
743 let type_name_desc = BufferDesc::Text {
744 max_str_len: type_name_max_len,
745 };
746
747 let column_size_desc = null_i32;
748 let buffer_len_desc = null_i32;
749 let decimal_digits_desc = null_i16;
750 let precision_radix_desc = null_i16;
751 let nullable_desc = not_null_i16;
752
753 let remarks_desc = BufferDesc::Text {
754 max_str_len: remarks_max_len,
755 };
756
757 let column_default_desc = BufferDesc::Text {
758 max_str_len: column_default_max_len,
759 };
760
761 let sql_data_type_desc = not_null_i16;
762 let sql_datetime_sub_desc = null_i16;
763 let char_octet_len_desc = null_i32;
764 let ordinal_pos_desc = BufferDesc::I32 { nullable: false };
765
766 // We expect strings to be `YES`, `NO`, or a zero-length string, so `3` should be
767 // sufficient.
768 const IS_NULLABLE_LEN_MAX_LEN: usize = 3;
769 let is_nullable_desc = BufferDesc::Text {
770 max_str_len: IS_NULLABLE_LEN_MAX_LEN,
771 };
772
773 Ok(vec![
774 catalog_name_desc,
775 schema_name_desc,
776 table_name_desc,
777 column_name_desc,
778 data_type_desc,
779 type_name_desc,
780 column_size_desc,
781 buffer_len_desc,
782 decimal_digits_desc,
783 precision_radix_desc,
784 nullable_desc,
785 remarks_desc,
786 column_default_desc,
787 sql_data_type_desc,
788 sql_datetime_sub_desc,
789 char_octet_len_desc,
790 ordinal_pos_desc,
791 is_nullable_desc,
792 ])
793 }
794
795 fn allocate_statement(&self) -> Result<StatementImpl<'_>, Error> {
796 self.connection
797 .allocate_statement()
798 .into_result(&self.connection)
799 }
800}
801
802/// Implement `Debug` for [`Connection`], in order to play nice with derive Debugs for struct
803/// holding a [`Connection`].
804impl Debug for Connection<'_> {
805 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
806 write!(f, "Connection")
807 }
808}
809
810/// We need to implement [`StatementParent`] for [`Connection`] in order to express ownership of a
811/// connection for a statement handle. This is e.g. needed for [`Connection::into_cursor`].
812///
813/// # Safety:
814///
815/// Connection wraps an open Connection. It keeps the handle alive and valid during its lifetime.
816unsafe impl StatementParent for Connection<'_> {}
817
818/// We need to implement [`StatementParent`] for `Arc<Connection>` in order to be able to express
819/// ownership of a shared connection from a statement handle. This is e.g. needed for
820/// [`ConnectionTransitions::into_cursor`].
821///
822/// # Safety:
823///
824/// `Arc<Connection>` wraps an open Connection. It keeps the handle alive and valid during its
825/// lifetime.
826unsafe impl StatementParent for Arc<Connection<'_>> {}
827
828/// Options to be passed then opening a connection to a datasource.
829#[derive(Default, Clone, Copy)]
830pub struct ConnectionOptions {
831 /// Number of seconds to wait for a login request to complete before returning to the
832 /// application. The default is driver-dependent. If `0` the timeout is disabled and a
833 /// connection attempt will wait indefinitely.
834 ///
835 /// If the specified timeout exceeds the maximum login timeout in the data source, the driver
836 /// substitutes that value and uses the maximum login timeout instead.
837 ///
838 /// This corresponds to the `SQL_ATTR_LOGIN_TIMEOUT` attribute in the ODBC specification.
839 ///
840 /// See:
841 /// <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetconnectattr-function>
842 pub login_timeout_sec: Option<u32>,
843 /// Packet size in bytes. Not all drivers support this option.
844 pub packet_size: Option<u32>,
845}
846
847impl ConnectionOptions {
848 /// Set the attributes corresponding to the connection options to an allocated connection
849 /// handle. Usually you would rather provide the options then creating the connection with e.g.
850 /// [`crate::Environment::connect_with_connection_string`] rather than calling this method
851 /// yourself.
852 pub fn apply(&self, handle: &handles::Connection) -> Result<(), Error> {
853 if let Some(timeout) = self.login_timeout_sec {
854 handle.set_login_timeout_sec(timeout).into_result(handle)?;
855 }
856 if let Some(packet_size) = self.packet_size {
857 handle.set_packet_size(packet_size).into_result(handle)?;
858 }
859 Ok(())
860 }
861}
862
863/// You can use this method to escape a password so it is suitable to be appended to an ODBC
864/// connection string as the value for the `PWD` attribute. This method is only of interest for
865/// application in need to create their own connection strings.
866///
867/// See:
868///
869/// * <https://stackoverflow.com/questions/22398212/escape-semicolon-in-odbc-connection-string-in-app-config-file>
870/// * <https://docs.microsoft.com/en-us/dotnet/api/system.data.odbc.odbcconnection.connectionstring>
871///
872/// # Example
873///
874/// ```
875/// use odbc_api::escape_attribute_value;
876///
877/// let password = "abc;123}";
878/// let user = "SA";
879/// let mut connection_string_without_credentials =
880/// "Driver={ODBC Driver 18 for SQL Server};Server=localhost;";
881///
882/// let connection_string = format!(
883/// "{}UID={};PWD={};",
884/// connection_string_without_credentials,
885/// user,
886/// escape_attribute_value(password)
887/// );
888///
889/// assert_eq!(
890/// "Driver={ODBC Driver 18 for SQL Server};Server=localhost;UID=SA;PWD={abc;123}}};",
891/// connection_string
892/// );
893/// ```
894///
895/// ```
896/// use odbc_api::escape_attribute_value;
897/// assert_eq!("abc", escape_attribute_value("abc"));
898/// assert_eq!("ab}c", escape_attribute_value("ab}c"));
899/// assert_eq!("{ab;c}", escape_attribute_value("ab;c"));
900/// assert_eq!("{a}}b;c}", escape_attribute_value("a}b;c"));
901/// assert_eq!("{ab+c}", escape_attribute_value("ab+c"));
902/// ```
903pub fn escape_attribute_value(unescaped: &str) -> Cow<'_, str> {
904 // Search the string for semicolon (';') if we do not find any, nothing is to do and we can work
905 // without an extra allocation.
906 //
907 // * We escape ';' because it serves as a separator between key=value pairs
908 // * We escape '+' because passwords with `+` must be escaped on PostgreSQL for some reason.
909 if unescaped.contains(&[';', '+'][..]) {
910 // Surround the string with curly braces ('{','}') and escape every closing curly brace by
911 // repeating it.
912 let escaped = unescaped.replace('}', "}}");
913 Cow::Owned(format!("{{{escaped}}}"))
914 } else {
915 Cow::Borrowed(unescaped)
916 }
917}
918
919/// A pair of the error and the previous state, before the operation caused the error.
920///
921/// Some functions in this crate take a `self` and return another type in the result to express a
922/// state transitions in the underlying ODBC handle. In order to make such operations retryable, or
923/// offer other alternatives of recovery, they may return this error type instead of a plain
924/// [`Error`].
925#[derive(Debug)]
926pub struct FailedStateTransition<S> {
927 /// The ODBC error which caused the state transition to fail.
928 pub error: Error,
929 /// The state before the transition failed. This is useful to e.g. retry the operation, or
930 /// recover in another way.
931 pub previous: S,
932}
933
934impl<S> From<FailedStateTransition<S>> for Error {
935 fn from(value: FailedStateTransition<S>) -> Self {
936 value.error
937 }
938}
939
940impl<S> Display for FailedStateTransition<S> {
941 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942 write!(f, "{}", self.error)
943 }
944}
945
946impl<S> std::error::Error for FailedStateTransition<S>
947where
948 S: Debug,
949{
950 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
951 self.error.source()
952 }
953}
954
955/// An error type wrapping an [`Error`] and a [`Connection`]. It is used by
956/// [`Connection::into_cursor`], so that in case of failure the user can reuse the connection to try
957/// again. [`Connection::into_cursor`] could achieve the same by returning a tuple in case of an
958/// error, but this type causes less friction in most scenarios because [`Error`] implements
959/// [`From`] [`ConnectionAndError`] and it therfore works with the question mark operater (`?`).
960type ConnectionAndError<'conn> = FailedStateTransition<Connection<'conn>>;
961
962/// Ability to transition ownership of the connection to various children which represent statement
963/// handles in various states. E.g. [`crate::Prepared`] or [`crate::Cursor`]. Transfering ownership
964/// of the connection could e.g. be useful if you want to clean the connection after you are done
965/// with the child.
966///
967/// Having this in a trait rather than directly on [`Connection`] allows us to be generic over the
968/// type of ownership we express. E.g. we can express shared ownership of a connection by
969/// using an `Arc<Mutex<Connection>>` or `Arc<Connection>`. Or a still exclusive ownership using
970/// a plain [`Connection`].
971pub trait ConnectionTransitions: Sized {
972 // Note to self. This might eveolve into a `Connection` trait. Which expresses ownership
973 // of a connection (shared or not). It could allow to get a dereferened borrowed conection
974 // which does not allow for state transtions as of now (like StatementRef). I may not want to
975 // rock the boat that much right now.
976
977 /// The type passed to [crate::handles::StatementConnection] to express ownership of the
978 /// connection.
979 type StatementParent: StatementParent;
980
981 /// Similar to [`crate::Connection::into_cursor`], yet it operates on an
982 /// `Arc<Mutex<Connection>>`. `Arc<Connection>` can be used if you want shared ownership of
983 /// connections. However, `Arc<Connection>` is not `Send` due to `Connection` not being `Sync`.
984 /// So sometimes you may want to wrap your `Connection` into an `Arc<Mutex<Connection>>` to
985 /// allow shared ownership of the connection across threads. This function allows you to create
986 /// a cursor from such a shared which also holds a strong reference to it.
987 ///
988 /// # Parameters
989 ///
990 /// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;".
991 /// * `params`: `?` may be used as a placeholder in the statement text. You can use `()` to
992 /// represent no parameters. See the [`crate::parameter`] module level documentation for more
993 /// information on how to pass parameters.
994 /// * `query_timeout_sec`: Use this to limit the time the query is allowed to take, before
995 /// responding with data to the application. The driver may replace the number of seconds you
996 /// provide with a minimum or maximum value.
997 ///
998 /// For the timeout to work the driver must support this feature. E.g. PostgreSQL, and
999 /// Microsoft SQL Server do, but SQLite or MariaDB do not.
1000 ///
1001 /// You can specify ``0``, to deactivate the timeout, this is the default. So if you want no
1002 /// timeout, just leave it at `None`. Only reason to specify ``0`` is if for some reason your
1003 /// datasource does not have ``0`` as default.
1004 ///
1005 /// This corresponds to `SQL_ATTR_QUERY_TIMEOUT` in the ODBC C API.
1006 ///
1007 /// See: <https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetstmtattr-function>
1008 fn into_cursor(
1009 self,
1010 query: &str,
1011 params: impl ParameterCollectionRef,
1012 query_timeout_sec: Option<usize>,
1013 ) -> Result<
1014 Option<CursorImpl<StatementConnection<Self::StatementParent>>>,
1015 FailedStateTransition<Self>,
1016 >;
1017
1018 /// Prepares an SQL statement which takes ownership of the connection. The advantage over
1019 /// [`Connection::prepare`] is, that you do not need to keep track of the lifetime of the
1020 /// connection seperatly and can create types which do own the prepared query and only depend on
1021 /// the lifetime of the environment.
1022 ///
1023 /// # Parameters
1024 ///
1025 /// * `query`: The text representation of the SQL statement. E.g. "SELECT * FROM my_table;". `?`
1026 /// may be used as a placeholder in the statement text, to be replaced with parameters during
1027 /// execution.
1028 ///
1029 /// ```no_run
1030 /// use odbc_api::{
1031 /// environment, Error, ColumnarBulkInserter, ConnectionTransitions, Connection,
1032 /// handles::StatementConnection, buffers::{BufferDesc, AnyBuffer}, ConnectionOptions,
1033 /// };
1034 ///
1035 /// const CONNECTION_STRING: &str =
1036 /// "Driver={ODBC Driver 18 for SQL Server};\
1037 /// Server=localhost;UID=SA;\
1038 /// PWD=My@Test@Password1;";
1039 ///
1040 /// /// Supports columnar bulk inserts on a heterogenous schema (columns have different types),
1041 /// /// takes ownership of a connection created using an environment with static lifetime.
1042 /// type Inserter = ColumnarBulkInserter<StatementConnection<Connection<'static>>, AnyBuffer>;
1043 ///
1044 /// /// Creates an inserter which can be reused to bulk insert birthyears with static lifetime.
1045 /// fn make_inserter(query: &str) -> Result<Inserter, Error> {
1046 /// let env = environment()?;
1047 /// let conn = env.connect_with_connection_string(
1048 /// CONNECTION_STRING,
1049 /// ConnectionOptions::default()
1050 /// )?;
1051 /// let prepared = conn.into_prepared("INSERT INTO Birthyear (name, year) VALUES (?, ?)")?;
1052 /// let buffers = [
1053 /// BufferDesc::Text { max_str_len: 255},
1054 /// BufferDesc::I16 { nullable: false },
1055 /// ];
1056 /// let capacity = 400;
1057 /// prepared.into_column_inserter(capacity, buffers)
1058 /// }
1059 /// ```
1060 fn into_prepared(
1061 self,
1062 query: &str,
1063 ) -> Result<Prepared<StatementConnection<Self::StatementParent>>, Error>;
1064
1065 /// Creates a preallocated statement handle like [`Connection::preallocate`]. Yet the statement
1066 /// also takes ownership of the connection.
1067 fn into_preallocated(
1068 self,
1069 ) -> Result<Preallocated<StatementConnection<Self::StatementParent>>, Error>;
1070}
1071
1072impl<'env> ConnectionTransitions for Connection<'env> {
1073 type StatementParent = Self;
1074
1075 fn into_cursor(
1076 self,
1077 query: &str,
1078 params: impl ParameterCollectionRef,
1079 query_timeout_sec: Option<usize>,
1080 ) -> Result<Option<CursorImpl<StatementConnection<Self>>>, FailedStateTransition<Self>> {
1081 self.into_cursor(query, params, query_timeout_sec)
1082 }
1083
1084 fn into_prepared(self, query: &str) -> Result<Prepared<StatementConnection<Self>>, Error> {
1085 self.into_prepared(query)
1086 }
1087
1088 fn into_preallocated(self) -> Result<Preallocated<StatementConnection<Self>>, Error> {
1089 self.into_preallocated()
1090 }
1091}
1092
1093impl<'env> ConnectionTransitions for Arc<Connection<'env>> {
1094 type StatementParent = Self;
1095
1096 fn into_cursor(
1097 self,
1098 query: &str,
1099 params: impl ParameterCollectionRef,
1100 query_timeout_sec: Option<usize>,
1101 ) -> Result<Option<CursorImpl<StatementConnection<Self>>>, FailedStateTransition<Self>> {
1102 // Result borrows the connection. We convert the cursor into a raw pointer, to not confuse
1103 // the borrow checker.
1104 let result = self.execute(query, params, query_timeout_sec);
1105 let maybe_stmt_ptr = result
1106 .map(|opt| opt.map(|cursor| cursor.into_stmt().into_sys()))
1107 .map_err(|error| {
1108 // If the execute fails, we return a FailedStateTransition with the error and the
1109 // connection.
1110 FailedStateTransition {
1111 error,
1112 previous: Arc::clone(&self),
1113 }
1114 })?;
1115 let Some(stmt_ptr) = maybe_stmt_ptr else {
1116 return Ok(None);
1117 };
1118 // Safe: The connection is the parent of the statement referenced by `stmt_ptr`.
1119 let stmt = unsafe { StatementConnection::new(stmt_ptr, self) };
1120 // Safe: `stmt` is valid and in cursor state.
1121 let cursor = unsafe { CursorImpl::new(stmt) };
1122 Ok(Some(cursor))
1123 }
1124
1125 fn into_prepared(self, query: &str) -> Result<Prepared<StatementConnection<Self>>, Error> {
1126 let stmt = self.prepare(query)?;
1127 let stmt_ptr = stmt.into_handle().into_sys();
1128 // Safe: The connection is the parent of the statement referenced by `stmt_ptr`.
1129 let stmt = unsafe { StatementConnection::new(stmt_ptr, self) };
1130 // `stmt` is valid and in prepared state.
1131 let prepared = Prepared::new(stmt);
1132 Ok(prepared)
1133 }
1134
1135 fn into_preallocated(self) -> Result<Preallocated<StatementConnection<Self>>, Error> {
1136 let stmt = self.preallocate()?;
1137 let stmt_ptr = stmt.into_handle().into_sys();
1138 // Safe: The connection is the parent of the statement referenced by `stmt_ptr`.
1139 let stmt = unsafe { StatementConnection::new(stmt_ptr, self) };
1140 // Safe: `stmt` is valid and its state is allocated.
1141 let preallocated = unsafe { Preallocated::new(stmt) };
1142 Ok(preallocated)
1143 }
1144}