This commit is contained in:
2026-08-12 18:22:26 -05:00
parent 7e3b3dff6d
commit 9cc7093c48
6 changed files with 102 additions and 39 deletions
+31
View File
@@ -0,0 +1,31 @@
import sqlite3
import time
LOCKED_MSGS = ("database is locked", "database is busy")
def connect(db_path, timeout=30):
"""Open a SQLite connection hardened against cross-process contention.
Enables WAL mode and a busy timeout so that the multiple bot processes
sharing a database file wait for each other instead of raising
``OperationalError: database is locked`` immediately.
"""
conn = sqlite3.connect(db_path, timeout=timeout)
conn.execute("PRAGMA busy_timeout=%d" % (timeout * 1000))
conn.execute("PRAGMA journal_mode=WAL")
return conn
def commit(conn, retries=5, backoff=0.2):
"""Commit, retrying briefly when the database is locked by another writer."""
for attempt in range(retries):
try:
conn.commit()
return
except sqlite3.OperationalError as e:
if str(e).lower() in LOCKED_MSGS and attempt < retries - 1:
time.sleep(backoff * (attempt + 1))
continue
raise