Skip to content

Commit 91ca532

Browse files
authored
Merge pull request #18 from sqlpage/81reap/connecting/3b
Report local ODBC setup failures as configuration errors
2 parents 5c7c976 + f28f027 commit 91ca532

4 files changed

Lines changed: 80 additions & 15 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
4242
`OdbcConnection::connect()` accepts a standard ODBC connection string, a bare
4343
DSN name, or the legacy `odbc:` prefix.
4444

45+
Local connection setup failures, such as an unregistered DSN (`IM002`), return
46+
`sqlx::Error::Configuration` with the original ODBC diagnostic as the cause.
47+
Server connection and authentication failures still return `sqlx::Error::Database`.
48+
4549
SQLx `query()` uses the driver's prepared-statement parameter count to check
4650
binds. Use `sqlx_core::raw_sql::raw_sql()` for SQL that needs direct execution
4751
without bind parameters.

‎src/connection.rs‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,7 @@ impl OdbcConnection {
6060
pub fn connect_blocking(options: &OdbcConnectOptions) -> Result<Self> {
6161
let (connection, ready) = Self::start(options)?;
6262
ready.recv().map_err(|_| {
63-
crate::OdbcError::Configuration(
64-
"ODBC connection worker stopped while opening".to_owned(),
65-
)
63+
crate::OdbcError::Configuration("ODBC connection worker stopped while opening".into())
6664
})??;
6765
Ok(connection)
6866
}
@@ -122,7 +120,9 @@ impl OdbcConnection {
122120
let _ = finished.send(());
123121
})
124122
.map_err(|error| {
125-
crate::OdbcError::Configuration(format!("failed to start ODBC worker: {error}"))
123+
crate::OdbcError::Configuration(
124+
format!("failed to start ODBC worker: {error}").into(),
125+
)
126126
})?;
127127

128128
Ok((
@@ -289,18 +289,13 @@ fn worker_stopped() -> sqlx_core::Error {
289289

290290
fn open_connection(options: &OdbcConnectOptions) -> Result<odbc_api::Connection<'static>> {
291291
let env = odbc_api::environment().map_err(|error| {
292-
crate::OdbcError::Configuration(format!(
293-
"failed to initialize the process-wide ODBC environment: {error}"
294-
))
292+
crate::OdbcError::Configuration(
293+
format!("failed to initialize the process-wide ODBC environment: {error}").into(),
294+
)
295295
})?;
296296

297297
env.connect_with_connection_string(options.connection_string(), Default::default())
298-
.map_err(|error| {
299-
crate::error::database_error_with_context(
300-
error,
301-
"failed to open ODBC connection using the supplied connection string",
302-
)
303-
})
298+
.map_err(crate::error::connection_error)
304299
}
305300

306301
impl<'c> ConnectionState<'c> {

‎src/error.rs‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use odbc_api::{
22
handles::{slice_to_cow_utf8, Record},
33
Error as OdbcApiError,
44
};
5+
use sqlx_core::error::BoxDynError;
56
use std::borrow::Cow;
67
use std::fmt::{Display, Formatter, Result as FmtResult};
78

@@ -17,7 +18,7 @@ pub enum OdbcError {
1718

1819
/// Invalid local configuration.
1920
#[error("ODBC configuration error: {0}")]
20-
Configuration(String),
21+
Configuration(#[source] BoxDynError),
2122
}
2223

2324
impl From<OdbcApiError> for OdbcError {
@@ -30,11 +31,28 @@ impl From<OdbcError> for sqlx_core::Error {
3031
fn from(error: OdbcError) -> Self {
3132
match error {
3233
OdbcError::Database(error) => sqlx_core::Error::Database(Box::new(error)),
33-
OdbcError::Configuration(message) => sqlx_core::Error::Configuration(message.into()),
34+
OdbcError::Configuration(error) => sqlx_core::Error::Configuration(error),
3435
}
3536
}
3637
}
3738

39+
pub(crate) fn connection_error(error: OdbcApiError) -> OdbcError {
40+
let local_setup_failure = match &error {
41+
OdbcApiError::Diagnostics { record, .. } => {
42+
// Missing DSN, driver load failure, DRIVER syntax, or driver architecture mismatch.
43+
matches!(&record.state.0, b"IM002" | b"IM003" | b"IM012" | b"IM014")
44+
}
45+
_ => false,
46+
};
47+
if local_setup_failure {
48+
return OdbcError::Configuration(Box::new(error));
49+
}
50+
database_error_with_context(
51+
error,
52+
"failed to open ODBC connection using the supplied connection string",
53+
)
54+
}
55+
3856
pub(crate) fn database_error_with_context(
3957
error: OdbcApiError,
4058
context: impl Into<String>,
@@ -161,6 +179,35 @@ mod tests {
161179
text.bytes().map(C::from).collect()
162180
}
163181

182+
#[test]
183+
fn only_known_local_connection_failures_are_configuration_errors() {
184+
let diagnostic = |state| OdbcApiError::Diagnostics {
185+
function: "SQLDriverConnect",
186+
record: Record {
187+
state: State(state),
188+
native_error: 0,
189+
message: Vec::new(),
190+
},
191+
};
192+
193+
for state in [*b"IM002", *b"IM003", *b"IM012", *b"IM014"] {
194+
let OdbcError::Configuration(error) = connection_error(diagnostic(state)) else {
195+
panic!("{} should be a configuration error", State(state).as_str());
196+
};
197+
assert!(matches!(
198+
error.downcast_ref::<OdbcApiError>(),
199+
Some(OdbcApiError::Diagnostics { record, .. }) if record.state == State(state)
200+
));
201+
}
202+
203+
for state in [*b"08001", *b"28000", *b"HY000"] {
204+
let OdbcError::Database(error) = connection_error(diagnostic(state)) else {
205+
panic!("{} should be a database error", State(state).as_str());
206+
};
207+
assert_eq!(error.code().as_deref(), Some(State(state).as_str()));
208+
}
209+
}
210+
164211
#[test]
165212
fn database_error_uses_odbc_diagnostics_for_message_and_code() {
166213
let error = OdbcDatabaseError::from(OdbcApiError::Diagnostics {

‎tests/odbc.rs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,25 @@ async fn sqlx_connection_connect_ping_and_transaction_when_configured(
179179
Ok(())
180180
}
181181

182+
#[tokio::test]
183+
async fn connecting_to_a_missing_dsn_reports_configuration_error_im002() {
184+
// Keep the DSN under the ODBC 32-character limit so this tests a missing DSN,
185+
// not a malformed connection string.
186+
let connection_string = format!("DSN=sqlx_missing_dsn_{}", std::process::id());
187+
let error = OdbcConnection::connect(&connection_string)
188+
.await
189+
.expect_err("connecting to a missing data source should fail");
190+
191+
let sqlx_core::Error::Configuration(error) = error else {
192+
panic!("a missing DSN should be a configuration error: {error:?}");
193+
};
194+
let Some(odbc_api::Error::Diagnostics { record, .. }) = error.downcast_ref::<odbc_api::Error>()
195+
else {
196+
panic!("the configuration error should retain the ODBC diagnostic: {error:?}");
197+
};
198+
assert_eq!(record.state.as_str(), "IM002");
199+
}
200+
182201
#[tokio::test]
183202
async fn custom_transaction_begin_is_rejected_when_configured(
184203
) -> Result<(), Box<dyn std::error::Error>> {

0 commit comments

Comments
 (0)