sqlx_core_oldapi/odbc/connection/
mod.rs

1use crate::connection::Connection;
2use crate::error::Error;
3use crate::odbc::{
4    Odbc, OdbcArguments, OdbcColumn, OdbcConnectOptions, OdbcQueryResult, OdbcRow, OdbcTypeInfo,
5};
6use crate::transaction::Transaction;
7use either::Either;
8use sqlx_rt::spawn_blocking;
9mod odbc_bridge;
10use crate::odbc::{OdbcStatement, OdbcStatementMetadata};
11use futures_core::future::BoxFuture;
12use futures_util::future;
13use odbc_api::ConnectionTransitions;
14use odbc_api::{handles::StatementConnection, Prepared, ResultSetMetadata, SharedConnection};
15use odbc_bridge::{establish_connection, execute_sql};
16use std::borrow::Cow;
17use std::collections::HashMap;
18use std::sync::{Arc, Mutex};
19
20mod executor;
21
22type PreparedStatement = Prepared<StatementConnection<SharedConnection<'static>>>;
23type SharedPreparedStatement = Arc<Mutex<PreparedStatement>>;
24
25fn collect_columns(prepared: &mut PreparedStatement) -> Vec<OdbcColumn> {
26    let count = prepared.num_result_cols().unwrap_or(0);
27    (1..=count)
28        .map(|i| create_column(prepared, i as u16))
29        .collect()
30}
31
32fn create_column(stmt: &mut PreparedStatement, index: u16) -> OdbcColumn {
33    let mut cd = odbc_api::ColumnDescription::default();
34    let _ = stmt.describe_col(index, &mut cd);
35
36    OdbcColumn {
37        name: decode_column_name(cd.name, index),
38        type_info: OdbcTypeInfo::new(cd.data_type),
39        ordinal: usize::from(index.checked_sub(1).unwrap()),
40    }
41}
42
43fn decode_column_name(name_bytes: Vec<u8>, index: u16) -> String {
44    String::from_utf8(name_bytes).unwrap_or_else(|_| format!("col{}", index - 1))
45}
46
47/// A connection to an ODBC-accessible database.
48///
49/// ODBC uses a blocking C API, so we offload blocking calls to the runtime's blocking
50/// thread-pool via `spawn_blocking` and synchronize access with a mutex.
51pub struct OdbcConnection {
52    pub(crate) conn: SharedConnection<'static>,
53    pub(crate) stmt_cache: HashMap<Arc<str>, SharedPreparedStatement>,
54}
55
56impl std::fmt::Debug for OdbcConnection {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("OdbcConnection")
59            .field("conn", &self.conn)
60            .finish()
61    }
62}
63
64impl OdbcConnection {
65    pub(crate) async fn with_conn<R, F, S>(&mut self, operation: S, f: F) -> Result<R, Error>
66    where
67        R: Send + 'static,
68        F: FnOnce(&mut odbc_api::Connection<'static>) -> Result<R, Error> + Send + 'static,
69        S: std::fmt::Display + Send + 'static,
70    {
71        let conn = Arc::clone(&self.conn);
72        spawn_blocking(move || {
73            let mut conn_guard = conn.lock().map_err(|_| {
74                Error::Protocol(format!("ODBC {}: failed to lock connection", operation))
75            })?;
76            f(&mut conn_guard)
77        })
78        .await
79    }
80
81    pub(crate) async fn establish(options: &OdbcConnectOptions) -> Result<Self, Error> {
82        let shared_conn = spawn_blocking({
83            let options = options.clone();
84            move || {
85                let conn = establish_connection(&options)?;
86                let shared_conn = odbc_api::SharedConnection::new(std::sync::Mutex::new(conn));
87                Ok::<_, Error>(shared_conn)
88            }
89        })
90        .await?;
91
92        Ok(Self {
93            conn: shared_conn,
94            stmt_cache: HashMap::new(),
95        })
96    }
97
98    /// Returns the name of the actual Database Management System (DBMS) this
99    /// connection is talking to as reported by the ODBC driver.
100    pub async fn dbms_name(&mut self) -> Result<String, Error> {
101        self.with_conn("dbms_name", move |conn| {
102            Ok(conn.database_management_system_name()?)
103        })
104        .await
105    }
106
107    pub(crate) async fn ping_blocking(&mut self) -> Result<(), Error> {
108        self.with_conn("ping", move |conn| {
109            conn.execute("SELECT 1", (), None)?;
110            Ok(())
111        })
112        .await
113    }
114
115    pub(crate) async fn begin_blocking(&mut self) -> Result<(), Error> {
116        self.with_conn("begin", move |conn| {
117            conn.set_autocommit(false)?;
118            Ok(())
119        })
120        .await
121    }
122
123    pub(crate) async fn commit_blocking(&mut self) -> Result<(), Error> {
124        self.with_conn("commit", move |conn| {
125            conn.commit()?;
126            conn.set_autocommit(true)?;
127            Ok(())
128        })
129        .await
130    }
131
132    pub(crate) async fn rollback_blocking(&mut self) -> Result<(), Error> {
133        self.with_conn("rollback", move |conn| {
134            conn.rollback()?;
135            conn.set_autocommit(true)?;
136            Ok(())
137        })
138        .await
139    }
140
141    /// Launches a background task to execute the SQL statement and send the results to the returned channel.
142    pub(crate) fn execute_stream(
143        &mut self,
144        sql: &str,
145        args: Option<OdbcArguments>,
146    ) -> flume::Receiver<Result<Either<OdbcQueryResult, OdbcRow>, Error>> {
147        let (tx, rx) = flume::bounded(64);
148
149        let maybe_prepared = if let Some(prepared) = self.stmt_cache.get(sql) {
150            MaybePrepared::Prepared(Arc::clone(prepared))
151        } else {
152            MaybePrepared::NotPrepared(sql.to_string())
153        };
154
155        let conn = Arc::clone(&self.conn);
156        sqlx_rt::spawn(sqlx_rt::spawn_blocking(move || {
157            let mut conn = conn.lock().expect("failed to lock connection");
158            if let Err(e) = execute_sql(&mut conn, maybe_prepared, args, &tx) {
159                let _ = tx.send(Err(e));
160            }
161        }));
162
163        rx
164    }
165
166    pub(crate) async fn clear_cached_statements(&mut self) -> Result<(), Error> {
167        // Clear the statement metadata cache
168        self.stmt_cache.clear();
169        Ok(())
170    }
171
172    pub async fn prepare<'a>(&mut self, sql: &'a str) -> Result<OdbcStatement<'a>, Error> {
173        let conn = Arc::clone(&self.conn);
174        let sql_arc = Arc::from(sql.to_string());
175        let sql_clone = Arc::clone(&sql_arc);
176        let (prepared, metadata) = spawn_blocking(move || {
177            let mut prepared = conn.into_prepared(&sql_clone)?;
178            let metadata = OdbcStatementMetadata {
179                columns: collect_columns(&mut prepared),
180                parameters: usize::from(prepared.num_params().unwrap_or(0)),
181            };
182            Ok::<_, Error>((prepared, metadata))
183        })
184        .await?;
185        self.stmt_cache
186            .insert(Arc::clone(&sql_arc), Arc::new(Mutex::new(prepared)));
187        Ok(OdbcStatement {
188            sql: Cow::Borrowed(sql),
189            metadata,
190        })
191    }
192}
193
194pub(crate) enum MaybePrepared {
195    Prepared(SharedPreparedStatement),
196    NotPrepared(String),
197}
198
199impl Connection for OdbcConnection {
200    type Database = Odbc;
201
202    type Options = OdbcConnectOptions;
203
204    fn close(self) -> BoxFuture<'static, Result<(), Error>> {
205        Box::pin(async move {
206            // Drop connection by moving Arc and letting it fall out of scope.
207            drop(self);
208            Ok(())
209        })
210    }
211
212    fn close_hard(self) -> BoxFuture<'static, Result<(), Error>> {
213        Box::pin(async move { Ok(()) })
214    }
215
216    fn ping(&mut self) -> BoxFuture<'_, Result<(), Error>> {
217        Box::pin(self.ping_blocking())
218    }
219
220    fn begin(&mut self) -> BoxFuture<'_, Result<Transaction<'_, Self::Database>, Error>>
221    where
222        Self: Sized,
223    {
224        Transaction::begin(self)
225    }
226
227    #[doc(hidden)]
228    fn flush(&mut self) -> BoxFuture<'_, Result<(), Error>> {
229        Box::pin(future::ok(()))
230    }
231
232    #[doc(hidden)]
233    fn should_flush(&self) -> bool {
234        false
235    }
236
237    fn clear_cached_statements(&mut self) -> BoxFuture<'_, Result<(), Error>> {
238        Box::pin(self.clear_cached_statements())
239    }
240}
241
242// moved helpers to connection/inner.rs