Use the axum-sqlx-tx crate to automatically manage request-bound SQLx transactions that commit on success or rollback on error. Add the dependency and inject the transaction into your handler to begin using it.
[dependencies]
axum-sqlx-tx = "0.1"
use axum::Router;
use axum_sqlx_tx::Transaction;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/update", post_handler);
// ... setup server
}
async fn post_handler(mut tx: Transaction<sqlx::Sqlite>) -> Result<(), sqlx::Error> {
tx.execute("UPDATE users SET status = 'active'").await?;
// Commits automatically if no error, rolls back if error occurs
Ok(())
}