FAQ - Help and questions

How do I use transactions in sqlx so that a failed step undoes the earlier ones?

#sqlx#transactions#database#error-handlingpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Call pool.begin() to get a Transaction, run each statement with &mut *tx as the executor, and call tx.commit() at the end. If the function returns early with an error, the transaction is dropped and rolled back, so earlier statements leave no trace in the database.

Checked with rustc 1.93.0, sqlx 0.8.6 (SQLite), tokio 1.54.1, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A transaction makes a group of statements succeed or fail as one. In sqlx the early return is the rollback: if the Transaction value goes out of scope without commit, sqlx rolls it back (the sqlx documentation states this).

rust
use sqlx::{sqlite::SqlitePoolOptions, SqlitePool};

async fn transfer(pool: &SqlitePool, from: i64, to: i64, amount: i64) -> Result<(), sqlx::Error> {
    let mut tx = pool.begin().await?;
    sqlx::query("UPDATE accounts SET balance = balance - ? WHERE id = ?").bind(amount).bind(from).execute(&mut *tx).await?;
    sqlx::query("UPDATE accounts SET balance = balance + ? WHERE id = ?").bind(amount).bind(to).execute(&mut *tx).await?;
    // The CHECK constraint on `balance` makes the first UPDATE fail when the account is short;
    // the `?` then returns early, `tx` is dropped, and the transaction is rolled back.
    tx.commit().await
}

async fn balances(pool: &SqlitePool) -> Vec<(i64, i64)> {
    sqlx::query_as("SELECT id, balance FROM accounts ORDER BY id").fetch_all(pool).await.unwrap()
}

#[tokio::main]
async fn main() {
    let pool = SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await.unwrap();
    sqlx::query("CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER NOT NULL CHECK (balance >= 0))").execute(&pool).await.unwrap();
    sqlx::query("INSERT INTO accounts VALUES (1, 100), (2, 0)").execute(&pool).await.unwrap();

    println!("start:            {:?}", balances(&pool).await);
    println!("transfer 30:      {:?}", transfer(&pool, 1, 2, 30).await.is_ok());
    println!("after:            {:?}", balances(&pool).await);
    let err = transfer(&pool, 1, 2, 500).await.unwrap_err();
    println!("transfer 500:     {err}");
    println!("after the failure: {:?}", balances(&pool).await);
}
text
start:            [(1, 100), (2, 0)]
transfer 30:      true
after:            [(1, 70), (2, 30)]
transfer 500:     error returned from database: (code: 275) CHECK constraint failed: balance >= 0
after the failure: [(1, 70), (2, 30)]

The first transfer moved 30 and committed. The second tried to move 500 out of an account holding 70: the database refused the first UPDATE through the CHECK (balance >= 0) rule, ? returned the error, the transaction was dropped, and the balances afterwards are the same as before the call.

Common mistakes#

  • Passing &pool instead of &mut *tx to the statements in the transaction. Those statements then run on another connection, outside the transaction.
  • Forgetting commit(). The work is silently rolled back when the value is dropped.
  • Holding a transaction open while waiting for a slow network call. Other writers wait for it.

Do I need a transaction for one statement?#

A single statement is already atomic. Use a transaction when several statements must succeed together.

Why max_connections(1) in the example?#

For an in-memory SQLite database in a small demonstration. See the thread on in-memory databases in tests.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet