Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Potential Performance Issue with Session Management in Repository Methods #40

Open
vuxmai opened this issue Aug 26, 2024 · 0 comments
Open

Comments

@vuxmai
Copy link

vuxmai commented Aug 26, 2024

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()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@vuxmai and others