From f28f027782502a54623a454073a2c6a79799bc6f Mon Sep 17 00:00:00 2001 From: Ophir Lojkine Date: Fri, 27 Nov 2026 16:12:51 +0000 Subject: [PATCH] Classify local ODBC connection setup failures Co-authored-by: 81reap --- README.md | 4 ++++ src/connection.rs | 21 ++++++++----------- src/error.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++-- tests/odbc.rs | 19 ++++++++++++++++++ 4 files changed, 80 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 98e6cd0..45df993 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,10 @@ async fn main() -> Result<(), Box> { `OdbcConnection::connect()` accepts a standard ODBC connection string, a bare DSN name, or the legacy `odbc:` prefix. +Local connection setup failures, such as an unregistered DSN (`IM002`), return +`sqlx::Error::Configuration` with the original ODBC diagnostic as the cause. +Server connection and authentication failures still return `sqlx::Error::Database`. + SQLx `query()` uses the driver's prepared-statement parameter count to check binds. Use `sqlx_core::raw_sql::raw_sql()` for SQL that needs direct execution without bind parameters. diff --git a/src/connection.rs b/src/connection.rs index d3579c9..1afe1c1 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -60,9 +60,7 @@ impl OdbcConnection { pub fn connect_blocking(options: &OdbcConnectOptions) -> Result { let (connection, ready) = Self::start(options)?; ready.recv().map_err(|_| { - crate::OdbcError::Configuration( - "ODBC connection worker stopped while opening".to_owned(), - ) + crate::OdbcError::Configuration("ODBC connection worker stopped while opening".into()) })??; Ok(connection) } @@ -122,7 +120,9 @@ impl OdbcConnection { let _ = finished.send(()); }) .map_err(|error| { - crate::OdbcError::Configuration(format!("failed to start ODBC worker: {error}")) + crate::OdbcError::Configuration( + format!("failed to start ODBC worker: {error}").into(), + ) })?; Ok(( @@ -289,18 +289,13 @@ fn worker_stopped() -> sqlx_core::Error { fn open_connection(options: &OdbcConnectOptions) -> Result> { let env = odbc_api::environment().map_err(|error| { - crate::OdbcError::Configuration(format!( - "failed to initialize the process-wide ODBC environment: {error}" - )) + crate::OdbcError::Configuration( + format!("failed to initialize the process-wide ODBC environment: {error}").into(), + ) })?; env.connect_with_connection_string(options.connection_string(), Default::default()) - .map_err(|error| { - crate::error::database_error_with_context( - error, - "failed to open ODBC connection using the supplied connection string", - ) - }) + .map_err(crate::error::connection_error) } impl<'c> ConnectionState<'c> { diff --git a/src/error.rs b/src/error.rs index e915802..793f48d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -2,6 +2,7 @@ use odbc_api::{ handles::{slice_to_cow_utf8, Record}, Error as OdbcApiError, }; +use sqlx_core::error::BoxDynError; use std::borrow::Cow; use std::fmt::{Display, Formatter, Result as FmtResult}; @@ -17,7 +18,7 @@ pub enum OdbcError { /// Invalid local configuration. #[error("ODBC configuration error: {0}")] - Configuration(String), + Configuration(#[source] BoxDynError), } impl From for OdbcError { @@ -30,11 +31,28 @@ impl From for sqlx_core::Error { fn from(error: OdbcError) -> Self { match error { OdbcError::Database(error) => sqlx_core::Error::Database(Box::new(error)), - OdbcError::Configuration(message) => sqlx_core::Error::Configuration(message.into()), + OdbcError::Configuration(error) => sqlx_core::Error::Configuration(error), } } } +pub(crate) fn connection_error(error: OdbcApiError) -> OdbcError { + let local_setup_failure = match &error { + OdbcApiError::Diagnostics { record, .. } => { + // Missing DSN, driver load failure, DRIVER syntax, or driver architecture mismatch. + matches!(&record.state.0, b"IM002" | b"IM003" | b"IM012" | b"IM014") + } + _ => false, + }; + if local_setup_failure { + return OdbcError::Configuration(Box::new(error)); + } + database_error_with_context( + error, + "failed to open ODBC connection using the supplied connection string", + ) +} + pub(crate) fn database_error_with_context( error: OdbcApiError, context: impl Into, @@ -161,6 +179,35 @@ mod tests { text.bytes().map(C::from).collect() } + #[test] + fn only_known_local_connection_failures_are_configuration_errors() { + let diagnostic = |state| OdbcApiError::Diagnostics { + function: "SQLDriverConnect", + record: Record { + state: State(state), + native_error: 0, + message: Vec::new(), + }, + }; + + for state in [*b"IM002", *b"IM003", *b"IM012", *b"IM014"] { + let OdbcError::Configuration(error) = connection_error(diagnostic(state)) else { + panic!("{} should be a configuration error", State(state).as_str()); + }; + assert!(matches!( + error.downcast_ref::(), + Some(OdbcApiError::Diagnostics { record, .. }) if record.state == State(state) + )); + } + + for state in [*b"08001", *b"28000", *b"HY000"] { + let OdbcError::Database(error) = connection_error(diagnostic(state)) else { + panic!("{} should be a database error", State(state).as_str()); + }; + assert_eq!(error.code().as_deref(), Some(State(state).as_str())); + } + } + #[test] fn database_error_uses_odbc_diagnostics_for_message_and_code() { let error = OdbcDatabaseError::from(OdbcApiError::Diagnostics { diff --git a/tests/odbc.rs b/tests/odbc.rs index e2ac2ca..c2d114b 100644 --- a/tests/odbc.rs +++ b/tests/odbc.rs @@ -179,6 +179,25 @@ async fn sqlx_connection_connect_ping_and_transaction_when_configured( Ok(()) } +#[tokio::test] +async fn connecting_to_a_missing_dsn_reports_configuration_error_im002() { + // Keep the DSN under the ODBC 32-character limit so this tests a missing DSN, + // not a malformed connection string. + let connection_string = format!("DSN=sqlx_missing_dsn_{}", std::process::id()); + let error = OdbcConnection::connect(&connection_string) + .await + .expect_err("connecting to a missing data source should fail"); + + let sqlx_core::Error::Configuration(error) = error else { + panic!("a missing DSN should be a configuration error: {error:?}"); + }; + let Some(odbc_api::Error::Diagnostics { record, .. }) = error.downcast_ref::() + else { + panic!("the configuration error should retain the ODBC diagnostic: {error:?}"); + }; + assert_eq!(record.state.as_str(), "IM002"); +} + #[tokio::test] async fn custom_transaction_begin_is_rejected_when_configured( ) -> Result<(), Box> {