Skip to content

Commit

Permalink
Optimize GET /section performance by minimizing SQL queries
Browse files Browse the repository at this point in the history
  • Loading branch information
m-danya committed Dec 29, 2024
1 parent 7b7ad1e commit 4fd7303
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 18 deletions.
2 changes: 1 addition & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
Expand Down
2 changes: 1 addition & 1 deletion planty/infrastructure/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ class SectionModel(Base):

index: Mapped[int] # ordering inside parent

tasks = relationship(
tasks: Mapped[list[TaskModel]] = relationship(
"TaskModel",
back_populates="section",
order_by="TaskModel.index",
Expand Down
24 changes: 8 additions & 16 deletions planty/infrastructure/repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,19 +140,6 @@ def _fill_in_model_except_index(self, task: Task, task_model: TaskModel) -> None
task_model.recurrence_type = task.recurrence.type
task_model.flexible_recurrence_mode = task.recurrence.flexible_mode

async def get_section_tasks(self, section_id: UUID) -> list[Task]:
result = await self._db_session.execute(
select(TaskModel)
.where(
(TaskModel.section_id == section_id)
& (TaskModel.is_archived.is_(False))
)
.options(selectinload(TaskModel.attachments))
.order_by(TaskModel.index)
)
task_models = result.scalars().all()
return await self.get_entities(task_models)

async def search(self, user_id: UUID, query: str) -> list[Task]:
# TODO: Reimplement search to improve performance. Possible options:
# 1) Use PostgreSQL Full-text search ( => deal with SQLite separately.. )
Expand Down Expand Up @@ -246,13 +233,18 @@ async def get(
with_direct_subsections: bool = False,
) -> Section:
result = await self._db_session.execute(
select(SectionModel).where(SectionModel.id == section_id)
select(SectionModel)
.where(SectionModel.id == section_id)
.options(
selectinload(SectionModel.tasks).selectinload(TaskModel.attachments)
)
)
section_model: Optional[SectionModel] = result.scalar_one_or_none()
if section_model is None:
raise SectionNotFoundException(section_id=section_id)
# TODO use .options(selectinload(SectionModel.tasks)) instead
tasks = await self._task_repo.get_section_tasks(section_id)
# filter out archived tasks from section tasks
task_models = [tm for tm in section_model.tasks if not tm.is_archived]
tasks = await self._task_repo.get_entities(task_models)
subsections = []
if with_direct_subsections:
subsection_models = (
Expand Down

0 comments on commit 4fd7303

Please sign in to comment.