在sqlx中有一种Transaction
类型可以让您在一个事务中运行多个查询。
我试图弄清楚如何做到这一点,遗憾的是没有记录,尽管有自动生成的 API 文档。
我的第一次尝试:
async fn insert_user() {
let pool: sqlx::Pool<sqlx::MySql> =
futures::executor::block_on(crate::db::open_mariadb_pool()).unwrap();
use sqlx::Acquire;
let mut conn = pool.acquire().await.unwrap();
let tx = conn.begin().await.unwrap();
let insert_query = sqlx::query("INSERT INTO user (email, email_verification_secret, email_verified, password_hash, hourly_rate)
VALUES (?, ?, ?, ?, ?);"
)
.bind("text@example.com")
.bind(false)
.bind(123)
.bind("pwhash")
.bind(20);
let get_row_query = sqlx::query::<sqlx::MySql>("SELECT * FROM user WHERE id = LAST_INSERT_ID();");
insert_query.execute(tx);
get_row_query.execute(tx);
tx.commit();
}
产生以下错误:
error[E0277]: the trait bound `Transaction<'_, MySql>: Executor<'_>` is not satisfied
--> src/controller_user.rs:86:26
|
86 | insert_query.execute(tx);
| ^^ the trait `Executor<'_>` is not implemented for `Transaction<'_, MySql>`
|
= help: the following implementations were found:
<&'t mut Transaction<'c, MySql> as Executor<'t>>
error[E0277]: the trait bound `Transaction<'_, MySql>: Executor<'_>` is not satisfied
--> src/controller_user.rs:87:27
|
87 | get_row_query.execute(tx);
| ^^ the trait `Executor<'_>` is not implemented for `Transaction<'_, MySql>`
|
= help: the following implementations were found:
<&'t mut Transaction<'c, MySql> as Executor<'t>>
我真的不知道从哪里开始考虑这个问题——但我无法从自动生成的 API 文档中找到答案。