Skip to content
Open
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
23 changes: 14 additions & 9 deletions app/common/repositories/base_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@

from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy import asc, desc
from sqlalchemy import asc, desc, func, select, Select
from sqlalchemy.orm import Session
from sqlalchemy.orm.query import Query

from app.common.schemas.pagination_schema import ListFilter, ListResponse

Expand All @@ -32,12 +31,16 @@ def get(self, db: Session, model_id: UUID) -> Optional[ModelType]:
return db.query(self.model).filter(self.model.id == model_id).first()

def list(
self, db: Session, list_options: ListFilter, query: Query | None = None
self,
db: Session,
list_options: ListFilter,
query: Select | None = None,
) -> ListResponse:
if not query:
query = db.query(self.model)

total = query.count()
if query is None:
query = select(self.model)
count_query = select(func.count()).select_from(self.model)
else:
count_query = select(func.count()).select_from(query.subquery())

if list_options.order_by:
column = list_options.order_by
Expand All @@ -47,10 +50,12 @@ def list(
query = query.order_by(by(column))

query = query.offset(list_options.page_size * (list_options.page - 1))

query = query.limit(list_options.page_size)

total = db.execute(count_query).scalar_one()

return ListResponse(
data=query.all(),
data=db.execute(query).scalars().all(),
page=list_options.page,
page_size=list_options.page_size,
total=total,
Expand Down
Loading