From 9c5b1d9804b3e77c102866c1504e569e95013200 Mon Sep 17 00:00:00 2001 From: Username Date: Sat, 20 Dec 2025 03:44:38 +0100 Subject: [PATCH] enable sqlite wal mode for file databases --- app/database.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/app/database.py b/app/database.py index 9c38511..45218e0 100644 --- a/app/database.py +++ b/app/database.py @@ -45,6 +45,15 @@ def _get_connection_string(db_path) -> tuple[str, dict]: return db_path, {} +def _is_file_database(db_path) -> bool: + """Check if database path refers to a file (not in-memory).""" + if isinstance(db_path, Path): + return True + if isinstance(db_path, str) and db_path not in (":memory:", ""): + return not db_path.startswith("file::memory:") + return False + + def get_db() -> sqlite3.Connection: """Get database connection for current request context.""" if "db" not in g: @@ -53,8 +62,10 @@ def get_db() -> sqlite3.Connection: g.db = sqlite3.connect(conn_str, **kwargs) g.db.row_factory = sqlite3.Row g.db.execute("PRAGMA foreign_keys = ON") - if isinstance(db_path, Path): - g.db.execute("PRAGMA journal_mode = WAL") + if _is_file_database(db_path): + # WAL mode set in init_db; these optimize per-connection behavior + g.db.execute("PRAGMA busy_timeout = 5000") + g.db.execute("PRAGMA synchronous = NORMAL") return g.db @@ -79,6 +90,9 @@ def init_db() -> None: _memory_db_holder.commit() else: db = get_db() + # Enable WAL mode for file databases (persists with database) + if _is_file_database(db_path): + db.execute("PRAGMA journal_mode = WAL") db.executescript(SCHEMA) db.commit()