From 90ef77c8723ac9d0ba7bd3b52a80a2b14843ff99 Mon Sep 17 00:00:00 2001 From: John Carmack Date: Wed, 13 Nov 2024 07:58:50 -0800 Subject: [PATCH] fix(sql) Allow tauri-plugin-sql to work when Tauri is running async (#2038) --- .../sql-allow-blocking-without-nested-runtime.md | 5 +++++ plugins/sql/src/lib.rs | 13 +++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 .changes/sql-allow-blocking-without-nested-runtime.md 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 000000000..ff2c773fe --- /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 e19b72a78..56b2a3a6b 100644 --- a/plugins/sql/src/lib.rs +++ b/plugins/sql/src/lib.rs @@ -102,6 +102,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 { @@ -136,7 +145,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; @@ -164,7 +173,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() {