diff --git a/src-tauri/src/commands/db_pool_commands.rs b/src-tauri/src/commands/db_pool_commands.rs index 7f3070c..8c38243 100644 --- a/src-tauri/src/commands/db_pool_commands.rs +++ b/src-tauri/src/commands/db_pool_commands.rs @@ -92,7 +92,9 @@ mod tests { use super::*; use rusqlite::Connection; use sqlx::Executor; + use std::future::Future; use std::path::{Path, PathBuf}; + use std::task::Poll; /// The URL `Database.load` gives the plugin: the key of its `DbInstances`. const URL: &str = "sqlite:profile_0a1b2c3d.db"; @@ -423,6 +425,32 @@ mod tests { single.close().await; } + /// A statement that arrives while the new pool opens waits for the swap, + /// then runs on the new pool, never on the plugin's: the plugin's + /// `execute` and `select` look their pool up under the read lock of + /// `DbInstances`, which the swap holds in write mode from the read of the + /// plugin's options to the insert of the new pool. + #[tokio::test(flavor = "current_thread")] + async fn a_statement_sent_while_the_new_pool_opens_runs_on_the_new_pool() { + let dir = TestDir::new("held-lock"); + let (instances, _plugin) = plugin_pool(&profile_db(&dir)).await; + let mut swap = Box::pin(swap_in_single_connection_pool(&instances, URL)); + // One poll: the swap runs up to its first wait, the opening of the new + // pool, whose connection sqlx opens on a thread of its own. + let first = std::future::poll_fn(|cx| Poll::Ready(swap.as_mut().poll(cx))).await; + assert!(first.is_pending(), "the new pool opens on a thread of its own"); + + // What the plugin's `execute` and `select` do first. + let statement = async { + let pools = instances.0.read().await; + let DbPool::Sqlite(pool) = pools.get(URL).expect("a pool stored for URL"); + pool.options().get_max_connections() + }; + let (swapped, connections) = tokio::join!(swap, statement); + swapped.unwrap(); + assert_eq!(connections, 1, "the statement found the plugin's pool while the new one opened"); + } + #[tokio::test(flavor = "current_thread")] async fn the_swap_refuses_a_database_not_loaded_or_closed_and_keeps_the_map() { let dir = TestDir::new("refusals");