fix: Add missing sqlite3 import and improve database connection robustness by verifying and safely closing connections.

This commit is contained in:
Marco Gallegos
2025-12-22 15:08:04 -06:00
parent cfd359c231
commit 4ad40c48e9
3 changed files with 38 additions and 5 deletions

View File

@@ -100,6 +100,22 @@ This document tracks all pending tasks, improvements, and issues identified in t
- **Description**: `identity.py:42` string comparison for ADMIN_ID could fail if numeric
- **Action needed**: Fix type handling for user ID comparison
### [BUG-004] Missing sqlite3 import
- **Status**: DONE
- **Priority**: High
- **Description**: `flow_engine.py` missing `sqlite3` import causing NameError
- **Files affected**: `flow_engine.py`
- **Action needed**: Add `import sqlite3`
- **Due**: ASAP
### [BUG-005] Telegram Conflict Error
- **Status**: DONE
- **Priority**: High
- **Description**: `telegram.error.Conflict` indicates multiple bot instances running
- **Files affected**: Runtime
- **Action needed**: Kill all orphan processes and restart
- **Due**: ASAP
## **Documentation & Testing** 📚
### [DOC-001] Documentation Consistency

View File

@@ -15,16 +15,32 @@ local = threading.local()
def get_db_connection():
"""Creates a connection to the SQLite database."""
if not hasattr(local, "conn"):
local.conn = sqlite3.connect(DATABASE_FILE, check_same_thread=False)
local.conn.row_factory = sqlite3.Row
if hasattr(local, "conn"):
try:
# Check if connection is open
local.conn.execute("SELECT 1")
logger.debug("Reusing existing database connection")
return local.conn
except sqlite3.ProgrammingError:
logger.warning("Detected closed connection in thread-local storage. Recreating.")
del local.conn
logger.debug("Creating new database connection")
local.conn = sqlite3.connect(DATABASE_FILE, check_same_thread=False)
local.conn.row_factory = sqlite3.Row
return local.conn
def close_db_connection():
"""Closes the database connection."""
if hasattr(local, "conn"):
local.conn.close()
del local.conn
logger.debug("Closing database connection")
try:
local.conn.close()
except Exception as e:
logger.error(f"Error closing database connection: {e}")
finally:
if hasattr(local, "conn"):
del local.conn
def setup_database():
"""Sets up the database tables if they don't exist."""

View File

@@ -2,6 +2,7 @@
import json
import logging
import os
import sqlite3
from bot.db import get_db_connection
from bot.modules.sales_rag import generate_sales_pitch
from bot.modules.nfc_tag import generate_nfc_tag