From 89bf87cb62e1ee2e83b5282dce30a483b4911ef5 Mon Sep 17 00:00:00 2001 From: Scott Idem Date: Wed, 21 Jan 2026 12:49:47 -0500 Subject: [PATCH] fix(db): stabilize connection refreshing and prevent ResourceClosedError - Update sql_connect to refresh global db object via reconnect_db - Add returns_rows check and safe fetch block in sql_select - Prevents 500 errors during transient database connection issues --- app/lib_sql_core.py | 16 +++++++++------- app/lib_sql_crud.py | 13 ++++++++++++- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/app/lib_sql_core.py b/app/lib_sql_core.py index 97d7530..c72b7bd 100644 --- a/app/lib_sql_core.py +++ b/app/lib_sql_core.py @@ -77,10 +77,12 @@ def reconnect_db() -> bool: log.exception("DB SQL Core: FAILED to refresh database connection!") return False -def sql_connect(current_db, log_lvl: int = logging.INFO) -> bool: - """Old compatibility wrapper for disposing the engine.""" - if current_db: - current_db.engine.dispose() - log.info('DB SQL Core: Disposed of the current engine via sql_connect.') - return True - return False \ No newline at end of file +def sql_connect(current_db=None, log_lvl: int = logging.INFO) -> bool: + + """Refreshes the global database connection.""" + + log.setLevel(log_lvl) + + log.info('DB SQL Core: Refreshing database connection via sql_connect...') + + return reconnect_db() \ No newline at end of file diff --git a/app/lib_sql_crud.py b/app/lib_sql_crud.py index 36a6d23..363c12e 100644 --- a/app/lib_sql_crud.py +++ b/app/lib_sql_crud.py @@ -291,7 +291,18 @@ def sql_select( return [] if as_list else None # Fetch all rows first to determine actual count reliably - rows = result.all() + try: + # Check if the result set actually contains rows before fetching + if hasattr(result, 'returns_rows') and not result.returns_rows: + log.warning("SQL Result does not return rows (ResourceClosedError prevented).") + return [] if as_list else None + + rows = result.all() + except Exception as e: + log.error(f"SQL Fetch Error: {e}") + set_last_sql_error(e) + return [] if as_list else None + count = len(rows) if count == 0: