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

事务

Orm::transaction 接收异步回调并提供 OrmTransaction。在回调中从事务对象获取模型 Repository, 即可确保操作使用同一连接:

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?;

回调返回 Ok 时事务提交;返回错误时 ORM 回滚并返回该错误。若回滚本身失败,返回错误会同时报告 回调错误与回滚错误。

也可以显式控制事务:

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

从根 Orm 创建的 Repository 不会自动绑定到事务。在事务回调或手动事务中,必须通过事务对象 获取 Repository。