import logging from sqlmodel import create_engine, Session, SQLModel from models import User, Task import os # Set up logging logger = logging.getLogger(__name__) # Get database URL from environment DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./todo_app.db") from tenacity import retry, stop_after_attempt, wait_exponential @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10)) def create_engine_with_retry(): """Create database engine with retry logic""" try: engine = create_engine( DATABASE_URL, echo=False, pool_size=20, # Number of connections to maintain in the pool max_overflow=30, # Number of connections to allow in addition to pool_size pool_pre_ping=True, # Verify connections before using them pool_recycle=3600, # Recycle connections after 1 hour pool_timeout=30 # Time to wait for a connection from the pool ) # Test the connection with engine.connect() as conn: pass return engine except Exception as e: logger.error(f"Database connection failed: {str(e)}") raise # Create engine with connection pool configuration and retry logic engine = create_engine_with_retry() def create_db_and_tables(): """Create database tables""" SQLModel.metadata.create_all(engine) def get_session(): """Get database session""" with Session(engine) as session: yield session