diff --git a/README.md b/README.md index cb359f3..98e6cd0 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,9 @@ query stream stops delivery and lets the worker release its cursor before running the next operation. A native ODBC call already in progress can still run to completion. +ODBC transactions support `begin()`. Custom `begin_with()` statements and +nested transactions are rejected. + ## Any Driver Install this crate explicitly before opening ODBC URLs through SQLx diff --git a/src/connection.rs b/src/connection.rs index 59832d0..d3579c9 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -46,6 +46,7 @@ struct ConnectionState<'c> { buffer_settings: OdbcBufferSettings, status: Arc, broken: bool, + rejected_nested_begin: bool, } impl std::fmt::Debug for OdbcConnection { @@ -99,6 +100,7 @@ impl OdbcConnection { buffer_settings: options.buffer_settings, status: worker_status, broken: false, + rejected_nested_begin: false, }; if ready.send(Ok(())).is_err() { @@ -182,11 +184,23 @@ impl OdbcConnection { .map_err(|_| worker_stopped())? } - pub(crate) async fn begin_transaction(&mut self) -> std::result::Result<(), sqlx_core::Error> { + pub(crate) async fn begin_transaction( + &mut self, + statement: Option, + ) -> std::result::Result<(), sqlx_core::Error> { let (reply, result) = flume::bounded(1); let (acknowledge, acknowledged) = flume::bounded(1); self.jobs .send(Box::new(move |state| { + // SQLx queues a rollback even for a failed or cancelled begin. Mark + // rejected nested begins before checking for cancellation, so that the + // queued rollback cannot affect the outer transaction. + let nested = state.status.transaction_depth.load(Ordering::Relaxed) > 0; + if nested || statement.is_some() { + state.rejected_nested_begin = nested; + let _ = reply.send(Err(sqlx_core::Error::InvalidSavePointStatement)); + return; + } if reply.is_disconnected() { return; } @@ -220,7 +234,11 @@ impl OdbcConnection { } pub(crate) fn start_rollback(&mut self) { - let _ = self.jobs.send(Box::new(|state| state.rollback_on_drop())); + let _ = self.jobs.send(Box::new(|state| { + if !std::mem::take(&mut state.rejected_nested_begin) { + state.rollback_on_drop(); + } + })); } pub(crate) fn transaction_depth(&self) -> usize { @@ -314,10 +332,6 @@ impl<'c> ConnectionState<'c> { } fn begin(&mut self) -> std::result::Result<(), sqlx_core::Error> { - if self.status.transaction_depth.load(Ordering::Relaxed) > 0 { - return Err(sqlx_core::Error::InvalidSavePointStatement); - } - self.conn.set_autocommit(false).map_err(|error| { crate::error::database_error_with_context( error, diff --git a/src/transaction.rs b/src/transaction.rs index 98d74cf..3a5634e 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -8,9 +8,9 @@ impl sqlx_core::transaction::TransactionManager for OdbcTransactionManager { async fn begin( conn: &mut OdbcConnection, - _statement: Option, + statement: Option, ) -> Result<(), sqlx_core::Error> { - conn.begin_transaction().await + conn.begin_transaction(statement).await } async fn commit(conn: &mut OdbcConnection) -> Result<(), sqlx_core::Error> { diff --git a/tests/odbc.rs b/tests/odbc.rs index d62fb12..e2ac2ca 100644 --- a/tests/odbc.rs +++ b/tests/odbc.rs @@ -179,6 +179,94 @@ async fn sqlx_connection_connect_ping_and_transaction_when_configured( Ok(()) } +#[tokio::test] +async fn custom_transaction_begin_is_rejected_when_configured( +) -> Result<(), Box> { + let Some(mut conn) = get_test_conn("ODBC custom transaction begin test").await? else { + return Ok(()); + }; + assert_rejected_begin_preserves_outer_transaction(&mut conn).await?; + + let Some(mut any) = get_any_test_conn("Any ODBC custom transaction begin test").await? else { + return Ok(()); + }; + assert_rejected_begin_preserves_outer_transaction(&mut any).await +} + +async fn assert_rejected_begin_preserves_outer_transaction( + conn: &mut C, +) -> Result<(), Box> +where + C: Connection, + for<'c> &'c mut C: Executor<'c, Database = C::Database>, +{ + use sqlx_core::raw_sql::raw_sql; + use std::future::Future; + use std::task::{Context, Poll, Waker}; + + assert!(matches!( + conn.begin_with("BEGIN READ ONLY").await, + Err(sqlx_core::Error::InvalidSavePointStatement) + )); + assert!(!conn.is_in_transaction()); + let table = test_table_name("rejected_begin"); + raw_sql(AssertSqlSafe(format!("CREATE TABLE {table} (id INTEGER)"))) + .execute(&mut *conn) + .await?; + + let mut tx = conn.begin().await?; + raw_sql(AssertSqlSafe(format!("INSERT INTO {table} VALUES (1)"))) + .execute(&mut *tx) + .await?; + assert!(matches!( + tx.begin().await, + Err(sqlx_core::Error::InvalidSavePointStatement) + )); + assert!(matches!( + tx.begin_with("BEGIN READ ONLY").await, + Err(sqlx_core::Error::InvalidSavePointStatement) + )); + { + let mut nested = std::pin::pin!(tx.begin()); + let mut context = Context::from_waker(Waker::noop()); + if let Poll::Ready(result) = nested.as_mut().poll(&mut context) { + assert!(matches!( + result, + Err(sqlx_core::Error::InvalidSavePointStatement) + )); + } + } + tx.commit().await?; + + let mut tx = conn.begin().await?; + raw_sql(AssertSqlSafe(format!("INSERT INTO {table} VALUES (2)"))) + .execute(&mut *tx) + .await?; + assert!(matches!( + tx.begin().await, + Err(sqlx_core::Error::InvalidSavePointStatement) + )); + drop(tx); + + let committed = format!("SELECT id FROM {table} WHERE id = 1"); + let rolled_back = format!("SELECT id FROM {table} WHERE id = 2"); + let committed = raw_sql(AssertSqlSafe(committed)) + .fetch_optional(&mut *conn) + .await?; + let rolled_back = raw_sql(AssertSqlSafe(rolled_back)) + .fetch_optional(&mut *conn) + .await?; + raw_sql(AssertSqlSafe(format!("DROP TABLE {table}"))) + .execute(conn) + .await?; + assert!(committed.is_some(), "outer transaction failed to commit"); + assert!( + rolled_back.is_none(), + "dropped outer transaction failed to roll back" + ); + Ok(()) +} + #[tokio::test] async fn sqlx_pool_acquires_and_queries_when_configured() -> Result<(), Box> {