Simplify queries to move song in playlist

This commit is contained in:
vfsfitvnm 2022-09-15 18:56:34 +02:00
parent 19b19fe958
commit e13d083a8c
3 changed files with 14 additions and 41 deletions

View file

@ -197,14 +197,16 @@ interface Database {
@RewriteQueriesToDropUnusedColumns
fun songsWithContentLength(): Flow<List<DetailedSongWithContentLength>>
@Query("UPDATE SongPlaylistMap SET position = position - 1 WHERE playlistId = :playlistId AND position >= :fromPosition")
fun decrementSongPositions(playlistId: Long, fromPosition: Int)
@Query("UPDATE SongPlaylistMap SET position = position - 1 WHERE playlistId = :playlistId AND position >= :fromPosition AND position <= :toPosition")
fun decrementSongPositions(playlistId: Long, fromPosition: Int, toPosition: Int)
@Query("UPDATE SongPlaylistMap SET position = position + 1 WHERE playlistId = :playlistId AND position >= :fromPosition AND position <= :toPosition")
fun incrementSongPositions(playlistId: Long, fromPosition: Int, toPosition: Int)
@Query("""
UPDATE SongPlaylistMap SET position =
CASE
WHEN position < :fromPosition THEN position + 1
WHEN position > :fromPosition THEN position - 1
ELSE :toPosition
END
WHERE playlistId = :playlistId AND position BETWEEN MIN(:fromPosition,:toPosition) and MAX(:fromPosition,:toPosition)
""")
fun move(playlistId: Long, fromPosition: Int, toPosition: Int)
@Query("DELETE FROM SongPlaylistMap WHERE playlistId = :id")
fun clearPlaylist(id: Long)

View file

@ -132,17 +132,8 @@ fun InPlaylistMediaItemMenu(
onDismiss = onDismiss,
onRemoveFromPlaylist = {
transaction {
Database.delete(
SongPlaylistMap(
songId = song.id,
playlistId = playlistId,
position = positionInPlaylist
)
)
Database.decrementSongPositions(
playlistId = playlistId,
fromPosition = positionInPlaylist + 1
)
Database.move(playlistId, positionInPlaylist, Int.MAX_VALUE)
Database.delete(SongPlaylistMap(song.id, playlistId, Int.MAX_VALUE))
}
},
modifier = modifier

View file

@ -92,28 +92,8 @@ fun LocalPlaylistScreen(playlistId: Long) {
lazyListState = lazyListState,
key = playlistWithSongs.songs,
onDragEnd = { fromIndex, toIndex ->
transaction {
if (fromIndex > toIndex) {
Database.incrementSongPositions(
playlistId = playlistWithSongs.playlist.id,
fromPosition = toIndex,
toPosition = fromIndex - 1
)
} else if (fromIndex < toIndex) {
Database.decrementSongPositions(
playlistId = playlistWithSongs.playlist.id,
fromPosition = fromIndex + 1,
toPosition = toIndex
)
}
Database.update(
SongPlaylistMap(
songId = playlistWithSongs.songs[fromIndex].id,
playlistId = playlistWithSongs.playlist.id,
position = toIndex
)
)
query {
Database.move(playlistWithSongs.playlist.id, fromIndex, toIndex)
}
},
extraItemCount = 1