I noticed that in the current implementation of the UserSQLAlchemyRepo, each repository method creates a new session using the session_factory() context manager. It can lead to potential performance issues when multiple repository methods are called sequentially within the same service layer function.
|
_async_session_factory = async_sessionmaker( |
|
class_=AsyncSession, |
|
sync_session_class=RoutingSession, |
|
expire_on_commit=False, |
|
) |
|
session = async_scoped_session( |
|
session_factory=_async_session_factory, |
|
scopefunc=get_session_context, |
|
) |
|
|
|
|
|
class Base(DeclarativeBase): |
|
... |
|
|
|
|
|
@asynccontextmanager |
|
async def session_factory() -> AsyncGenerator[AsyncSession, None]: |
|
_session = async_sessionmaker( |
|
class_=AsyncSession, |
|
sync_session_class=RoutingSession, |
|
expire_on_commit=False, |
|
)() |
|
try: |
|
yield _session |
|
finally: |
|
await _session.close() |
|
async def get_user_by_email_or_nickname( |
|
self, |
|
*, |
|
email: str, |
|
nickname: str, |
|
) -> User | None: |
|
async with session_factory() as read_session: |
|
stmt = await read_session.execute( |
|
select(User).where(or_(User.email == email, User.nickname == nickname)), |
|
) |
|
return stmt.scalars().first() |
I noticed that in the current implementation of the UserSQLAlchemyRepo, each repository method creates a new session using the session_factory() context manager. It can lead to potential performance issues when multiple repository methods are called sequentially within the same service layer function.
fastapi-boilerplate/core/db/session.py
Lines 51 to 76 in ca3bb3f
fastapi-boilerplate/app/user/adapter/output/persistence/sqlalchemy/user.py
Lines 29 to 39 in ca3bb3f