from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import QueuePool import os from dotenv import load_dotenv from pathlib import Path ROOT_DIR = Path(__file__).parent load_dotenv(ROOT_DIR / '.env') DATABASE_URL = os.environ.get('DATABASE_URL', 'postgresql://user:password@localhost:5432/membership_db') # Configure engine with connection pooling and connection health checks engine = create_engine( DATABASE_URL, poolclass=QueuePool, pool_size=5, # Keep 5 connections open max_overflow=10, # Allow up to 10 extra connections during peak pool_pre_ping=True, # CRITICAL: Test connections before using them pool_recycle=3600, # Recycle connections every hour (prevents stale connections) echo=False, # Set to True for SQL debugging connect_args={ 'connect_timeout': 10, # Timeout connection attempts after 10 seconds 'options': '-c statement_timeout=30000' # 30 second query timeout } ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() def get_db(): db = SessionLocal() try: yield db finally: db.close()