20 lines
703 B
Python
20 lines
703 B
Python
from collections.abc import AsyncIterator
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
from sqlalchemy.pool import NullPool
|
|
|
|
from app.core.config import settings
|
|
|
|
_engine_kwargs: dict = {"echo": settings.DB_ECHO, "pool_pre_ping": True}
|
|
if settings.is_test:
|
|
# Tests run each case in its own event loop; pooled connections can't cross loops.
|
|
_engine_kwargs["poolclass"] = NullPool
|
|
|
|
engine = create_async_engine(settings.DATABASE_URL, **_engine_kwargs)
|
|
SessionLocal = async_sessionmaker(engine, expire_on_commit=False, autoflush=False)
|
|
|
|
|
|
async def get_db() -> AsyncIterator[AsyncSession]:
|
|
async with SessionLocal() as session:
|
|
yield session
|