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

@@ -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