The trait `LoadConnection` is not implemented for `&diesel::PgConnection`.

huangapple go评论53阅读模式
英文:

the trait `LoadConnection` is not implemented for `&diesel::PgConnection`

问题

我想用Rust创建一个REST API,但无法让它正常工作。

到目前为止,我的相关代码如下:

 main.rs 中:

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // 将 .env 加载到环境变量中。
    dotenv::dotenv().ok();

    env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

    // 设置数据库连接池
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL");
    let manager = ConnectionManager::<PgConnection>::new(database_url);
    let pool: DbPool = r2d2::Pool::builder()
        .test_on_check_out(true)
        .build(manager)
        .expect("Could not build connection pool");
    let port = std::env::var("PORT").expect("$PORT is not set.");
    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(pool.clone()))
            .wrap(middleware::Logger::default())
            .route("/", web::get().to(|| async { "Actix REST API" }))
            .service(handlers::common::houses::index)
    })
    .bind(("0.0.0.0", port.parse().unwrap()))?
    .run()
    .await
}

模式:

diesel::table! {
  houses (id) {
    id -> Int4,
    user_id -> Varchar,
    street -> Varchar,
    figure -> Varchar,
    floor -> Varchar,
    create_date -> Timestamp,
    update_date -> Timestamp,
    is_deleted -> Bool,
  }
}

模型:

#[derive(Debug, Serialize, Deserialize, Queryable)]
pub struct House {
    pub id: i32,
    pub user_id: String,
    pub street: String,
    pub figure: String,
    pub floor: String,
    pub create_date: chrono::NaiveDateTime,
    pub update_date: chrono::NaiveDateTime,
    pub is_deleted: bool,
}

处理程序:

#[get("/houses")]
async fn index(pool: web::Data<DbPool>) -> Result<HttpResponse, Error> {
    let houses = web::block(move || {
        let conn = &pool.get()?;
        find_all(&conn)
    })
    .await?
    .map_err(actix_web::error::ErrorInternalServerError)?;

    Ok(HttpResponse::Ok().json(houses))
}

fn find_all(conn: &PgConnection) -> Result<Vec<House>, DbError> {
    use crate::schemas::common::houses::houses::dsl::*;

    let items = houses.load::<House>(&mut conn)?;
    Ok(items)
}

依赖项为:

[dependencies]
actix-web = "4"
chrono = { version = "0.4.19", features = ["serde"] }
diesel = { version = "2.0.3", features = ["postgres", "r2d2", "chrono"] }
dotenv = "0.15.0"
env_logger = "0.10.0"
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0"

它一直报错,我不明白原因。

错误信息为:

error[E0277]: the trait bound `&diesel::PgConnection: LoadConnection` is not satisfied
src\handlers\common\houses.rs:25:37
| 25 | let items = houses.load::<House>(&mut conn)?;
| ---- | -^^^^^^^^
| | | the trait `LoadConnection` is not implemented for `&diesel::PgConnection`
help: consider removing the leading `&`-reference required by a bound introduced by this call
| note: required for `table` to implement `LoadQuery<'_, &diesel::PgConnection, House>`
note: required by a bound in `diesel::RunQueryDsl::load`

我在 diesel 版本 1.4 中见过类似的错误,但我认为这个版本不同。
另外,我刚开始使用 Rust,目前有点迷茫。

我希望有人知道问题所在以及如何解决它。
英文:

I want to create a rest api with rust and can't make it work.

My relevant code so far:

In the main.rs:

#[actix_web::main]
async fn main() -&gt; std::io::Result&lt;()&gt; {
// Loading .env into environment variable.
dotenv::dotenv().ok();
env_logger::init_from_env(env_logger::Env::new().default_filter_or(&quot;info&quot;));
// set up database connection pool
let database_url = std::env::var(&quot;DATABASE_URL&quot;).expect(&quot;DATABASE_URL&quot;);
let manager = ConnectionManager::&lt;PgConnection&gt;::new(database_url);
let pool: DbPool = r2d2::Pool::builder()
.test_on_check_out(true)
.build(manager)
.expect(&quot;Could not build connection pool&quot;);
let port = std::env::var(&quot;PORT&quot;).expect(&quot;$PORT is not set.&quot;);
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
.wrap(middleware::Logger::default())
.route(&quot;/&quot;, web::get().to(|| async { &quot;Actix REST API&quot; }))
.service(handlers::common::houses::index)
})
.bind((&quot;0.0.0.0&quot;, port.parse().unwrap()))?
.run()
.await
}

The schema:

diesel::table! {
houses (id) {
id -&gt; Int4,
user_id -&gt; Varchar,
street -&gt; Varchar,
figure -&gt; Varchar,
floor -&gt; Varchar,
create_date -&gt; Timestamp,
update_date -&gt; Timestamp,
is_deleted -&gt; Bool,
}
}

The model:

#[derive(Debug, Serialize, Deserialize, Queryable)]
pub struct House {
pub id: i32,
pub user_id: String,
pub street: String,
pub figure: String,
pub floor: String,
pub create_date: chrono::NaiveDateTime,
pub update_date: chrono::NaiveDateTime,
pub is_deleted: bool,
}

The handler:

#[get(&quot;/houses&quot;)]
async fn index(pool: web::Data&lt;DbPool&gt;) -&gt; Result&lt;HttpResponse, Error&gt; {
let houses = web::block(move || {
let conn = &amp;pool.get()?;
find_all(&amp;conn)
})
.await?
.map_err(actix_web::error::ErrorInternalServerError)?;
Ok(HttpResponse::Ok().json(houses))
}
fn find_all(conn: &amp;PgConnection) -&gt; Result&lt;Vec&lt;House&gt;, DbError&gt; {
use crate::schemas::common::houses::houses::dsl::*;
let items =houses.load::&lt;House&gt;(&amp;mut conn)?;
Ok(items)
}

The dependencies are:

[dependencies]
actix-web = &quot;4&quot;
chrono = { version = &quot;0.4.19&quot;, features = [&quot;serde&quot;] }
diesel = { version = &quot;2.0.3&quot;, features = [&quot;postgres&quot;, &quot;r2d2&quot;, &quot;chrono&quot;] }
dotenv = &quot;0.15.0&quot;
env_logger = &quot;0.10.0&quot;
serde = { version = &quot;1.0.136&quot;, features = [&quot;derive&quot;] }
serde_json = &quot;1.0&quot;`

It keeps giving an error, and I don't understand why.
The error is:

`error[E0277]: the trait bound `&amp;diesel::PgConnection: LoadConnection` is not satisfied src\handlers\common\houses.rs:25:37
| 25   |     let items =houses.load::&lt;House&gt;(&amp;mut conn)?;
|                       ----          -^^^^^^^^
|                       |             | the trait `LoadConnection` is not implemented for `&amp;diesel::PgConnection` help: consider removing the leading `&amp;`-reference required by a bound introduced by this call
| note: required for `table` to implement `LoadQuery&lt;&#39;_, &amp;diesel::PgConnection, House&gt;` note: required by a bound in `diesel::RunQueryDsl::load`

I've seen a similar error with the diesel version 1.4, but I think that this version is different.
Plus I'm starting with rust and I'm a little lost in general at the moment.

I was hopping someone knows what the problem is and how to fix it.

答案1

得分: 0

`PgConnection` 实现了 [`LoadConnection`](https://docs.rs/diesel/2.0.3/diesel/connection/trait.LoadConnection.html),但 `&amp;PgConnection` 不是(注意多余的 `&amp;`)。

 `conn` 变为可变引用并传递:

```rust
#[get("/houses")]
async fn index(pool: web::Data<DbPool>) -> Result<HttpResponse, Error> {
    let houses = web::block(move || {
        let mut conn = pool.get()?; // <------------
        find_all(&mut conn)         // <------------
    })
    .await?
    .map_err(actix_web::error::ErrorInternalServerError)?;

    Ok(HttpResponse::Ok().json(houses))
}

fn find_all(conn: &mut PgConnection) -> Result<Vec<House>, DbError> {
                // ^^^ <------------
    use crate::schemas::common::houses::houses::dsl::*;

    let items = houses.load::<House>(conn)?; // <------------
    Ok(items)
}
英文:

PgConnection implements LoadConnection but &amp;PgConnection does not (note the extra &amp;).

Make conn mutable and pass as a mutable reference:

#[get(&quot;/houses&quot;)]
async fn index(pool: web::Data&lt;DbPool&gt;) -&gt; Result&lt;HttpResponse, Error&gt; {
let houses = web::block(move || {
let mut conn = pool.get()?; // &lt;------------
find_all(&amp;mut conn)         // &lt;------------
})
.await?
.map_err(actix_web::error::ErrorInternalServerError)?;
Ok(HttpResponse::Ok().json(houses))
}
fn find_all(conn: &amp;mut PgConnection) -&gt; Result&lt;Vec&lt;House&gt;, DbError&gt; {
// ^^^ &lt;------------
use crate::schemas::common::houses::houses::dsl::*;
let items = houses.load::&lt;House&gt;(conn)?; // &lt;------------
Ok(items)
}

huangapple
  • 本文由 发表于 2023年2月7日 04:25:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定