# ================================================================ # services/auth/app/core/database.py (ENHANCED VERSION) # ================================================================ """ Database configuration for authentication service """ import structlog from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker from sqlalchemy.pool import NullPool from app.core.config import settings from shared.database.base import Base logger = structlog.get_logger() # Create async engine engine = create_async_engine( settings.DATABASE_URL, poolclass=NullPool, echo=settings.DEBUG, future=True ) # Create session factory AsyncSessionLocal = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False, autoflush=False, autocommit=False ) async def get_db() -> AsyncSession: """Database dependency""" async with AsyncSessionLocal() as session: try: yield session await session.commit() except Exception as e: await session.rollback() logger.error(f"Database session error: {e}") raise finally: await session.close() async def create_tables(): """Create database tables""" async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) logger.info("Database tables created successfully")