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
This commit is contained in:
@@ -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
|
||||
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()
|
||||
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user