Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
`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.
Expand Down
21 changes: 8 additions & 13 deletions src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,7 @@ impl OdbcConnection {
pub fn connect_blocking(options: &OdbcConnectOptions) -> Result<Self> {
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)
}
Expand Down Expand Up @@ -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((
Expand Down Expand Up @@ -289,18 +289,13 @@ fn worker_stopped() -> sqlx_core::Error {

fn open_connection(options: &OdbcConnectOptions) -> Result<odbc_api::Connection<'static>> {
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> {
Expand Down
51 changes: 49 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -17,7 +18,7 @@ pub enum OdbcError {

/// Invalid local configuration.
#[error("ODBC configuration error: {0}")]
Configuration(String),
Configuration(#[source] BoxDynError),
}

impl From<OdbcApiError> for OdbcError {
Expand All @@ -30,11 +31,28 @@ impl From<OdbcError> 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<String>,
Expand Down Expand Up @@ -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::<OdbcApiError>(),
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 {
Expand Down
19 changes: 19 additions & 0 deletions tests/odbc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<odbc_api::Error>()
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<dyn std::error::Error>> {
Expand Down