After_Chido_Api/config/database.py

53 lines
1.3 KiB
Python

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from config.settings import settings
import logging
from contextlib import asynccontextmanager
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
DATABASE_URL = settings.database_url
# Configuration optimisée du moteur
engine = create_async_engine(
DATABASE_URL,
echo=True,
pool_size=5,
max_overflow=10,
pool_timeout=30,
pool_recycle=1800,
pool_pre_ping=True
)
AsyncSessionLocal = sessionmaker(
engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False
)
@asynccontextmanager
async def get_db():
session = AsyncSessionLocal()
try:
yield session
await session.commit()
except SQLAlchemyError as e:
await session.rollback()
logger.error(f"Database error: {str(e)}")
raise
finally:
await session.close()
async def init_db():
from models.db import metadata
try:
async with engine.begin() as conn:
await conn.run_sync(metadata.create_all)
logger.info("Database tables created successfully.")
except Exception as e:
logger.error(f"Error creating database tables: {str(e)}")
raise