Skip to content

Commit

Permalink
optimize: make order indexing blazingly fast
Browse files Browse the repository at this point in the history
  • Loading branch information
kraanzu committed Sep 22, 2024
1 parent 2dd0744 commit 2873026
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 8 deletions.
25 changes: 25 additions & 0 deletions dooit/api/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,25 @@ def shift_up(self) -> bool:

return True

def _add_sibling(self) -> Self:
raise NotImplementedError

def add_sibling(self):
sibling = self._add_sibling()
index = self.order_index

cls = self.__class__
manager.session.query(cls).filter(cls.order_index > index).update(
{cls.order_index: cls.order_index + 1},
synchronize_session=False,
)

sibling.order_index = index + 1
manager.session.add(sibling)
manager.session.commit()

return sibling

def shift_down(self) -> bool:
"""
Shift the item one place down among its siblings
Expand All @@ -108,6 +127,12 @@ def set_order_index(self, index: int) -> None:
if index > len(self.siblings) or index < 0:
index = len(self.siblings)

cls = self.__class__
manager.session.query(cls).filter(cls.order_index >= index).update(
{cls.order_index: cls.order_index + 1},
synchronize_session=False,
)

siblings = [
i for i in self.siblings if i.id != self.id and i.order_index >= index
]
Expand Down
4 changes: 1 addition & 3 deletions dooit/api/todo.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,11 @@ def add_todo(self) -> "Todo":
todo.save()
return todo

def add_sibling(self) -> "Todo":
def _add_sibling(self) -> "Todo":
todo = Todo(
parent_todo=self.parent_todo,
parent_workspace=self.parent_workspace,
)
todo.save()
todo.set_order_index(self.order_index + 1)
return todo

# ----------- HELPER FUNCTIONS --------------
Expand Down
9 changes: 4 additions & 5 deletions dooit/api/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,10 @@ def add_todo(self) -> "Todo":
todo.save()
return todo

def add_sibling(self) -> "Workspace":
assert self.parent_workspace is not None

workspace = self.parent_workspace.add_workspace()
workspace.set_order_index(self.order_index + 1)
def _add_sibling(self) -> "Workspace":
workspace = Workspace(
parent_workspace=self.parent_workspace,
)
return workspace

def save(self) -> None:
Expand Down

0 comments on commit 2873026

Please sign in to comment.