From be4f19757cf2cb6374aa9aeda688683df2214624 Mon Sep 17 00:00:00 2001 From: Keith Edmunds Date: Thu, 22 Dec 2022 17:41:46 +0000 Subject: [PATCH] Improve performance of save_playlist --- app/models.py | 21 +++++++++++++++++++++ app/playlists.py | 6 +++--- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/app/models.py b/app/models.py index 7ecfccc..9a961bb 100644 --- a/app/models.py +++ b/app/models.py @@ -593,6 +593,27 @@ class PlaylistRows(Base): .values(row_number=PlaylistRows.row_number + move_by) ) + @staticmethod + def indexed_by_row(session: Session, playlist_id: int) -> dict: + """ + Return a dictionary of playlist_rows indexed by row number for + the passed playlist_id. + """ + + plrs = session.execute( + select(PlaylistRows) + .where( + PlaylistRows.playlist_id == playlist_id, + ) + .order_by(PlaylistRows.row_number) + ).scalars().all() + + result = {} + for plr in plrs: + result[plr.row_number] = plr + + return result + class Settings(Base): """Manage settings""" diff --git a/app/playlists.py b/app/playlists.py index b645ad1..dca8dd1 100644 --- a/app/playlists.py +++ b/app/playlists.py @@ -827,11 +827,11 @@ class PlaylistTab(QTableWidget): the row number is correct (in case tracks have been reordered). """ + plr_dict = PlaylistRows.indexed_by_row(session, self.playlist_id) for row in range(self.rowCount()): - plr = session.get(PlaylistRows, self._get_playlistrow_id(row)) # Set the row number and playlist id (even if correct) - plr.row_number = row - plr.playlist_id = self.playlist_id + plr_dict[row].row_number = row + plr_dict[row].playlist_id = self.playlist_id # Any rows in the database with a row_number higher that the # current value of 'row' should not be there. Commit session