Pool name is now a global variable that only needs to supplied once

This commit is contained in:
Florian 2025-11-06 17:04:26 +01:00
parent 29fb26d4f9
commit 1cbcb812c9

View File

@ -28,29 +28,33 @@ MYSQL_CONFIG = {
_pool_lock = threading.Lock()
_connection_pool = None
_pool_name = "MySQLPool"
_health_thread = None
_stop_healthcheck = threading.Event()
def create_connection_pool(pool_name: str = "MySQLPool"):
def create_connection_pool(pool_name : str = None):
"""
Create a MySQL connection pool.
Args:
pool_name (str): Name for the connection pool.
pool_name (str): Name for the connection pool overriding the default.
Raises:
RuntimeError: If pool creation fails after retries.
"""
global _connection_pool
global _connection_pool, _pool_name
if pool_name:
_pool_name = pool_name
with _pool_lock:
if _connection_pool is not None:
logger.debug("[MySQL] Pool already exists, returning existing pool")
return
for attempt in range (1,MAX_RETRIES+1):
try:
logger.info(f"[MySQL] Attempt {attempt} to connect...")
pool = pooling.MySQLConnectionPool(
pool_name=pool_name,
pool_name=_pool_name,
pool_size=5,
pool_reset_session=True,
**MYSQL_CONFIG
@ -82,13 +86,10 @@ def close_connection_pool():
_stop_healthcheck.set()
logger.debug("[MySQL] Healthcheck stop flag set")
def get_connection_pool(pool_name: str = "MySQLPool") -> MySQLConnectionPool:
def get_connection_pool() -> MySQLConnectionPool:
"""
Retrieve the existing MySQL connection pool, or create a new one if not initialized.
Args:
pool_name (str): Name for the connection pool.
Returns:
MySQLConnectionPool: The active connection pool.
"""
@ -96,22 +97,19 @@ def get_connection_pool(pool_name: str = "MySQLPool") -> MySQLConnectionPool:
with _pool_lock:
if _connection_pool is None:
logger.debug("[MySQL] No pool found, creating one")
create_connection_pool(pool_name)
create_connection_pool(_pool_name)
else:
logger.debug(f"[MySQL] Returning existing pool: {_connection_pool}")
return _connection_pool
def get_db(pool_name: str = "MySQLPool") -> Generator[MySQLConnection, None, None]:
def get_db() -> Generator[MySQLConnection, None, None]:
"""
Context generator yielding a database connection from the pool.
Args:
pool_name (str): Name for the connection pool.
Yields:
MySQLConnection: A live MySQL database connection.
"""
pool = get_connection_pool(pool_name)
pool = get_connection_pool()
logger.debug(f"[MySQL] Acquiring connection from pool: {pool}")
conn = pool.get_connection()
@ -120,8 +118,8 @@ def get_db(pool_name: str = "MySQLPool") -> Generator[MySQLConnection, None, Non
logger.debug("[MySQL] Connection alive")
except Error as e:
logger.warning(f"[MySQL] Connection dead, recreating pool: {e}")
create_connection_pool(pool_name)
pool = get_connection_pool(pool_name)
create_connection_pool(_pool_name)
pool = get_connection_pool()
conn = pool.get_connection()
logger.debug("[MySQL] Reconnected successfully")