diff --git a/.changes/fix-sql-blocking.md b/.changes/fix-sql-blocking.md new file mode 100644 index 000000000..518f02a5c --- /dev/null +++ b/.changes/fix-sql-blocking.md @@ -0,0 +1,5 @@ +--- +sql: patch +--- + +Replace `Mutex` with `RwLock` to enable concurrent SQL execution. \ No newline at end of file diff --git a/plugins/sql/src/commands.rs b/plugins/sql/src/commands.rs index 8cd90e9c5..760d00b2d 100644 --- a/plugins/sql/src/commands.rs +++ b/plugins/sql/src/commands.rs @@ -23,7 +23,7 @@ pub(crate) async fn load( pool.migrate(&migrator).await?; } - db_instances.0.lock().await.insert(db.clone(), pool); + db_instances.0.write().await.insert(db.clone(), pool); Ok(db) } @@ -36,7 +36,7 @@ pub(crate) async fn close( db_instances: State<'_, DbInstances>, db: Option, ) -> Result { - let mut instances = db_instances.0.lock().await; + let instances = db_instances.0.read().await; let pools = if let Some(db) = db { vec![db] @@ -45,9 +45,7 @@ pub(crate) async fn close( }; for pool in pools { - let db = instances - .get_mut(&pool) - .ok_or(Error::DatabaseNotLoaded(pool))?; + let db = instances.get(&pool).ok_or(Error::DatabaseNotLoaded(pool))?; db.close().await; } @@ -62,9 +60,9 @@ pub(crate) async fn execute( query: String, values: Vec, ) -> Result<(u64, LastInsertId), crate::Error> { - let mut instances = db_instances.0.lock().await; + let instances = db_instances.0.read().await; - let db = instances.get_mut(&db).ok_or(Error::DatabaseNotLoaded(db))?; + let db = instances.get(&db).ok_or(Error::DatabaseNotLoaded(db))?; db.execute(query, values).await } @@ -75,8 +73,8 @@ pub(crate) async fn select( query: String, values: Vec, ) -> Result>, crate::Error> { - let mut instances = db_instances.0.lock().await; + let instances = db_instances.0.read().await; - let db = instances.get_mut(&db).ok_or(Error::DatabaseNotLoaded(db))?; + let db = instances.get(&db).ok_or(Error::DatabaseNotLoaded(db))?; db.select(query, values).await } diff --git a/plugins/sql/src/lib.rs b/plugins/sql/src/lib.rs index f66137b8e..352ffbec5 100644 --- a/plugins/sql/src/lib.rs +++ b/plugins/sql/src/lib.rs @@ -29,12 +29,12 @@ use tauri::{ plugin::{Builder as PluginBuilder, TauriPlugin}, Manager, RunEvent, Runtime, }; -use tokio::sync::Mutex; +use tokio::sync::{Mutex, RwLock}; use std::collections::HashMap; #[derive(Default)] -pub struct DbInstances(pub Mutex>); +pub struct DbInstances(pub RwLock>); #[derive(Serialize)] #[serde(untagged)] @@ -140,7 +140,7 @@ impl Builder { tauri::async_runtime::block_on(async move { let instances = DbInstances::default(); - let mut lock = instances.0.lock().await; + let mut lock = instances.0.write().await; for db in config.preload { let pool = DbPool::connect(&db, app).await?; @@ -168,7 +168,7 @@ impl Builder { if let RunEvent::Exit = event { tauri::async_runtime::block_on(async move { let instances = &*app.state::(); - let instances = instances.0.lock().await; + let instances = instances.0.read().await; for value in instances.values() { value.close().await; }