Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Transactions

Orm::transaction runs an asynchronous callback with an OrmTransaction. The callback receives model repositories from the transaction, so all operations use the same connection.

let user_id = orm
    .transaction(async |transaction| {
        let mut user = User {
            id: None,
            email: "ada@example.com".into(),
            display_name: "Ada".into(),
            deleted_at: None,
            version: 0,
        };
        transaction.repo::<User>()?.insert(&mut user).await?;

        let mut profile = Profile {
            id: None,
            user_id: user.id.expect("generated id"),
            biography: "Mathematician".into(),
        };
        transaction.repo::<Profile>()?.insert(&mut profile).await?;

        Ok(user.id.expect("generated id"))
    })
    .await?;

The transaction commits when the callback returns Ok. If the callback returns an error, the ORM rolls back and returns the error. A rollback failure is reported together with the callback error.

For explicit control, call begin, perform operations through transaction.repo::<Model>(), then call commit or rollback:

let mut transaction = orm.begin().await?;
transaction.repo::<User>()?.delete(user_id).await?;
transaction.commit().await?;

Repository handles created from the root Orm are not transaction-bound. Inside a transaction callback or manual transaction, obtain repositories from the transaction object.