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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 20 additions & 6 deletions src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ struct ConnectionState<'c> {
buffer_settings: OdbcBufferSettings,
status: Arc<ConnectionStatus>,
broken: bool,
rejected_nested_begin: bool,
}

impl std::fmt::Debug for OdbcConnection {
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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<sqlx_core::sql_str::SqlStr>,
) -> 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;
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ impl sqlx_core::transaction::TransactionManager for OdbcTransactionManager {

async fn begin(
conn: &mut OdbcConnection,
_statement: Option<sqlx_core::sql_str::SqlStr>,
statement: Option<sqlx_core::sql_str::SqlStr>,
) -> Result<(), sqlx_core::Error> {
conn.begin_transaction().await
conn.begin_transaction(statement).await
}

async fn commit(conn: &mut OdbcConnection) -> Result<(), sqlx_core::Error> {
Expand Down
88 changes: 88 additions & 0 deletions tests/odbc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn std::error::Error>> {
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<C>(
conn: &mut C,
) -> Result<(), Box<dyn std::error::Error>>
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<dyn std::error::Error>>
{
Expand Down