sqlx-transaction-manager
A type-safe transaction management wrapper for SQLx with automatic commit/rollback.
Features
- ✅ Automatic Rollback: Transactions automatically roll back on drop if not explicitly committed
- ✅ Type-Safe: Transaction boundaries are enforced at compile time
- ✅ Ergonomic API: Simple
with_transactionfunction for common use cases - ✅ Nested Transactions: Support for savepoints to simulate nested transactions
- ✅ Zero Runtime Overhead: Thin wrapper around SQLx's native transaction support
- ✅ Works with sqlx-named-bind: Seamless integration with named parameter binding
Installation
Add this to your Cargo.toml:
[]
= { = "0.8", = ["mysql", "runtime-tokio"] }
= "0.1"
Quick Start
use MySqlPool;
use with_transaction;
async
Examples
Multiple Operations in One Transaction
use MySqlPool;
use with_transaction;
let user_id = with_transaction.await?;
Using with sqlx-named-bind
use MySqlPool;
use with_transaction;
use PreparedQuery;
with_transaction.await?;
Nested Transactions (Savepoints)
use MySqlPool;
use ;
with_transaction.await?;
Manual Transaction Control
use MySqlPool;
use TransactionContext;
let mut tx = begin.await?;
query
.bind
.execute
.await?;
// Explicitly commit
tx.commit.await?;
Comparison: Before and After
Before (Raw SQLx)
let mut tx = pool.begin.await?;
match query
.bind
.execute
.await
After (sqlx-transaction-manager)
with_transaction.await?;
Error Handling
Transactions automatically roll back on error:
let result = with_transaction.await;
assert!;
// The INSERT was rolled back
How It Works
- TransactionContext: Wraps SQLx's
Transactionand tracks its state - Automatic Cleanup: Uncommitted transactions are rolled back on drop
- Type Safety: Consumed transactions can't be reused (enforced at compile time)
- Executor Access: Provides
&mut MySqlConnectionfor use with SQLx queries
Limitations
- Currently only supports MySQL (PostgreSQL and SQLite support planned)
- Nested transactions use savepoints (MySQL limitation)
- Error type is
sqlx_transaction_manager::Error(wrapssqlx::Error)
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.