diff --git a/database.py b/database.py index b6d2337..15cd561 100644 --- a/database.py +++ b/database.py @@ -5,16 +5,23 @@ from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker import os +import logging +from sqlalchemy.exc import SQLAlchemyError engine = create_engine( os.getenv("DB_URL"), - pool_pre_ping=True, # Check connection before using it - pool_size=5, # Connection pool size - max_overflow=10, # Max extra connections when pool is full - pool_recycle=3600, # Recycle connections after 1 hour - echo=True, # Log SQL queries - connect_args={"sslmode": "require" if os.getenv("IS_DEV") == "False" else "disable"}, + pool_pre_ping=True, + pool_size=2, # Reduced from 5 + max_overflow=3, # Reduced from 10 + pool_recycle=1800, # Reduced to 30 minutes + pool_timeout=30, # Add connection timeout + echo=False, # Disable in production - this uses memory + connect_args={ + "sslmode": "require" if os.getenv("IS_DEV") == "False" else "disable", + "connect_timeout": 10, # Connection timeout + "command_timeout": 60, # Query timeout + }, ) Base = declarative_base() # Base class for ORM models @@ -26,5 +33,14 @@ def get_db(): db = SessionLocal() try: yield db + db.commit() # Explicit commit + except SQLAlchemyError as e: + db.rollback() + logging.error(f"Database error: {e}") + raise + except Exception as e: + db.rollback() + logging.error(f"Unexpected error: {e}") + raise finally: db.close()