0

I'm trying to build a rest-api using Rocket, Diesel, and a PostGreSQL database. For this I've tried to "inject" the database connection into a GET method using the rocket_sync_db_pools crate for as quoted in the Rocket guide Rocket also provides support for synchronous, blocking ORMs like Diesel via the rocket_sync_db_pools library. Thus I have tried to stray away the code from using the following code from the Diesel documentation https://diesel.rs/guides/getting-started:

// main.rs
#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(user_controller::stage())
        .attach(cors::CORS)
}

pub fn establish_connection() -> PgConnection {
    dotenv().ok();

    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    PgConnection::establish(&database_url)
        .unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
}

// user_controller.rs
#[get("/<user_id>")]
pub async fn read(user_id: i32) -> Option<Json<User>> {
    let conn = &mut establish_connection();
    let potential_user = users
        .filter(id.eq(user_id))
        .first(conn);
    
    match potential_user {
        Ok(user) => Some(Json(user)),
        Err(NotFound) => None,
        Err(_) => panic!("Internal server error")
    }   
}

pub fn stage() -> AdHoc {
    AdHoc::on_ignite("User Mounts Stage", |rocket| async {
        rocket.mount("/user", routes![read])
    })
}

Into changing it as follows:

// main.rs
use rocket_sync_db_pools::{database, diesel::PgConnection};

#[database("postgres_db")]
pub struct Db(PgConnection);

#[launch]
fn rocket() -> _ {
    rocket::build()
        .attach(user_controller::stage())
        .attach(CourseroDbConn::fairing())
        .attach(cors::CORS)
}

// user_controller.rs
#[get("/<user_id>")]
async fn read(db: Db, user_id: i32) -> Option<Json<User>> {
    db.run(move |conn| {
        users
            .filter(id.eq(user_id))
            .first(conn)
    }).await.map(Json).ok()
}

pub fn stage() -> AdHoc {
    AdHoc::on_ignite("User Mounts Stage", |rocket| async {
        rocket.mount("/user", routes![read])
    })
}

I left out some sections such as the models used and the libraries used, but if they are required for solving this problem I would gladly post them. The versions of the libraries are:

[dependencies]
rocket = { version = "0.5.0-rc.2", features = ["json"] }
diesel = { version = "2.0.0", features = ["postgres"] }

[dependencies.rocket_sync_db_pools]
version = "0.1.0-rc.2"
features = ["diesel_postgres_pool"]

However, the error that shows up from the conn variable in the 2nd version that uses rocket_sync_db_pools is as the question post title describes it. The resources that I have tried to use are:

  1. Official Rocket documentation for states
  2. Official rocket_sync_db_pools documentation
  3. Stackoverflow question regarding connection pools
  4. An example in official rocket GitHub that does not work
Yukera
  • 71
  • 5

0 Answers0