From ba48ecd35679cee523e261317d32153e9280268e Mon Sep 17 00:00:00 2001 From: le king fu Date: Thu, 12 Nov 2026 20:34:54 -0500 Subject: [PATCH] fix(db): run every statement on one connection of the plugin's pool (#543) tauri-plugin-sql opens each database with Pool::connect, a sqlx pool of up to ten connections, and sqlx gives a connection back to its pool through a spawned task. Two statements sent back to back made the pool open a second connection and serve both in turn, so a transaction of withTransaction was split: its BEGIN and first write on one connection, a later write on the other, which waited for the first one's write lock and failed with "database is locked" (code 5) after 5 s. Adding a keyword from the right-click menu (six statements) and creating a sub-category hit it; the 14 withTransaction call sites were exposed. Right after Database.load, inside the exclusive section that opens a profile, loadUnlocked now calls use_single_connection_pool, a new Tauri command (db_pool_commands.rs) that replaces the plugin's DbPool::Sqlite in DbInstances by a pool of one connection, never recycled, opened with the plugin pool's own connect options, then closes the plugin's pool. getDb() and withTransaction find the connection only once the switch succeeded; a failed switch writes a folder-free Journal line, closes the plugin's pool and fails the opening. sqlx 0.8.6 becomes a direct dependency with features the plugin already enables: Cargo.lock only gains the edge, no package. test: reproduces #543. The Rust tests replay, on a real sqlx pool opened like the plugin's, the statements of a keyword on one then two checked transactions (one split) and of a sub-category: code 5 on the plugin's pool, green after the swap (6 of 6 red on a no-op swap). db.test.ts pins the place of the switch and its failure path. Fixes #543 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.fr.md | 4 + CHANGELOG.md | 4 + src-tauri/Cargo.lock | 1 + src-tauri/Cargo.toml | 4 + src-tauri/src/commands/db_pool_commands.rs | 473 +++++++++++++++++++++ src-tauri/src/commands/mod.rs | 2 + src-tauri/src/lib.rs | 1 + src/services/db.test.ts | 213 +++++++++- src/services/db.ts | 76 +++- 9 files changed, 744 insertions(+), 34 deletions(-) create mode 100644 src-tauri/src/commands/db_pool_commands.rs diff --git a/CHANGELOG.fr.md b/CHANGELOG.fr.md index 1eb42ab..e2c0a9d 100644 --- a/CHANGELOG.fr.md +++ b/CHANGELOG.fr.md @@ -2,6 +2,10 @@ ## [Non publié] +### Corrigé + +- L'ajout d'un mot-clé par le clic droit sur une transaction, la création d'une catégorie et les autres enregistrements en plusieurs étapes, comme une répartition ou une restauration, ne peuvent plus échouer sur « database is locked » (#543). + ## [0.18.0] - 2026-11-10 ### Ajouté diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f0d6bf..2cd7515 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +### Fixed + +- Adding a keyword from a transaction's right-click menu, creating a category, and the other saves made in several steps, such as a split or a restore, can no longer fail with “database is locked” (#543). + ## [0.18.0] - 2026-11-10 ### Added diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index a846f1c..5b57449 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -4510,6 +4510,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "sqlx", "subtle", "tauri", "tauri-build", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 6d16b61..e28b158 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -22,6 +22,10 @@ tauri-build = { version = "2", features = [] } tauri = { version = "2", features = [] } tauri-plugin-opener = "2" tauri-plugin-sql = { version = "2", features = ["sqlite"] } +# The sqlx of tauri-plugin-sql, named directly to replace the plugin's pool by +# a pool of one connection (#543, ADR 0027, db_pool_commands.rs). Same version +# as the plugin's, and only features it already enables: no new crate. +sqlx = { version = "0.8.6", default-features = false, features = ["sqlite", "runtime-tokio"] } tauri-plugin-dialog = "2" # Built without its default `zip` feature (#455): that feature only pulls # `zip` on Windows and `tar` on Linux to unpack archived update packages, and diff --git a/src-tauri/src/commands/db_pool_commands.rs b/src-tauri/src/commands/db_pool_commands.rs new file mode 100644 index 0000000..7f3070c --- /dev/null +++ b/src-tauri/src/commands/db_pool_commands.rs @@ -0,0 +1,473 @@ +//! The SQLite pool behind the webview's queries (#543, ADR 0027). +//! +//! tauri-plugin-sql opens a database with `Pool::connect`, a sqlx pool of up +//! to ten connections, and runs every `execute` or `select` of the webview as +//! a fresh acquire from it. sqlx gives a connection back to its pool through a +//! spawned task: when the next statement arrives before that task ran, the +//! pool finds no idle connection, opens a second one, and from then on serves +//! the two in turn. A transaction driven from TypeScript (`withTransaction`, +//! `src/services/db.ts`) is then split: its `BEGIN` and a first write on one +//! connection, a later write on the other, which waits for the first one's +//! write lock and fails with "database is locked" (SQLite code 5) after the +//! 5 s busy timeout. The FIFO lock of `db.ts` orders the statements; it cannot +//! choose their connection. +//! +//! `use_single_connection_pool` closes that gap: right after `Database.load`, +//! before any statement, it replaces the plugin's pool by a pool of ONE +//! connection on the same database, so every statement of the profile runs on +//! that connection, whatever the timing. It relies on `DbInstances` and +//! `DbPool`, public but undocumented parts of tauri-plugin-sql: a bump of the +//! plugin or of sqlx re-checks them (ADR 0027, `REVIEW.md` « Dépendances »). + +use sqlx::sqlite::{SqlitePool, SqlitePoolOptions}; +use tauri::State; +use tauri_plugin_sql::{DbInstances, DbPool}; + +/// Options of the pool that replaces the plugin's: one connection, which sqlx +/// never closes on its own. With its defaults, sqlx closes a connection idle +/// for 10 minutes, or older than 30 minutes when it comes back to the pool: +/// closed between two statements of a transaction, the connection would cut +/// it as surely as a second one. +pub(crate) fn single_connection_pool_options() -> SqlitePoolOptions { + SqlitePoolOptions::new() + .max_connections(1) + .idle_timeout(None) + .max_lifetime(None) +} + +/// Replace the pool stored under `db` in `instances` by a pool of one +/// connection on the same database, then close the replaced pool. On a +/// refusal or a failure, `instances` is left as it was. +pub(crate) async fn swap_in_single_connection_pool( + instances: &DbInstances, + db: &str, +) -> Result<(), String> { + // Held while the new pool opens: no statement of the webview reaches + // either pool between the read of the plugin's options and the swap. + let mut pools = instances.0.write().await; + // `Sqlite` is the only variant with the plugin's `sqlite` feature, the + // only one this app enables: if the plugin's enum changes, this line stops + // compiling, and the switch is re-checked (ADR 0027). + let DbPool::Sqlite(current) = pools + .get(db) + .ok_or_else(|| format!("database_not_loaded: {db}"))?; + // A pool closed by the plugin's `close` stays in its map: reopening it + // here would bring back a profile the app has closed. + if current.is_closed() { + return Err(format!("database_closed: {db}")); + } + // The plugin's own options: same file, same pragmas (5 s busy timeout, + // foreign keys on), without resolving the path a second time. + let options = current.connect_options().as_ref().clone(); + let single: SqlitePool = single_connection_pool_options() + .connect_with(options) + .await + .map_err(|e| format!("single_connection_pool_failed: {e}"))?; + let replaced = pools.insert(db.to_string(), DbPool::Sqlite(single)); + drop(pools); + if let Some(DbPool::Sqlite(replaced)) = replaced { + replaced.close().await; + } + Ok(()) +} + +/// Replace the pool tauri-plugin-sql opened for `db`, the `sqlite:` URL given +/// to `Database.load`, by a pool of one connection on the same database, then +/// close the plugin's pool (#543, ADR 0027). `loadUnlocked` +/// (`src/services/db.ts`) calls it right after `Database.load`, before any +/// statement, and fails the opening of the profile when it fails. Errors: +/// `database_not_loaded: `, `database_closed: `, or +/// `single_connection_pool_failed: `; in all three, the plugin's +/// pool stays where it was, and no message names a folder. +#[tauri::command] +pub async fn use_single_connection_pool( + db_instances: State<'_, DbInstances>, + db: String, +) -> Result<(), String> { + swap_in_single_connection_pool(&db_instances, &db).await +} + +#[cfg(test)] +mod tests { + use super::*; + use rusqlite::Connection; + use sqlx::Executor; + use std::path::{Path, PathBuf}; + + /// The URL `Database.load` gives the plugin: the key of its `DbInstances`. + const URL: &str = "sqlite:profile_0a1b2c3d.db"; + + /// A folder of its own for each test (cargo runs the tests on parallel + /// threads, so the 5 s busy timeouts of the red replays overlap), removed + /// when the test ends, failed assertion included. + struct TestDir(PathBuf); + + impl TestDir { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!( + "simpl-resultat-db-pool-{}-{}", + name, + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + TestDir(dir) + } + } + + impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + /// The rows the replays touch, on top of the seed: 90001 receives the + /// keyword `MARCHE LAVAL`, which the seed does not hold (the lookup finds + /// nothing and the service inserts it), 90002 is a top-level category with + /// nothing in it (a new sub-category makes it a parent), transaction 1 is + /// a plain one, and 2 is a split parent with its entry (3, sent to 90004) + /// and its offset line (4, same description, opposite sign: + /// `isOffsetChild`). + const FIXTURE: &str = " + INSERT INTO categories (id, name, type, is_inputable, sort_order) VALUES + (90001, 'Epicerie', 'expense', 1, 90), + (90002, 'Maison', 'expense', 1, 91), + (90003, 'Divers', 'expense', 1, 92), + (90004, 'Pharmacie', 'expense', 1, 93); + INSERT INTO transactions (id, date, description, amount, category_id, is_split, parent_transaction_id) VALUES + (1, '2026-10-05', 'MARCHE LAVAL 0042', -25.5, NULL, 0, NULL), + (2, '2026-10-06', 'MARCHE LAVAL', -100.0, 90003, 1, NULL), + (3, '2026-10-06', 'MARCHE LAVAL', -40.0, 90004, 1, 2), + (4, '2026-10-06', 'MARCHE LAVAL', 40.0, 90003, 1, 2); + "; + + /// A profile database as a new profile gets it (`consolidated_schema.sql`, + /// seed included), plus `FIXTURE`, written in one transaction: one sync to + /// disk instead of one per statement of the seed. + fn profile_db(dir: &TestDir) -> PathBuf { + let path = dir.0.join("profile_0a1b2c3d.db"); + let conn = Connection::open(&path).unwrap(); + conn.execute_batch("BEGIN").unwrap(); + conn.execute_batch(crate::database::CONSOLIDATED_SCHEMA).unwrap(); + conn.execute_batch(FIXTURE).unwrap(); + conn.execute_batch("COMMIT").unwrap(); + path + } + + /// The pool tauri-plugin-sql opens (`wrapper.rs`: `Pool::connect` on + /// `sqlite:`, so sqlx's defaults: ten connections, 5 s busy timeout, + /// foreign keys on), stored in a `DbInstances` under the URL, as its + /// `load` command stores it. + async fn plugin_pool(path: &Path) -> (DbInstances, SqlitePool) { + let pool = SqlitePool::connect(&format!("sqlite:{}", path.display())) + .await + .unwrap(); + let instances = DbInstances::default(); + instances + .0 + .write() + .await + .insert(URL.to_string(), DbPool::Sqlite(pool.clone())); + (instances, pool) + } + + /// The pool `instances` holds for `URL`. + async fn stored_pool(instances: &DbInstances) -> SqlitePool { + let pools = instances.0.read().await; + let DbPool::Sqlite(pool) = pools.get(URL).expect("a pool stored for URL"); + pool.clone() + } + + /// A value bound as tauri-plugin-sql binds what the webview sends + /// (`wrapper.rs`): every number as an `f64`, a string as a `String`. + #[derive(Clone, Copy)] + enum Arg { + Num(f64), + Text(&'static str), + } + + /// One `execute` or `select` of the webview. + struct Statement { + select: bool, + sql: &'static str, + args: Vec, + } + + fn execute(sql: &'static str, args: &[Arg]) -> Statement { + Statement { select: false, sql, args: args.to_vec() } + } + + fn select(sql: &'static str, args: &[Arg]) -> Statement { + Statement { select: true, sql, args: args.to_vec() } + } + + /// Run `statements` as `db.ts` and the plugin do: each one a fresh + /// `execute` or `fetch_all` on the pool, back to back, without any pause. + /// On the first error, a ROLLBACK whatever its own outcome, as the + /// TypeScript callbacks do, then that first error. + async fn replay(pool: &SqlitePool, statements: &[Statement]) -> Result<(), sqlx::Error> { + for statement in statements { + let mut query = sqlx::query(statement.sql); + for arg in &statement.args { + query = match *arg { + Arg::Num(n) => query.bind(n), + Arg::Text(t) => query.bind(t.to_owned()), + }; + } + let outcome = if statement.select { + pool.fetch_all(query).await.map(|_| ()) + } else { + pool.execute(query).await.map(|_| ()) + }; + if let Err(error) = outcome { + let _ = pool.execute("ROLLBACK").await; + return Err(error); + } + } + Ok(()) + } + + /// SQLite's result code of a failed statement: "5" is `SQLITE_BUSY`, + /// "database is locked". + fn sqlite_code(error: &sqlx::Error) -> Option { + error + .as_database_error() + .and_then(|e| e.code()) + .map(|code| code.into_owned()) + } + + fn count(conn: &Connection, sql: &str) -> i64 { + conn.query_row(sql, [], |row| row.get(0)).unwrap() + } + + /// `category_id` and `is_manually_categorized` of a transaction. + fn categorized(conn: &Connection, id: i64) -> (Option, i64) { + conn.query_row( + "SELECT category_id, is_manually_categorized FROM transactions WHERE id = ?1", + [id], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap() + } + + // The statements of the services, as they send them (#543). A change of + // these services does not reach this file: the replays pin the sequences + // of the issue, the shape a transaction of `withTransaction` takes. + + // categorizationService.ts, applyKeywordInTransaction + const KEYWORD_LOOKUP: &str = "SELECT id, category_id FROM keywords WHERE keyword = $1 LIMIT 1"; + const KEYWORD_INSERT: &str = "INSERT INTO keywords (keyword, category_id, priority) VALUES ($1, $2, $3)"; + const RECATEGORIZE: &str = "UPDATE transactions SET category_id = $1, is_manually_categorized = 1, updated_at = CURRENT_TIMESTAMP WHERE id = $2 AND parent_transaction_id IS NULL"; + // splitOffsetService.ts, propagateCategoryToOffsets + const SPLIT_PARENT: &str = "SELECT id, description, amount, is_split, is_manually_categorized, parent_transaction_id FROM transactions WHERE id = $1"; + const SPLIT_CHILDREN: &str = "SELECT id, description, amount FROM transactions WHERE parent_transaction_id = $1 ORDER BY id"; + const OFFSET_FOLLOWS: &str = "UPDATE transactions SET category_id = $1, is_manually_categorized = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3"; + // categoryService.ts, getCategoryDepth then createCategory + const CATEGORY_DEPTH: &str = "SELECT parent_id FROM categories WHERE id = $1 AND is_active = 1"; + const HIERARCHY_ROWS: &str = "SELECT id, parent_id, is_active, is_inputable FROM categories"; + const PARENT_HAS_TRANSACTIONS: &str = "SELECT COUNT(*) AS cnt FROM transactions WHERE category_id = $1"; + const PARENT_HAS_BUDGET: &str = "SELECT (SELECT COUNT(*) FROM budget_entries WHERE category_id = $1 AND amount <> 0) + (SELECT COUNT(*) FROM budget_template_entries WHERE category_id = $1 AND amount <> 0) AS cnt"; + const PARENT_HAS_KEYWORDS: &str = "SELECT COUNT(*) AS cnt FROM keywords WHERE category_id = $1 AND is_active = 1"; + const CATEGORY_INSERT: &str = "INSERT INTO categories (name, type, color, parent_id, is_inputable, sort_order) VALUES ($1, $2, $3, $4, $5, $6)"; + const MARK_AS_PARENT: &str = "UPDATE categories SET is_inputable = 0 WHERE id = $1 AND is_inputable = 1"; + + /// Max's case (#543): a new keyword from the right-click menu, one plain + /// transaction checked. Six statements. + fn keyword_on_one_transaction() -> Vec { + use Arg::*; + vec![ + execute("BEGIN", &[]), + select(KEYWORD_LOOKUP, &[Text("MARCHE LAVAL")]), + execute(KEYWORD_INSERT, &[Text("MARCHE LAVAL"), Num(90001.0), Num(100.0)]), + execute(RECATEGORIZE, &[Num(90001.0), Num(1.0)]), + select(SPLIT_PARENT, &[Num(1.0)]), + execute("COMMIT", &[]), + ] + } + + /// The same keyword on two checked transactions, the plain one and the + /// split parent, whose offset line follows it (#454). + fn keyword_on_two_transactions() -> Vec { + use Arg::*; + vec![ + execute("BEGIN", &[]), + select(KEYWORD_LOOKUP, &[Text("MARCHE LAVAL")]), + execute(KEYWORD_INSERT, &[Text("MARCHE LAVAL"), Num(90001.0), Num(100.0)]), + execute(RECATEGORIZE, &[Num(90001.0), Num(1.0)]), + select(SPLIT_PARENT, &[Num(1.0)]), + execute(RECATEGORIZE, &[Num(90001.0), Num(2.0)]), + select(SPLIT_PARENT, &[Num(2.0)]), + select(SPLIT_CHILDREN, &[Num(2.0)]), + execute(OFFSET_FOLLOWS, &[Num(90001.0), Num(1.0), Num(4.0)]), + execute("COMMIT", &[]), + ] + } + + /// A sub-category under 90002, the second case of the issue (comment + /// 33076): the depth read through `getDb()` before the transaction, then + /// the hierarchy, the three counts of `checkParentContent` (90002 still + /// takes input), the row, and `markAsParent`. + fn sub_category() -> Vec { + use Arg::*; + vec![ + select(CATEGORY_DEPTH, &[Num(90002.0)]), + execute("BEGIN", &[]), + select(HIERARCHY_ROWS, &[]), + select(PARENT_HAS_TRANSACTIONS, &[Num(90002.0)]), + select(PARENT_HAS_BUDGET, &[Num(90002.0)]), + select(PARENT_HAS_KEYWORDS, &[Num(90002.0)]), + execute( + CATEGORY_INSERT, + &[Text("Quincaillerie"), Text("expense"), Text("#64748b"), Num(90002.0), Num(1.0), Num(1.0)], + ), + execute(MARK_AS_PARENT, &[Num(90002.0)]), + execute("COMMIT", &[]), + ] + } + + /// The regression test of #543. On the pool tauri-plugin-sql opens, the + /// statements of one transaction, sent back to back, end on code 5 + /// ("database is locked"): the pool opened a second connection. On a fresh + /// copy of the same database whose pool was swapped, the same statements + /// all run, on one connection, and `check` reads what they wrote. + /// + /// The callers run on a `current_thread` runtime, where the red is certain + /// rather than likely: the task that returns a connection to the pool only + /// runs when the test yields, so the next statement always finds the pool + /// without an idle connection, and the two connections then alternate. On + /// Tauri's multi-thread runtime, the same race depends on timing, which is + /// why the defect only showed now and then. + async fn split_by_the_plugin_pool_then_whole_after_the_swap( + name: &str, + statements: Vec, + check: impl Fn(&Connection), + ) { + let before = TestDir::new(&format!("{name}-before")); + let (_instances, plugin) = plugin_pool(&profile_db(&before)).await; + let error = replay(&plugin, &statements) + .await + .expect_err("the plugin's pool splits the transaction"); + assert_eq!(sqlite_code(&error).as_deref(), Some("5"), "{error}"); + assert!(plugin.size() >= 2, "a second connection: {}", plugin.size()); + plugin.close().await; + + let after = TestDir::new(&format!("{name}-after")); + let path = profile_db(&after); + let (instances, _plugin) = plugin_pool(&path).await; + swap_in_single_connection_pool(&instances, URL).await.unwrap(); + let single = stored_pool(&instances).await; + replay(&single, &statements) + .await + .expect("one connection keeps the transaction whole"); + assert_eq!(single.size(), 1); + single.close().await; + check(&Connection::open(&path).unwrap()); + } + + #[tokio::test(flavor = "current_thread")] + async fn a_keyword_on_one_checked_transaction_saves_on_one_connection() { + split_by_the_plugin_pool_then_whole_after_the_swap("keyword-one", keyword_on_one_transaction(), |conn| { + assert_eq!(count(conn, "SELECT COUNT(*) FROM keywords WHERE keyword = 'MARCHE LAVAL'"), 1); + assert_eq!(categorized(conn, 1), (Some(90001), 1)); + }) + .await; + } + + #[tokio::test(flavor = "current_thread")] + async fn a_keyword_on_several_checked_transactions_moves_the_offset_line_too() { + split_by_the_plugin_pool_then_whole_after_the_swap("keyword-two", keyword_on_two_transactions(), |conn| { + assert_eq!(count(conn, "SELECT COUNT(*) FROM keywords WHERE keyword = 'MARCHE LAVAL'"), 1); + assert_eq!(categorized(conn, 1), (Some(90001), 1)); + assert_eq!(categorized(conn, 2), (Some(90001), 1)); + // The entry keeps its category, the offset line follows its parent. + assert_eq!(categorized(conn, 3), (Some(90004), 0)); + assert_eq!(categorized(conn, 4), (Some(90001), 1)); + }) + .await; + } + + #[tokio::test(flavor = "current_thread")] + async fn a_sub_category_saves_on_one_connection() { + split_by_the_plugin_pool_then_whole_after_the_swap("sub-category", sub_category(), |conn| { + assert_eq!( + count(conn, "SELECT COUNT(*) FROM categories WHERE name = 'Quincaillerie' AND parent_id = 90002"), + 1 + ); + assert_eq!(count(conn, "SELECT is_inputable FROM categories WHERE id = 90002"), 0); + }) + .await; + } + + #[tokio::test(flavor = "current_thread")] + async fn the_swap_keeps_the_file_and_pragmas_and_closes_the_plugin_pool() { + let dir = TestDir::new("swap"); + let (instances, plugin) = plugin_pool(&profile_db(&dir)).await; + swap_in_single_connection_pool(&instances, URL).await.unwrap(); + + assert!(plugin.is_closed()); + let single = stored_pool(&instances).await; + assert!(!single.is_closed()); + let options = single.options(); + assert_eq!(options.get_max_connections(), 1); + assert_eq!(options.get_idle_timeout(), None); + assert_eq!(options.get_max_lifetime(), None); + assert_eq!( + single.connect_options().get_filename(), + plugin.connect_options().get_filename() + ); + // The plugin's pragmas: 5 s busy timeout, foreign keys on. + let busy: i64 = sqlx::query_scalar("PRAGMA busy_timeout").fetch_one(&single).await.unwrap(); + let foreign_keys: i64 = sqlx::query_scalar("PRAGMA foreign_keys").fetch_one(&single).await.unwrap(); + assert_eq!((busy, foreign_keys), (5000, 1)); + assert_eq!(instances.0.read().await.len(), 1); + single.close().await; + } + + #[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"); + let (instances, plugin) = plugin_pool(&profile_db(&dir)).await; + + assert_eq!( + swap_in_single_connection_pool(&instances, "sqlite:profile_ffffffff.db").await, + Err("database_not_loaded: sqlite:profile_ffffffff.db".to_string()) + ); + let stored = stored_pool(&instances).await; + assert_eq!(stored.options().get_max_connections(), 10, "still the plugin's pool"); + assert!(!plugin.is_closed()); + + // What the plugin's `close` command does: the pool stays in the map, closed. + plugin.close().await; + assert_eq!( + swap_in_single_connection_pool(&instances, URL).await, + Err(format!("database_closed: {URL}")) + ); + let stored = stored_pool(&instances).await; + assert!(stored.is_closed(), "the closed pool, not a reopened one"); + assert_eq!(stored.options().get_max_connections(), 10); + assert_eq!(instances.0.read().await.len(), 1); + } + + /// Unix only: Windows refuses to delete a file that a connection holds open. + #[cfg(unix)] + #[tokio::test(flavor = "current_thread")] + async fn a_replacement_that_cannot_open_leaves_the_plugin_pool_in_place() { + let dir = TestDir::new("open-fails"); + let path = profile_db(&dir); + let (instances, plugin) = plugin_pool(&path).await; + // The plugin's idle connection keeps the deleted file open; a new + // connection finds no file, and the plugin's options never create one. + std::fs::remove_file(&path).unwrap(); + + let error = swap_in_single_connection_pool(&instances, URL).await.unwrap_err(); + assert!(error.starts_with("single_connection_pool_failed: "), "{error}"); + assert!(!error.contains('/') && !error.contains('\\'), "no folder: {error}"); + + assert!(!plugin.is_closed()); + let stored = stored_pool(&instances).await; + assert_eq!(stored.options().get_max_connections(), 10, "still the plugin's pool"); + let one: i64 = sqlx::query_scalar("SELECT 1").fetch_one(&stored).await.unwrap(); + assert_eq!(one, 1); + plugin.close().await; + } +} diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 33d4d7f..b0588d2 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -2,6 +2,7 @@ pub mod account_cache; pub mod auth_commands; pub mod backup_commands; pub mod balance_commands; +pub mod db_pool_commands; pub mod entitlements; pub mod export_import_commands; pub mod feedback_commands; @@ -17,6 +18,7 @@ pub mod token_store; pub use auth_commands::*; pub use backup_commands::*; pub use balance_commands::*; +pub use db_pool_commands::*; pub use entitlements::*; pub use export_import_commands::*; pub use feedback_commands::*; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index f22a134..aee2a1f 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -461,6 +461,7 @@ pub fn run() { commands::verify_pin, commands::repair_migrations, commands::prepare_profile_db, + commands::use_single_connection_pool, commands::validate_license_key, commands::store_license, commands::remove_license, diff --git a/src/services/db.test.ts b/src/services/db.test.ts index f305085..2bef5d3 100644 --- a/src/services/db.test.ts +++ b/src/services/db.test.ts @@ -1,13 +1,17 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -// Regression coverage for the "database is locked" fix (#228 follow-up). +// Regression coverage for the "database is locked" fixes (#228 follow-up, +// #408, #543). // // tauri-plugin-sql loads SQLite through a default multi-connection sqlx pool -// and exposes no transaction primitive, so a BEGIN and its COMMIT issued as -// separate db.execute calls could land on different pooled connections and -// strand an open write transaction (= permanent lock). db.ts funnels every -// operation through one FIFO lock, and withTransaction holds it for the whole -// BEGIN..COMMIT. These tests assert that serialization, without a real SQLite. +// and exposes no transaction primitive, so the statements of one transaction, +// sent as separate db.execute calls, could land on different pooled +// connections. db.ts funnels every operation through one FIFO lock, and +// withTransaction holds it for the whole BEGIN..COMMIT; right after +// Database.load, it switches the plugin's pool to a pool of one connection +// (`use_single_connection_pool`, #543), whose own test, against a real sqlx +// pool, is in src-tauri/src/commands/db_pool_commands.rs. These tests assert +// the serialization and the place of the switch, without a real SQLite. // Ordered log of every fake-db operation's start/end, shared with the fake db. const events: string[] = []; @@ -16,6 +20,9 @@ const h = vi.hoisted(() => ({ fakeDb: null as unknown as FakeDb, // What `prepare_profile_db` answers (#390); a test may make it throw. prepare: async (): Promise => null, + // What `use_single_connection_pool` answers (#543), with the arguments it + // was given; a test may make it throw or wait. + pool: async (_args: unknown): Promise => null, })); interface FakeDb { @@ -28,7 +35,11 @@ vi.mock("@tauri-apps/plugin-sql", () => ({ default: { load: vi.fn(async () => h.fakeDb) }, })); vi.mock("@tauri-apps/api/core", () => ({ - invoke: vi.fn(async (command: string) => (command === "prepare_profile_db" ? h.prepare() : false)), + invoke: vi.fn(async (command: string, args?: unknown) => { + if (command === "prepare_profile_db") return h.prepare(); + if (command === "use_single_connection_pool") return h.pool(args); + return false; + }), })); // The path API that logFolders.ts calls (#497), mocked on its own: its real // module imports `./core.js`, so the fake invoke above would answer homeDir() @@ -78,9 +89,16 @@ function makeFakeDb(name = "db"): FakeDb { }; } +/** The switch to one connection, logged in `events` with the URL it was given (#543). */ +async function recordedSwitch(args: unknown): Promise { + events.push(`pool:${(args as { db: string }).db}`); + return null; +} + beforeEach(async () => { h.fakeDb = makeFakeDb(); h.prepare = async () => null; + h.pool = recordedSwitch; await connectToProfile("test.db"); // Cleared after connecting: the connection opens by closing the previous // test's fake, whose close is logged too. @@ -257,7 +275,14 @@ describe("profile switch goes through the lock (#408)", () => { }); await txn; await switching; - expect(events).toEqual(["start:BEGIN", "end:BEGIN", "start:COMMIT", "end:COMMIT", "close:db"]); + expect(events).toEqual([ + "start:BEGIN", + "end:BEGIN", + "start:COMMIT", + "end:COMMIT", + "close:db", + "pool:sqlite:next.db", + ]); expect(old.close).toHaveBeenCalledTimes(1); }); @@ -289,7 +314,7 @@ describe("profile switch goes through the lock (#408)", () => { }; h.fakeDb = makeFakeDb("next"); await connectToProfile("next.db"); - expect(events).toEqual(["close-start", "close-end", "prepare"]); + expect(events).toEqual(["close-start", "close-end", "prepare", "pool:sqlite:next.db"]); }); it("fails a transaction queued behind a switch instead of running it on the new database", async () => { @@ -398,6 +423,8 @@ describe("profile switch goes through the lock (#408)", () => { await after; expect(events).toEqual([ "close:db", + // The new profile's statements run on the pool of one connection (#543). + "pool:sqlite:new.db", "start:CREATE A", "end:CREATE A", "start:CREATE B", @@ -408,6 +435,117 @@ describe("profile switch goes through the lock (#408)", () => { }); }); +// --------------------------------------------------------------------------- +// The pool of one connection, switched to right after Database.load (#543) +// --------------------------------------------------------------------------- + +describe("the plugin's pool becomes a pool of one connection before any statement (#543)", () => { + const FAILED = + "single_connection_pool_failed: error returned from database: (code: 14) unable to open database file"; + const FAILED_LINE = `Profile profile_0a1b2c3d.db: switching to a single-connection pool failed, profile not opened: ${FAILED}`; + + beforeEach(() => { + vi.mocked(logError).mockClear(); + vi.mocked(logWarn).mockClear(); + }); + + it("switches right after Database.load, and the first statement runs after the switch", async () => { + h.fakeDb = makeFakeDb("next"); + await connectToProfile("profile_0a1b2c3d.db"); + await (await getDb()).select("FIRST"); + expect(events).toEqual(["close:db", "pool:sqlite:profile_0a1b2c3d.db", "start:FIRST", "end:FIRST"]); + }); + + it("gives no connection while the switch runs, so nothing reaches the plugin's pool before it", async () => { + let finish: () => void = () => {}; + h.pool = async (args) => { + await recordedSwitch(args); + await new Promise((resolve) => { + finish = resolve; + }); + return null; + }; + const next = makeFakeDb("next"); + h.fakeDb = next; + const connecting = connectToProfile("profile_0a1b2c3d.db"); + await vi.waitFor(() => expect(events).toContain("pool:sqlite:profile_0a1b2c3d.db")); + await expect(getDb()).rejects.toThrow(/No database connection/); + await expect(withTransaction(async () => "early")).rejects.toThrow(/No database connection/); + + finish(); + await connecting; + await (await getDb()).execute("AFTER"); + expect(next.execute).toHaveBeenCalledTimes(1); + expect(next.execute).toHaveBeenCalledWith("AFTER", undefined); + }); + + it("fails the opening when the switch fails: the plugin's pool is closed, no connection is left, the Journal says why", async () => { + h.pool = async () => { + throw FAILED; + }; + const failed = makeFakeDb("failed"); + h.fakeDb = failed; + + const error = await connectToProfile("profile_0a1b2c3d.db").catch((e: unknown) => e); + + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toBe(FAILED_LINE); + expect(vi.mocked(logError).mock.calls).toEqual([[FAILED_LINE]]); + expect(failed.close).toHaveBeenCalledTimes(1); + expect(failed.execute).not.toHaveBeenCalled(); + expect(failed.select).not.toHaveBeenCalled(); + await expect(getDb()).rejects.toThrow(/No database connection/); + await expect(withTransaction(async () => undefined)).rejects.toThrow(/No database connection/); + + // A retry (startupConnection makes three) opens as usual, without closing + // the failed pool a second time. + h.pool = recordedSwitch; + const again = makeFakeDb("again"); + h.fakeDb = again; + await connectToProfile("profile_0a1b2c3d.db"); + expect(failed.close).toHaveBeenCalledTimes(1); + await (await getDb()).execute("Q"); + expect(again.execute).toHaveBeenCalledWith("Q", undefined); + }); + + it("runs no statement of a new profile whose switch fails", async () => { + h.pool = async () => { + throw "single_connection_pool_failed: boom"; + }; + const fresh = makeFakeDb("new"); + h.fakeDb = fresh; + + const error = await initializeNewProfileDb("new.db", ["CREATE A", "CREATE B"]).catch((e: unknown) => e); + + expect((error as Error).message).toBe( + "Profile new.db: switching to a single-connection pool failed, profile not opened: single_connection_pool_failed: boom" + ); + expect(fresh.execute).not.toHaveBeenCalled(); + expect(fresh.close).toHaveBeenCalledTimes(1); + await expect(getDb()).rejects.toThrow(/No database connection/); + }); + + it("keeps the switch error when the plugin's pool then fails to close, and writes that failure as a warning", async () => { + h.pool = async () => { + throw FAILED; + }; + const failed = makeFakeDb("failed"); + vi.mocked(failed.close).mockImplementation(async () => { + throw new Error("close refused"); + }); + h.fakeDb = failed; + + const error = await connectToProfile("profile_0a1b2c3d.db").catch((e: unknown) => e); + + expect((error as Error).message).toBe(FAILED_LINE); + expect(vi.mocked(logError).mock.calls).toEqual([[FAILED_LINE]]); + expect(vi.mocked(logWarn).mock.calls).toEqual([ + ["Profile profile_0a1b2c3d.db: the plugin's pool could not be closed after the failed switch: close refused"], + ]); + await expect(getDb()).rejects.toThrow(/No database connection/); + }); +}); + describe("blocking alert (#408)", () => { beforeEach(() => { vi.mocked(logWarn).mockClear(); @@ -573,15 +711,22 @@ describe("a profile is prepared before the plugin opens it (#390)", () => { expect([...consoleLines, ...journal].filter((line) => /[\\/]/.test(line))).toEqual([]); }); - it("prepares after the checksum repair and before Database.load", async () => { + it("prepares after the checksum repair and before Database.load, then switches the pool (#543)", async () => { await connectToProfile("profile_0a1b2c3d.db"); const invoked = vi.mocked(invoke).mock; - expect(invoked.calls.map((call) => call[0])).toEqual(["repair_migrations", "prepare_profile_db"]); + const load = vi.mocked(Database.load).mock; + expect(invoked.calls.map((call) => call[0])).toEqual([ + "repair_migrations", + "prepare_profile_db", + "use_single_connection_pool", + ]); expect(invoked.calls[1][1]).toEqual({ dbFilename: "profile_0a1b2c3d.db" }); - expect(invoked.invocationCallOrder[1]).toBeLessThan( - vi.mocked(Database.load).mock.invocationCallOrder[0] - ); + expect(invoked.invocationCallOrder[1]).toBeLessThan(load.invocationCallOrder[0]); + // The switch names the URL Database.load opened: the key of the plugin's map. + expect(load.calls[0]).toEqual(["sqlite:profile_0a1b2c3d.db"]); + expect(invoked.calls[2][1]).toEqual({ db: "sqlite:profile_0a1b2c3d.db" }); + expect(load.invocationCallOrder[0]).toBeLessThan(invoked.invocationCallOrder[2]); }); it("opens the database only once the preparation has finished", async () => { @@ -933,7 +1078,7 @@ describe("cleanLogLine: the known folders first, then withoutFolders (#497)", () }); }); -describe("the four Journal sites of db.ts take both curtains (#497)", () => { +describe("the six Journal sites of db.ts take both curtains (#497, #543)", () => { // Glued to `;`, which starts no path: withoutFolders alone keeps `jean`. const GLUED = "x;/home/jean dupont/notes/x.db"; @@ -992,6 +1137,38 @@ describe("the four Journal sites of db.ts take both curtains (#497)", () => { "Profile profile_0a1b2c3d.db: database preparation failed: Cannot read x.db", ]); }); + + it("a failed switch to one connection, in the Journal and in the error that fails the opening (#543)", async () => { + h.pool = async () => { + throw `single_connection_pool_failed: unable to open ${GLUED}`; + }; + h.fakeDb = makeFakeDb("next"); + + const error = await connectToProfile("profile_0a1b2c3d.db").catch((e: unknown) => e); + + const line = + "Profile profile_0a1b2c3d.db: switching to a single-connection pool failed, profile not opened: single_connection_pool_failed: unable to open x.db"; + expect(vi.mocked(logError).mock.calls.map((call) => call[0])).toEqual([line]); + // startupConnection shows the message on the error page and logs the error. + expect((error as Error).message).toBe(line); + }); + + it("a failed close of the plugin's pool after a failed switch (#543)", async () => { + h.pool = async () => { + throw "single_connection_pool_failed: boom"; + }; + const next = makeFakeDb("next"); + vi.mocked(next.close).mockImplementation(async () => { + throw new Error(`close refused for ${GLUED}`); + }); + h.fakeDb = next; + + await connectToProfile("profile_0a1b2c3d.db").catch(() => undefined); + + expect(vi.mocked(logWarn).mock.calls.map((call) => call[0])).toEqual([ + "Profile profile_0a1b2c3d.db: the plugin's pool could not be closed after the failed switch: close refused for x.db", + ]); + }); }); // --------------------------------------------------------------------------- @@ -1053,7 +1230,7 @@ describe("connectToProfile waits for the known folders (#497)", () => { answer("/home/max"); await connecting; // The path API never goes through invoke: the order stays the one of #390. - expect(m.commands()).toEqual(["repair_migrations", "prepare_profile_db"]); + expect(m.commands()).toEqual(["repair_migrations", "prepare_profile_db", "use_single_connection_pool"]); }); it("goes on 2 s after initKnownFolders() when homeDir() never answers", async () => { @@ -1069,7 +1246,7 @@ describe("connectToProfile waits for the known folders (#497)", () => { await vi.advanceTimersByTimeAsync(1); await connecting; - expect(m.commands()).toEqual(["repair_migrations", "prepare_profile_db"]); + expect(m.commands()).toEqual(["repair_migrations", "prepare_profile_db", "use_single_connection_pool"]); }); it("goes on at once when homeDir() rejects, with the folder that resolved", async () => { @@ -1086,7 +1263,7 @@ describe("connectToProfile waits for the known folders (#497)", () => { await vi.advanceTimersByTimeAsync(0); await connecting; - expect(m.commands()).toEqual(["repair_migrations", "prepare_profile_db"]); + expect(m.commands()).toEqual(["repair_migrations", "prepare_profile_db", "use_single_connection_pool"]); expect(m.logError.mock.calls.map((call) => call[0])).toEqual([ "Migration repair failed: Cannot open database: x;profile_0a1b2c3d.db", ]); diff --git a/src/services/db.ts b/src/services/db.ts index b2754f1..e1f0e53 100644 --- a/src/services/db.ts +++ b/src/services/db.ts @@ -7,25 +7,39 @@ let rawInstance: Database | null = null; let serializedInstance: Database | null = null; // --------------------------------------------------------------------------- -// DB access serialization (#228 follow-up — fix "database is locked"; #408). +// DB access: one connection, one queue (#228 follow-up, #408, #543). // // tauri-plugin-sql exposes NO transaction primitive to the JS side and loads // SQLite through a default multi-connection sqlx pool (`Pool::connect` => // max_connections = 10). Every db.execute / db.select is an independent -// `pool.acquire()`, so a `BEGIN` issued on one pooled connection and its -// matching `COMMIT` issued on another would strand an open write transaction -// on an idle connection — that connection then holds SQLite's write lock until -// the app restarts, and every later write fails with "database is locked". +// `pool.acquire()`, so the statements of one transaction could run on two +// connections: a `COMMIT` sent to the wrong one stranded an open write +// transaction until the app restarted (0.10.0), and a write sent to the second +// one waits for the first one's write lock, then fails with "database is +// locked" after sqlx's 5 s busy timeout (#543). // -// Fix: funnel EVERY db operation through a single FIFO async lock. Plain -// reads/writes take the lock per-statement; `withTransaction` holds it across -// the whole BEGIN..COMMIT. With no two operations ever overlapping in time, -// the pool keeps handing back its single idle connection, so a transaction's -// statements all run on the same connection and can never strand. Serializing -// all DB access is a non-issue for a local single-user app where queries are -// tiny and infrequent — and it makes the "atomic" saves genuinely atomic. +// The guarantee (#543, ADR 0027): right after `Database.load`, inside the +// exclusive section that opens a profile, `loadUnlocked` swaps the plugin's +// pool for a pool of ONE connection on the same database +// (`use_single_connection_pool`, src-tauri/src/commands/db_pool_commands.rs), +// before any statement. Keeping the operations from overlapping was not +// enough: sqlx returns a connection to its pool through a deferred task, so a +// statement sent right after another found no idle connection and made the +// pool open a second one, then serve the two in turn. // -// Rules (#408): +// The FIFO lock keeps the order: plain reads/writes take it per statement, +// `withTransaction` holds it across the whole BEGIN..COMMIT, so no statement +// from elsewhere runs inside someone else's transaction, on the connection +// they share. Serializing all DB access is a non-issue for a local +// single-user app where queries are tiny and infrequent — and it makes the +// "atomic" saves genuinely atomic. +// +// Rules (#408, #543): +// - Opening a profile switches the plugin's pool to one connection before +// anything can query it: `getDb()` and `withTransaction` find no connection +// until the switch succeeded. A failed switch fails the opening (a Journal +// line without folder, the plugin's pool closed) rather than leave the +// profile on a pool that splits transactions. // - The lock is strict and NOT reentrant. Inside a `withTransaction` callback, // use ONLY the handle the callback receives: it runs directly on the // connection the transaction holds. Calling `getDb()` from a callback (or @@ -239,8 +253,8 @@ export async function getDb(): Promise { /** * Run `fn` as one serialized transaction. The global DB lock is held for the - * ENTIRE callback so no other db.execute/select can interleave and strand the - * transaction on a different pooled connection. `fn` receives the transaction + * ENTIRE callback so no other db.execute/select runs inside the transaction, + * on the single connection of the pool (#543). `fn` receives the transaction * handle and is responsible for issuing BEGIN/COMMIT (and ROLLBACK on error) * on it — `withTransaction` only guarantees exclusive, non-interleaved access * for the whole BEGIN..COMMIT. Never call `getDb()` from `fn` (deadlock). @@ -293,8 +307,38 @@ async function closeUnlocked(): Promise { } } +/** + * Open `dbFilename`, then switch the plugin's pool to a pool of one connection + * (#543, ADR 0027) before anything can query it: the state that `getDb()` and + * `withTransaction` read is set only once the switch succeeded. A failed + * switch fails the opening: the line goes to the Journal and becomes the + * message of the error (both shown to the user, neither with a folder), the + * plugin's pool is closed, and no connection is left. + */ async function loadUnlocked(dbFilename: string): Promise { - const db = await Database.load(`sqlite:${dbFilename}`); + const url = `sqlite:${dbFilename}`; + const db = await Database.load(url); + try { + // `url` is the key of the plugin's map: the string Database.load was given. + await invoke("use_single_connection_pool", { db: url }); + } catch (e) { + const line = cleanLogLine( + `Profile ${dbFilename}: switching to a single-connection pool failed, profile not opened: ${e instanceof Error ? e.message : String(e)}` + ); + logError(line); + // Nothing references the plugin's pool any more: closed, rather than left + // open on the file until the next Database.load of this profile. + try { + await db.close(); + } catch (closeError) { + logWarn( + cleanLogLine( + `Profile ${dbFilename}: the plugin's pool could not be closed after the failed switch: ${closeError instanceof Error ? closeError.message : String(closeError)}` + ) + ); + } + throw new Error(line); + } generation += 1; rawInstance = db; serializedInstance = serialize(db, generation);