Search code examples
rustrust-dieselrust-rocket

How to get the database Connection in rocket.rs Fairing


How can I access the database in a Fairing in Rust Rocket (0.5-rc1) with rocket_sync_db_pools?

In routes, I can just request it as a parameter like so:

#[get("/")]
pub async fn index(db: Database) -> Json<Index> {
    ...
}

But when registering an AdHoc Fairing, how would I ask for the Database?

rocket::build()
    .attach(Template::fairing())
    .attach(Database::fairing())
    .attach(AdHoc::on_liftoff("Startup Check", |rocket| {
        Box::pin(async move {
            // Want to access the database here
        })
    }))
    ...

Solution

  • Found a solution: The database macro creates a get_one method for that purpose. See documentation here: https://api.rocket.rs/v0.5-rc/rocket_sync_db_pools/attr.database.html

    It can be used like so:

    #[database("db")]
    pub struct Database(diesel::SqliteConnection);
    
    rocket::build()
        .attach(Template::fairing())
        .attach(Database::fairing())
        .attach(AdHoc::on_liftoff("Startup Check", |rocket| {
            Box::pin(async move {
                let db = Database::get_one(rocket).await.unwrap();
                // use db instance ...
            })
        }))
        ...