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