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
2 changes: 1 addition & 1 deletion src/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ where
Box::pin(async move {
let res = res.await.unwrap(); // inner service is infallible

if res.status().is_success() {
if !res.status().is_server_error() && !res.status().is_client_error() {
if let Err(error) = transaction.commit().await {
return Ok(E::from(Error::Database { error }).into_response());
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
//! [`Tx`] is an `axum` [extractor][axum extractors] for obtaining a transaction that's bound to the
//! HTTP request. A transaction begins the first time the extractor is used for a request, and is
//! then stored in [request extensions] for use by other middleware/handlers. The transaction is
//! resolved depending on the status code of the eventual response – successful (HTTP `2XX`)
//! responses will cause the transaction to be committed, otherwise it will be rolled back.
//! resolved depending on the status code of the eventual response – successful (HTTP `2XX` or
//! `3XX`) responses will cause the transaction to be committed, otherwise it will be rolled back.
//!
//! This behaviour is often a sensible default, and using the extractor (e.g. rather than directly
//! using [`sqlx::Transaction`]s) means you can't forget to commit the transactions!
Expand Down
17 changes: 17 additions & 0 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,23 @@ async fn commit_on_success() {
assert_eq!(users, vec![(1, "huge hackerman".to_string())]);
}

#[tokio::test]
async fn commit_on_redirection() {
let (_db, pool, response) = build_app(|mut tx: Tx| async move {
let (_, _) = insert_user(&mut tx, 1, "john redirect").await;
http::StatusCode::SEE_OTHER
})
.await;

assert!(response.status.is_redirection());

let users: Vec<(i32, String)> = sqlx::query_as("SELECT * FROM users")
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(users, vec![(1, "john redirect".to_string())]);
}

#[tokio::test]
async fn rollback_on_error() {
let (_db, pool, response) = build_app(|mut tx: Tx| async move {
Expand Down