51 lines
1.3 KiB
Python
51 lines
1.3 KiB
Python
import os
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
|
from sqlalchemy.pool import NullPool
|
|
import logging
|
|
|
|
from database.models.generic_model import Base
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite+aiosqlite:///./data/sage_dataven.db")
|
|
|
|
engine = create_async_engine(
|
|
DATABASE_URL,
|
|
echo=False,
|
|
future=True,
|
|
poolclass=NullPool,
|
|
)
|
|
|
|
async_session_factory = async_sessionmaker(
|
|
engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
autoflush=False,
|
|
)
|
|
|
|
|
|
async def init_db():
|
|
logger.info("Debut init_db")
|
|
try:
|
|
logger.info("Tentative de connexion")
|
|
async with engine.begin() as conn:
|
|
logger.info("Connexion etablie")
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
logger.info("create_all execute")
|
|
|
|
logger.info("Base de données initialisée avec succès")
|
|
logger.info(f"Fichier DB: {DATABASE_URL}")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Erreur initialisation DB: {e}")
|
|
raise
|
|
|
|
|
|
async def get_session() -> AsyncSession:
|
|
async with async_session_factory() as session:
|
|
yield session
|
|
|
|
|
|
async def close_db():
|
|
await engine.dispose()
|
|
logger.info("Connexions DB fermées")
|