我正在学习 Rust 和 Rocket 框架,并尝试使用 Diesel 构建一个具有数据库连接的应用程序。我已经能够成功连接到 SqLite 数据库并执行一些基本的 CRUD 操作。现在我希望能够确保事务原子性。例如,我有一个用户模型,其中包含用户表和角色表,这两个表处于多对多关系,并通过名为 user_role 的联结表连接。因此,要插入新用户,我会执行以下操作:
let new_user = CreateUser{id: Option::from(new_id), username, email, password_hash: password };
diesel::insert_into(user::table)
.values(&new_user)
.execute(connection)
.expect("Error saving the user");
let user_role = CreateUserRole{user_id: new_user.id, role_id: existing_role.id};
diesel::insert_into(user_role::table)
.values(&user_role)
.execute(connection)
.expect("Could not add role to user");
Run Code Online (Sandbox Code Playgroud)
现在的问题是,如果角色分配出现问题,则会创建用户,但不会分配角色,这是我不希望发生的情况。有没有办法确保原子性,以便要么执行两个操作,要么都不执行任何操作。我在有关事务管理器的文档中看到了此页面:https ://docs.diesel.rs/master/diesel/connection/trait.TransactionManager.html ,但我真的不明白如何使用它,而且我还没有找到任何例子。