"""
Database utility functions and helpers
"""
import logging
from database import get_cached_connection, ManagedDBConnection


logger = logging.getLogger(__name__)


def fetch_as_dict(cursor):
    """Dictionary format ma rows fetch garne helper function"""
    columns = [col[0] for col in cursor.description]
    rows = cursor.fetchall()
    result = [dict(zip(columns, row)) for row in rows]
    return result


def get_db_connection():
    """Get a database connection from the pool with retry logic and caching.
    
    This wrapper function ensures that connections are properly managed and cached.
    """
    conn = get_cached_connection()
    return ManagedDBConnection(conn)


def allowed_file(filename):
    """Check if a file has an allowed extension."""
    from config import ALLOWED_EXTENSIONS
    
    # Performance optimization: Use a set for O(1) lookups
    ALLOWED_EXTENSIONS_SET = set(ALLOWED_EXTENSIONS)
    
    if not filename or '.' not in filename:
        return False
    ext = filename.rsplit('.', 1)[1].lower()
    return ext in ALLOWED_EXTENSIONS_SET