我想设置一个接受 SQLx PgPool或MySqlPool的通用函数。
use dotenv::dotenv;
use sqlx::postgres::PgPool;
use sqlx::{Pool, Database};
use std::env;
#[derive(Debug)]
struct Todo {
id: i64,
description: String,
done: bool,
}
#[actix_web::main]
async fn main() -> anyhow::Result<()> {
dotenv().ok();
let pool = PgPool::connect(&env::var("DATABASE_URL")?).await?;
list_todos(&pool).await?;
Ok(())
}
async fn list_todos<D: Database>(pool: &Pool<D>) -> anyhow::Result<Vec<Todo>> {
let todos = sqlx::query_as!(
Todo,
r#"
SELECT id, description, done
FROM todos
ORDER BY id
"#
)
.fetch_all(pool)
.await?;
Ok(todos)
}
我看到的错误是:
32 | .fetch_all(pool)
| ^^^^^^^^^ expected type parameter `D`, found struct `Postgres`
|
= note: expected type parameter `D`
found struct `Postgres`
error[E0277]: the trait bound `for<'c> &'c mut <D as sqlx::Database>::Connection: Executor<'c>` is not satisfied
关于如何设置函数以接受 PgPool 或 MySqlPool 参数的任何提示?谢谢