From 24cdea0a4ce25c00ac250d99333bd9cac984d61c Mon Sep 17 00:00:00 2001 From: Shane Handley Date: Sat, 6 Jun 2020 18:26:48 +1000 Subject: [PATCH] Enable WAL and busy_timeout for each sqlite connection to mitigate db locks, --- .gitignore | 2 ++ server/src/persistence/mod.rs | 24 +++++++++++++++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index eb77a24e0d..2eaacda61e 100644 --- a/.gitignore +++ b/.gitignore @@ -36,6 +36,8 @@ todo.txt # Game data *.sqlite *.sqlite-journal +*.sqlite-wal +*.sqlite-shm # direnv /.envrc diff --git a/server/src/persistence/mod.rs b/server/src/persistence/mod.rs index f4709a3edd..a47d253492 100644 --- a/server/src/persistence/mod.rs +++ b/server/src/persistence/mod.rs @@ -6,7 +6,7 @@ mod schema; extern crate diesel; -use diesel::prelude::*; +use diesel::{connection::SimpleConnection, prelude::*}; use diesel_migrations::embed_migrations; use std::{env, fs, path::PathBuf}; @@ -24,8 +24,26 @@ pub fn run_migrations(db_dir: &str) -> Result<(), diesel_migrations::RunMigratio fn establish_connection(db_dir: &str) -> SqliteConnection { let db_dir = &apply_saves_dir_override(db_dir); let database_url = format!("{}/db.sqlite", db_dir); - SqliteConnection::establish(&database_url) - .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)) + + let connection = SqliteConnection::establish(&database_url) + .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)); + + // Use Write-Ahead-Logging for improved concurrency: https://sqlite.org/wal.html + // Set a busy timeout (in ms): https://sqlite.org/c3ref/busy_timeout.html + if let Err(error) = connection.batch_execute( + " + PRAGMA journal_mode = WAL; + PRAGMA busy_timeout = 250; + ", + ) { + log::warn!( + "Failed adding PRAGMA statements while establishing sqlite connection, this will \ + result in a higher likelihood of locking errors: {}", + error + ); + } + + connection } fn apply_saves_dir_override(db_dir: &str) -> String {