I would like to initialize SeaOrm database connection in sync for easier usage inside application and testing, but not sure how to do it without error. I'm fine with any type of blocking as this happens only once. For testing #[tokio::test]
is used.
In current example I get following 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.
#[tokio::main]
async fn main() {
let database_service = DatabaseService::init();
}
pub struct DatabaseService {
pub connection: DatabaseConnection,
}
impl DatabaseService {
pub fn init() -> Self {
let connection_options = ConnectOptions::new(&API_ENV.db_url);
// tokio::runtime::Runtime::new() also gives similar error
let connection = Handle::try_current()
.expect("Can't get tokio runtime")
.block_on(async { sea_orm::SqlxPostgresConnector::connect(connection_options).await })
.expect("Can't connect to database");
Self { connection }
}
}
This is working with additional deps, but hangs in tests #[tokio::test]
probably due to this:
// futures = "0.3.31"
// futures-executor = "0.3.31"
let connection = futures::executor::block_on(sea_orm::SqlxPostgresConnector::connect(
connection_options,
))
.expect("Can't connect to database");
async
... the only calling contexts you mention or show are async (#[tokio::main]
and#[tokio::test]
).