Skip to content

Commit

Permalink
add genres index and sort order filter
Browse files Browse the repository at this point in the history
  • Loading branch information
denpeshkov committed Jan 31, 2024
1 parent 084ffbf commit d18f097
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP INDEX IF EXISTS movies_genres_idx;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CREATE INDEX IF NOT EXISTS movies_genres_idx ON movies USING GIN (genres);
11 changes: 9 additions & 2 deletions internal/postgres/movie.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"log/slog"
"strings"

"github.com/denpeshkov/greenlight/internal/greenlight"
"github.com/lib/pq"
Expand Down Expand Up @@ -52,11 +53,17 @@ func (s *MovieService) GetMovies(ctx context.Context, filter greenlight.MovieFil
ctx, cancel := context.WithTimeout(ctx, s.db.opts.queryTimeout)
defer cancel()

query := `
sortCol, sortDir := filter.Sort, "ASC"
if v, ok := strings.CutPrefix(sortCol, "-"); ok {
sortCol = v
sortDir = "DESC"
}

query := fmt.Sprintf(`
SELECT id, title, release_date, runtime, genres, version
FROM movies
WHERE (LOWER(title) = LOWER($1) OR $1 = '') AND (genres @> $2 OR $2 = '{}')
ORDER BY id ASC`
ORDER BY %s %s, id ASC`, sortCol, sortDir)
rs, err := s.db.db.QueryContext(ctx, query, filter.Title, pq.Array(filter.Genres))
if err != nil {
return nil, fmt.Errorf("%s: %w", op, err)
Expand Down

0 comments on commit d18f097

Please sign in to comment.