Search code examples
sqliterustrust-dieselrust-axum

the trait `LoadConnection` is not implemented for `deadpool::managed::Object<Manager<SqliteConnection>>`


Context

I'm currently trying to implement deadpool_diesel and diesel to my api made with Axum but I'm getting an error that I'm not sure to understand.

My guess is that I'm maybe doing something wrong with the usage of State but I'm still discovering Axum and Diesel so I don't really know for sure

Error

the trait `LoadConnection` is not implemented for `deadpool::managed::Object<Manager<SqliteConnection>>`

Code

// user.rs

pub async fn get_all_users(State(pool): State<Pool>) {
    let mut conn = pool.get().await.unwrap();

    let all_users = users
    .select(UserInformation::as_select())
    .load::<UserInformation>(&mut conn) // <---------- The error is appearing on the &mut conn
    .unwrap();
}
// main.rs

#[tokio::main]
async fn main() {
    let pool_manager = Manager::new(Config::get_db_path(), Runtime::Tokio1);
    let pool = Pool::builder(pool_manager)
        .max_size(50)
        .build()
        .unwrap();

    let app = Router::new()
        .route("/", get(hello))
        .route("/user", Router::new())
        .with_state(pool);

    let addr = format!("0.0.0.0:{}", config.port);

    axum::Server::bind(&addr.parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

Solution

  • dieselis not async and therefore deadpool-diesel added a sync wrapper around it. You need to call interact on the object passing it a closure like in the example code:

    let result = conn.interact(|conn| {
        let query = select("Hello world!".into_sql::<Text>());
        query.get_result::<String>(conn)
    }).await?;
    

    So my code should look like that:

    pub async fn get_all_users(State(pool): State<Pool>) {
        let mut conn = pool.get().await.unwrap();
       
        let all_users = conn.interact(|conn| users
            .select(UserInformation::as_select())
            .load::<UserInformation>(&mut conn)
            .unwrap()
        ).await.unwrap();
    }
    

    Original answer by deadpool owner: https://github.com/bikeshedder/deadpool/issues/267#issuecomment-1647989137