34 lines
1.1 KiB
Python
34 lines
1.1 KiB
Python
"""Connexion et sessions de base de données async."""
|
|
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
|
|
from backend.config.settings import get_settings
|
|
from backend.database.models import Base
|
|
|
|
settings = get_settings()
|
|
|
|
# Convertir l'URL SQLite en version async
|
|
DB_URL = settings.database_url
|
|
if DB_URL.startswith("sqlite:///"):
|
|
DB_URL = DB_URL.replace("sqlite:///", "sqlite+aiosqlite:///")
|
|
|
|
engine = create_async_engine(DB_URL, echo=settings.debug, pool_pre_ping=True)
|
|
AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
|
|
|
|
|
async def init_db():
|
|
"""Crée toutes les tables si elles n'existent pas."""
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
|
|
|
|
async def get_db():
|
|
"""Dépendance FastAPI - fournit une session DB."""
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
finally:
|
|
await session.close()
|