diff --git a/.changes/sql-allow-blocking-without-nested-runtime.md b/.changes/sql-allow-blocking-without-nested-runtime.md new file mode 100644 index 0000000000..ff2c773fea --- /dev/null +++ b/.changes/sql-allow-blocking-without-nested-runtime.md @@ -0,0 +1,5 @@ +--- +"sql": "patch" +--- + +Allow blocking on async code without creating a nested runtime. diff --git a/plugins/sql/src/lib.rs b/plugins/sql/src/lib.rs index 352ffbec5e..c310df296c 100644 --- a/plugins/sql/src/lib.rs +++ b/plugins/sql/src/lib.rs @@ -104,6 +104,15 @@ impl MigrationSource<'static> for MigrationList { } } +/// Allows blocking on async code without creating a nested runtime. +fn run_async_command(cmd: F) -> F::Output { + if tokio::runtime::Handle::try_current().is_ok() { + tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(cmd)) + } else { + tauri::async_runtime::block_on(cmd) + } +} + /// Tauri SQL plugin builder. #[derive(Default)] pub struct Builder { @@ -138,7 +147,7 @@ impl Builder { .setup(|app, api| { let config = api.config().clone().unwrap_or_default(); - tauri::async_runtime::block_on(async move { + run_async_command(async move { let instances = DbInstances::default(); let mut lock = instances.0.write().await; @@ -166,7 +175,7 @@ impl Builder { }) .on_event(|app, event| { if let RunEvent::Exit = event { - tauri::async_runtime::block_on(async move { + run_async_command(async move { let instances = &*app.state::(); let instances = instances.0.read().await; for value in instances.values() {