Skip to main content

sqlx_odbc/
any.rs

1//! Runtime `Any` driver support for ODBC.
2
3use crate::{
4    connection::OdbcExecution, DataTypeExt, Odbc, OdbcArgumentValue, OdbcArguments, OdbcColumn,
5    OdbcConnectOptions, OdbcConnection, OdbcQueryResult, OdbcTransactionManager, OdbcTypeInfo,
6};
7use futures_core::future::BoxFuture;
8use futures_core::stream::BoxStream;
9use futures_util::{future, stream, FutureExt, StreamExt};
10use sqlx_core::any::driver::AnyDriver;
11use sqlx_core::any::{
12    AnyArguments, AnyColumn, AnyConnectOptions, AnyConnectionBackend, AnyQueryResult, AnyRow,
13    AnyStatement, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind,
14};
15use sqlx_core::column::Column;
16use sqlx_core::connection::{ConnectOptions, Connection};
17use sqlx_core::database::Database;
18use sqlx_core::ext::ustr::UStr;
19use sqlx_core::row::Row;
20use sqlx_core::sql_str::SqlStr;
21use sqlx_core::statement::Statement;
22use sqlx_core::transaction::TransactionManager;
23use sqlx_core::{Either, HashMap};
24use std::sync::Arc;
25
26/// Installable ODBC driver for SQLx `Any` connections.
27pub const DRIVER: AnyDriver = AnyDriver::without_migrate::<Odbc>();
28
29impl AnyConnectionBackend for OdbcConnection {
30    fn name(&self) -> &str {
31        <Odbc as Database>::NAME
32    }
33
34    fn close(self: Box<Self>) -> BoxFuture<'static, sqlx_core::Result<()>> {
35        Connection::close(*self).boxed()
36    }
37
38    fn close_hard(self: Box<Self>) -> BoxFuture<'static, sqlx_core::Result<()>> {
39        Connection::close_hard(*self).boxed()
40    }
41
42    fn ping(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> {
43        Connection::ping(self).boxed()
44    }
45
46    fn begin(&mut self, statement: Option<SqlStr>) -> BoxFuture<'_, sqlx_core::Result<()>> {
47        OdbcTransactionManager::begin(self, statement).boxed()
48    }
49
50    fn commit(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> {
51        OdbcTransactionManager::commit(self).boxed()
52    }
53
54    fn rollback(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> {
55        OdbcTransactionManager::rollback(self).boxed()
56    }
57
58    fn start_rollback(&mut self) {
59        OdbcTransactionManager::start_rollback(self);
60    }
61
62    fn get_transaction_depth(&self) -> usize {
63        OdbcTransactionManager::get_transaction_depth(self)
64    }
65
66    fn shrink_buffers(&mut self) {
67        Connection::shrink_buffers(self);
68    }
69
70    fn flush(&mut self) -> BoxFuture<'_, sqlx_core::Result<()>> {
71        Connection::flush(self).boxed()
72    }
73
74    fn should_flush(&self) -> bool {
75        Connection::should_flush(self)
76    }
77
78    fn fetch_many(
79        &mut self,
80        query: SqlStr,
81        _persistent: bool,
82        arguments: Option<AnyArguments>,
83    ) -> BoxStream<'_, sqlx_core::Result<Either<AnyQueryResult, AnyRow>>> {
84        let arguments = arguments.map(map_arguments);
85
86        stream::once(async move { self.run_blocking_sql(query.as_str(), arguments.as_ref()) })
87            .map(|result| match result {
88                Ok(OdbcExecution::Done(result)) => {
89                    stream::once(future::ready(Ok(Either::Left(map_result(result))))).boxed()
90                }
91                Ok(OdbcExecution::Rows(rows)) => stream::iter(rows.into_iter().map(|row| {
92                    let column_names = column_names(row.columns());
93                    AnyRow::map_from(&row, column_names).map(Either::Right)
94                }))
95                .boxed(),
96                Err(error) => stream::once(future::ready(Err(error))).boxed(),
97            })
98            .flatten()
99            .boxed()
100    }
101
102    fn fetch_optional(
103        &mut self,
104        query: SqlStr,
105        _persistent: bool,
106        arguments: Option<AnyArguments>,
107    ) -> BoxFuture<'_, sqlx_core::Result<Option<AnyRow>>> {
108        let arguments = arguments.map(map_arguments);
109
110        Box::pin(async move {
111            match self.run_blocking_sql(query.as_str(), arguments.as_ref())? {
112                OdbcExecution::Done(_) => Ok(None),
113                OdbcExecution::Rows(rows) => rows
114                    .into_iter()
115                    .next()
116                    .map(|row| {
117                        let column_names = column_names(row.columns());
118                        AnyRow::map_from(&row, column_names)
119                    })
120                    .transpose(),
121            }
122        })
123    }
124
125    fn prepare_with<'c, 'q: 'c>(
126        &'c mut self,
127        sql: SqlStr,
128        _parameters: &[AnyTypeInfo],
129    ) -> BoxFuture<'c, sqlx_core::Result<AnyStatement>> {
130        Box::pin(async move {
131            let statement = self.prepare_blocking(sql)?;
132            let column_names = column_names(statement.columns());
133            AnyStatement::try_from_statement(statement, column_names)
134        })
135    }
136}
137
138impl<'a> TryFrom<&'a AnyConnectOptions> for OdbcConnectOptions {
139    type Error = sqlx_core::Error;
140
141    fn try_from(options: &'a AnyConnectOptions) -> Result<Self, Self::Error> {
142        let mut options_out = OdbcConnectOptions::from_url(&options.database_url)?;
143        options_out.log_statements = options.log_settings.statements_level;
144        options_out.log_slow_statements = options.log_settings.slow_statements_level;
145        options_out.log_slow_statement_duration = options.log_settings.slow_statements_duration;
146        Ok(options_out)
147    }
148}
149
150impl<'a> TryFrom<&'a OdbcTypeInfo> for AnyTypeInfo {
151    type Error = sqlx_core::Error;
152
153    fn try_from(type_info: &'a OdbcTypeInfo) -> Result<Self, Self::Error> {
154        let kind = match type_info.data_type() {
155            odbc_api::DataType::Unknown => AnyTypeInfoKind::Null,
156            odbc_api::DataType::Bit => AnyTypeInfoKind::Bool,
157            odbc_api::DataType::TinyInt | odbc_api::DataType::SmallInt => AnyTypeInfoKind::SmallInt,
158            odbc_api::DataType::Integer => AnyTypeInfoKind::Integer,
159            odbc_api::DataType::BigInt => AnyTypeInfoKind::BigInt,
160            odbc_api::DataType::Real => AnyTypeInfoKind::Real,
161            odbc_api::DataType::Float { .. } | odbc_api::DataType::Double => {
162                AnyTypeInfoKind::Double
163            }
164            data_type if data_type.accepts_character_data() => AnyTypeInfoKind::Text,
165            data_type if data_type.accepts_binary_data() => AnyTypeInfoKind::Blob,
166            data_type => {
167                return Err(sqlx_core::Error::AnyDriverError(
168                    format!("Any driver does not support the ODBC type {data_type:?}").into(),
169                ));
170            }
171        };
172
173        Ok(AnyTypeInfo { kind })
174    }
175}
176
177impl<'a> TryFrom<&'a OdbcColumn> for AnyColumn {
178    type Error = sqlx_core::Error;
179
180    fn try_from(column: &'a OdbcColumn) -> Result<Self, Self::Error> {
181        let type_info = AnyTypeInfo::try_from(column.type_info()).map_err(|error| {
182            sqlx_core::Error::ColumnDecode {
183                index: column.name().to_owned(),
184                source: error.into(),
185            }
186        })?;
187
188        Ok(Self {
189            ordinal: column.ordinal(),
190            name: UStr::new(column.name()),
191            type_info,
192        })
193    }
194}
195
196fn map_arguments(arguments: AnyArguments) -> OdbcArguments {
197    let mut out = OdbcArguments::default();
198
199    for value in arguments.values.0 {
200        out.add_value(match value {
201            AnyValueKind::Null(kind) => OdbcArgumentValue::Null(any_type_to_odbc(kind)),
202            AnyValueKind::Bool(value) => OdbcArgumentValue::Bit(value),
203            AnyValueKind::SmallInt(value) => OdbcArgumentValue::Int(i64::from(value)),
204            AnyValueKind::Integer(value) => OdbcArgumentValue::Int(i64::from(value)),
205            AnyValueKind::BigInt(value) => OdbcArgumentValue::Int(value),
206            AnyValueKind::Real(value) => OdbcArgumentValue::Float(f64::from(value)),
207            AnyValueKind::Double(value) => OdbcArgumentValue::Float(value),
208            AnyValueKind::Text(value) => OdbcArgumentValue::Text(value.to_string()),
209            AnyValueKind::TextSlice(value) => OdbcArgumentValue::Text(value.to_string()),
210            AnyValueKind::Blob(value) => OdbcArgumentValue::Bytes(value.to_vec()),
211            _ => unreachable!("unhandled Any argument value"),
212        });
213    }
214
215    out
216}
217
218fn any_type_to_odbc(kind: AnyTypeInfoKind) -> OdbcTypeInfo {
219    OdbcTypeInfo::new(match kind {
220        AnyTypeInfoKind::Null => odbc_api::DataType::Unknown,
221        AnyTypeInfoKind::Bool => odbc_api::DataType::Bit,
222        AnyTypeInfoKind::SmallInt => odbc_api::DataType::SmallInt,
223        AnyTypeInfoKind::Integer => odbc_api::DataType::Integer,
224        AnyTypeInfoKind::BigInt => odbc_api::DataType::BigInt,
225        AnyTypeInfoKind::Real => odbc_api::DataType::Real,
226        AnyTypeInfoKind::Double => odbc_api::DataType::Double,
227        AnyTypeInfoKind::Text => odbc_api::DataType::WVarchar { length: None },
228        AnyTypeInfoKind::Blob => odbc_api::DataType::Varbinary { length: None },
229    })
230}
231
232fn map_result(result: OdbcQueryResult) -> AnyQueryResult {
233    AnyQueryResult {
234        rows_affected: result.rows_affected(),
235        last_insert_id: None,
236    }
237}
238
239fn column_names(columns: &[OdbcColumn]) -> Arc<HashMap<UStr, usize>> {
240    Arc::new(
241        columns
242            .iter()
243            .map(|column| (UStr::new(column.name()), column.ordinal()))
244            .collect(),
245    )
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn maps_stable_odbc_types_to_any_types() {
254        assert_eq!(
255            AnyTypeInfo::try_from(&OdbcTypeInfo::new(odbc_api::DataType::Bit))
256                .unwrap()
257                .kind(),
258            AnyTypeInfoKind::Bool
259        );
260        assert_eq!(
261            AnyTypeInfo::try_from(&OdbcTypeInfo::new(odbc_api::DataType::Integer))
262                .unwrap()
263                .kind(),
264            AnyTypeInfoKind::Integer
265        );
266        assert_eq!(
267            AnyTypeInfo::try_from(&OdbcTypeInfo::new(odbc_api::DataType::WVarchar {
268                length: None
269            }))
270            .unwrap()
271            .kind(),
272            AnyTypeInfoKind::Text
273        );
274        assert_eq!(
275            AnyTypeInfo::try_from(&OdbcTypeInfo::new(odbc_api::DataType::Varbinary {
276                length: None
277            }))
278            .unwrap()
279            .kind(),
280            AnyTypeInfoKind::Blob
281        );
282    }
283
284    #[test]
285    fn rejects_unstable_odbc_types_for_any_mapping() {
286        assert!(matches!(
287            AnyTypeInfo::try_from(&OdbcTypeInfo::new(odbc_api::DataType::Timestamp {
288                precision: 6
289            })),
290            Err(sqlx_core::Error::AnyDriverError(_))
291        ));
292    }
293}