Files
bakery-ia/services/auth/app/core/database.py

52 lines
1.4 KiB
Python
Raw Normal View History

2025-07-17 21:25:27 +02:00
# ================================================================
# services/auth/app/core/database.py (ENHANCED VERSION)
# ================================================================
"""
2025-07-17 21:25:27 +02:00
Database configuration for authentication service
"""
2025-07-18 14:41:39 +02:00
import structlog
2025-07-17 21:25:27 +02:00
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.pool import NullPool
from app.core.config import settings
2025-07-17 21:25:27 +02:00
from shared.database.base import Base
2025-07-18 14:41:39 +02:00
logger = structlog.get_logger()
2025-07-17 21:25:27 +02:00
# 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
)
2025-07-17 21:25:27 +02:00
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()
2025-07-17 21:25:27 +02:00
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")