How to run Diesel migrations with rocket_db_pools and async? #2640
-
I started to upgrade my project to rc.4 (which went fine by the way), and I just realized there's now support for Async Postgresql with Diesel, so I tried to refactor my code to use that as well. I had some issues figuring out that I need to rewrite my imports to use rocket_db_pools::diesel instead of diesel to get the async variants, but after fixing that, it started to work. The only issue I have left is how to run the Diesel migrations automatically on startup? I found the example using fairings to do it, but I cannot get it to work properly with async Diesel connection pool. Here's what I got: use diesel_migrations::{FileBasedMigrations, MigrationHarness};
use rocket::{fairing, Build, Rocket};
use rocket_db_pools::diesel::dsl::*;
use rocket_db_pools::diesel::prelude::*;
use rocket_db_pools::diesel::RunQueryDsl;
use rocket_db_pools::{Connection, Database};
pub type ConnPool = rocket_db_pools::diesel::PgPool;
#[derive(Database)]
#[database("my_db")]
pub struct Db(ConnPool);
pub async fn run_migrations(rocket: Rocket<Build>) -> fairing::Result {
let migrations = FileBasedMigrations::find_migrations_directory().expect("migrations directory not found");
match Db::fetch(&rocket) {
Some(mut db) => match db.0.run_migrations(migrations) {
Ok(_) => {
info!("Migrations executed successfully");
Ok(rocket)
},
Err(e) => {
error!("Migrations failed! Error: {:?}", e);
Err(rocket)
},
},
None => Err(rocket),
}
}
...
fn build_rocket() -> Rocket<Build> {
rocket::build()
.attach(Db::init())
.attach(AdHoc::try_on_ignite("Diesel Migrations", run_migrations))
.mount("/", routes![index, favicon])
} I tried both
and
Any ideas how to get it working? What I find strange is that the run_migrations function is actually sync, is that normal? Or am I trying to call the wrong function here and there should be an async equivalent? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Ahh I think I found the issue: (also I realized I should have used I'll take a look at how straightforward the upgrade is, and open a PR if possible. |
Beta Was this translation helpful? Give feedback.
-
I tried replicating the example in So I still don't have any idea how to run pending migrations with async Diesel, any help is appreciated! |
Beta Was this translation helpful? Give feedback.
-
Sorry for leaving this open for so long, the solution in the linked PR works (although it's still not merged) |
Beta Was this translation helpful? Give feedback.
Check out #2648, where @ThouCheese uses diesel-async with migrations.