Automated Action acf2757384 Fix Supervisor startup errors and improve application resilience
- Update database path configuration for better compatibility
- Add comprehensive logging system with error handling
- Create supervisord.conf with proper configuration
- Add environment variable example file
- Enhance health check endpoint to report database status
- Add detailed startup and shutdown event handlers
- Update documentation with troubleshooting information
- Update requirements with additional helpful packages
2025-06-02 22:42:07 +00:00

54 lines
1.7 KiB
Python

from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from app.core.config import settings
from app.core.logging import get_logger
logger = get_logger("db.session")
# Create engine with better error handling
try:
logger.info(f"Creating database engine with URL: {settings.SQLALCHEMY_DATABASE_URL}")
engine = create_engine(
settings.SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False},
pool_pre_ping=True, # Ensure connections are still alive
)
# Add engine event listeners for debugging
@event.listens_for(engine, "connect")
def on_connect(dbapi_connection, connection_record):
logger.info("Database connection established")
@event.listens_for(engine, "engine_connect")
def on_engine_connect(connection):
logger.info("Engine connected")
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# Test connection on startup
with engine.connect() as conn:
logger.info("Database connection test successful")
except SQLAlchemyError as e:
logger.error(f"Database connection error: {e}", exc_info=True)
# Don't re-raise to allow fallback mechanisms
SessionLocal = None
# Dependency to get DB session
def get_db():
if not SessionLocal:
logger.error("Database session not initialized")
raise SQLAlchemyError("Database connection failed")
db = SessionLocal()
try:
logger.debug("DB session created")
yield db
except SQLAlchemyError as e:
logger.error(f"Database error during session: {e}")
raise
finally:
logger.debug("DB session closed")
db.close()