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

유저 API N+1 쿼리 개선 #27

Merged
merged 2 commits into from
Jul 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions waffledotcom/src/apps/user/repositories.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from fastapi import Depends
from sqlalchemy.orm import Session
from sqlalchemy.orm import Session, joinedload

from waffledotcom.src.apps.user.models import User
from waffledotcom.src.database.connection import Transaction, get_db_session
Expand All @@ -15,7 +15,7 @@ def __init__(
self.transaction = transaction

def get_users(self) -> list[User]:
return self.session.query(User).all()
return self.session.query(User).options(joinedload(User.positions)).all()

def get_user_by_id(self, user_id: int) -> User | None:
return self.session.query(User).filter(User.id == user_id).first()
Expand Down
21 changes: 15 additions & 6 deletions waffledotcom/src/database/connection.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from typing import Iterator
import asyncio
from collections.abc import AsyncIterator

import sqlalchemy
from fastapi import Depends
from sqlalchemy import orm
from sqlalchemy.exc import DatabaseError
from sqlalchemy.orm.session import Session

from waffledotcom.src.database.config import db_config
Expand All @@ -22,17 +24,24 @@ def __init__(self):
def get_engine(self) -> sqlalchemy.Engine:
return self._engine

def make_session(self) -> orm.Session:
session = self._session_maker()
return session
async def make_session(self) -> orm.Session:
exc = RuntimeError("이게 실행되면 버그이다.")
for _ in range(5):
try:
session = self._session_maker()
return session
except DatabaseError as e:
exc = e
await asyncio.sleep(1)
raise exc

def teardown(self):
orm.close_all_sessions()
self._engine.dispose()


def get_db_session() -> Iterator[orm.Session]:
session = DBSessionFactory().make_session()
async def get_db_session() -> AsyncIterator[orm.Session]:
session = await DBSessionFactory().make_session()

try:
yield session
Expand Down
Loading