Blocking for async on drop

I am creating a new database in Postgres every time there's a new integration test being executed and I would like to drop the database when the struct that does the work gets dropped.

I know async drop is not supported and apparently the next best thing is to spawn a new async and block on it. I haven't been able to achieve that using tokio runtime.

Here's a bit of the code as it stands right now:

impl Drop for PgPersistenceProvider {
    fn drop(&mut self) {
        let persistence = self.persistence.clone();
        println!("Spawning task...");
        let task = tokio::spawn(async move {
            let pool = persistence.pool.clone();
            let conn = pool.get().await.unwrap();
            println!("Selecting database...");
            let database: String = conn
                .query_one("SELECT current_database()", &[])
                .await
                .unwrap()
                .get(0);
            let sql = format!("DROP DATABASE {}", database);
            println!("Dropping database {}...", database);
            conn.execute(&sql, &[]).await.unwrap();
        });
        println!("Waiting on task...");
        let handle = Handle::current().clone();
        handle.block_on(task).unwrap();
    }
}

Every time I try to run it, regardless of how I try to create or acquire the current Tokio runtime, I get an error:

Cannot start a runtime from within a runtime. 
This happens because a function (like `block_on`) attempted to block 
the current thread while the thread is being used to drive asynchronous tasks.

Is there a way to get a hold of the current executing runtime and leverage that to block on the async?

Thanks!

You could use block_in_place, but generally I would just recommend that you don't do this.

1 Like