From a0533e1d782c9a137b199251a2b97d3877f2112e Mon Sep 17 00:00:00 2001 From: Josh Finlay Date: Wed, 8 Jan 2025 08:36:50 +1000 Subject: [PATCH] fix: database connection handling - Create new connections for each request instead of reusing one - Remove global connection pool to fix thread reuse error - Simplify shutdown handler --- backend/main.py | 26 ++++++++++---------------- frontend/src/App.tsx | 6 +++--- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/backend/main.py b/backend/main.py index 9b501c3..bd900ab 100644 --- a/backend/main.py +++ b/backend/main.py @@ -102,7 +102,14 @@ app = FastAPI() ha_mqtt = HomeAssistantMQTT() # Constants -DB_PATH = "gate.db" # Database file path +DB_PATH = "gatekeeper.db" # Database file path + +# Database connection handling +async def get_db(): + """Get a new database connection""" + db = await aiosqlite.connect(DB_PATH) + db.row_factory = aiosqlite.Row + return db # Set up MQTT event logging async def log_mqtt_event(action: str, success: bool = True): @@ -467,17 +474,6 @@ async def update_settings(settings: Settings): # Serve static files app.mount("/", StaticFiles(directory="../public", html=True), name="static") -# Database connection pool -db_pool = None - -async def get_db(): - """Get a database connection from the pool""" - global db_pool - if db_pool is None: - db_pool = await aiosqlite.connect(DB_PATH) - db_pool.row_factory = aiosqlite.Row - return db_pool - # GPIO Setup def setup_gpio(): """Initialize GPIO pins based on settings""" @@ -665,10 +661,8 @@ async def shutdown_event(): # 4. Close database connection logger.info("Closing database connection...") - global db_pool - if db_pool: - await db_pool.close() - logger.info("Database connection closed") + # No need to explicitly close as we're using new connections for each request + logger.info("Database connections will be closed automatically") logger.info("Shutdown completed successfully") except Exception as e: diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index e8a1662..23f03a4 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -9,8 +9,8 @@ function App() { const [hasMoreEvents, setHasMoreEvents] = useState(false); const [totalEvents, setTotalEvents] = useState(0); const [settings, setSettings] = useState({ - maxOpenTimeSeconds: '300', - triggerDuration: '500', + maxOpenTimeSeconds: 300, + triggerDuration: 500, mqtt: { broker: 'localhost', port: '1883', @@ -84,7 +84,7 @@ function App() { if (result.success) { const newEvents = await api.getEvents(); setEvents(newEvents.events); - setGateStatus(prev => ({ ...prev, isOpen: result.currentStatus })); + setGateStatus(prev => ({ ...prev, isOpen: result.isOpen })); } } catch (err) { setError('Failed to trigger gate');