Optimize GetAll genres query

This commit is contained in:
Deluan 2021-07-19 15:30:22 -04:00 committed by Deluan Quintão
parent 1471e1240d
commit b6e9ec4db4
3 changed files with 8 additions and 17 deletions

View File

@ -10,6 +10,6 @@ type Genre struct {
type Genres []Genre
type GenreRepository interface {
GetAll() (Genres, error)
Put(m *Genre) error
GetAll(...QueryOptions) (Genres, error)
Put(*Genre) error
}

View File

@ -26,14 +26,10 @@ func NewGenreRepository(ctx context.Context, o orm.Ormer) model.GenreRepository
return r
}
func (r *genreRepository) GetAll() (model.Genres, error) {
sq := Select("genre.*",
"count(distinct a.album_id) as album_count",
"count(distinct f.media_file_id) as song_count").
From(r.tableName).
LeftJoin("album_genres a on a.genre_id = genre.id").
LeftJoin("media_file_genres f on f.genre_id = genre.id").
GroupBy("genre.id")
func (r *genreRepository) GetAll(opt ...model.QueryOptions) (model.Genres, error) {
sq := r.newSelect(opt...).Columns("genre.id", "genre.name", "a.album_count", "m.song_count").
LeftJoin("(select ag.genre_id, count(ag.album_id) as album_count from album_genres ag group by ag.genre_id) a on a.genre_id = genre.id").
LeftJoin("(select mg.genre_id, count(mg.media_file_id) as song_count from media_file_genres mg group by mg.genre_id) m on m.genre_id = genre.id")
res := model.Genres{}
err := r.queryAll(sq, &res)
return res, err

View File

@ -3,9 +3,7 @@ package subsonic
import (
"context"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/navidrome/navidrome/conf"
@ -209,19 +207,16 @@ func (c *BrowsingController) GetSong(w http.ResponseWriter, r *http.Request) (*r
func (c *BrowsingController) GetGenres(w http.ResponseWriter, r *http.Request) (*responses.Subsonic, error) {
ctx := r.Context()
genres, err := c.ds.Genre(ctx).GetAll()
genres, err := c.ds.Genre(ctx).GetAll(model.QueryOptions{Sort: "name"})
if err != nil {
log.Error(r, err)
return nil, err
}
for i, g := range genres {
if strings.TrimSpace(g.Name) == "" {
if g.Name == "" {
genres[i].Name = "<Empty>"
}
}
sort.Slice(genres, func(i, j int) bool {
return genres[i].Name < genres[j].Name
})
response := newResponse()
response.Genres = toGenres(genres)