canape/backend/models/movies.go

121 lines
3.2 KiB
Go

package models
import (
"fmt"
"time"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
polochon "github.com/odwrtw/polochon/lib"
)
const (
upsertMovieQuery = `
INSERT INTO movies (imdb_id, title, rating, votes, plot, tmdb_id, year,
genres, original_title, runtime, sort_title, tagline)
VALUES (:imdb_id, :title, :rating, :votes, :plot, :tmdb_id, :year, :genres,
:original_title, :runtime, :sort_title, :tagline)
ON CONFLICT (imdb_id)
DO UPDATE
SET imdb_id=:imdb_id, title=:title, rating=:rating, votes=:votes,
plot=:plot, tmdb_id=:tmdb_id, year=:year, genres=:genres,
original_title=:original_title, runtime=:runtime, sort_title=:sort_title,
tagline=:tagline
RETURNING id;`
getMovieQueryByImdbID = `
SELECT *
FROM movies_with_rating
WHERE imdb_id=$1;`
)
// movieDB represents the Movie in the DB
type movieDB struct {
ID string `db:"id"`
ImdbID string `db:"imdb_id"`
TmdbID int `db:"tmdb_id"`
UserID *string `db:"user_id"`
Title string `db:"title"`
OriginalTitle string `db:"original_title"`
SortTitle string `db:"sort_title"`
Rating float32 `db:"rating"`
Votes int `db:"votes"`
Plot string `db:"plot"`
Year int `db:"year"`
Runtime int `db:"runtime"`
Tagline string `db:"tagline"`
Genres pq.StringArray `db:"genres"`
Created time.Time `db:"created_at"`
Updated time.Time `db:"updated_at"`
}
// GetMovie fills show details of a polochon.Movie
func GetMovie(db *sqlx.DB, pMovie *polochon.Movie) error {
var mDB movieDB
var err error
if pMovie.ImdbID != "" {
// Get the data from the DB
err = db.QueryRowx(getMovieQueryByImdbID, pMovie.ImdbID).StructScan(&mDB)
} else {
err = fmt.Errorf("Can't get movie details, you have to specify an ImdbID")
}
if err != nil {
return err
}
// Fills the polochon.Movie from the movieDB
FillFromDB(&mDB, pMovie)
return nil
}
// FillFromDB fills a Movie from a movieDB extracted from the DB
func FillFromDB(mDB *movieDB, pMovie *polochon.Movie) {
pMovie.ImdbID = mDB.ImdbID
pMovie.Title = mDB.Title
pMovie.Rating = mDB.Rating
pMovie.Votes = mDB.Votes
pMovie.Plot = mDB.Plot
pMovie.TmdbID = mDB.TmdbID
pMovie.Year = mDB.Year
pMovie.OriginalTitle = mDB.OriginalTitle
pMovie.Runtime = mDB.Runtime
pMovie.Genres = mDB.Genres
pMovie.SortTitle = mDB.SortTitle
pMovie.Tagline = mDB.Tagline
}
// UpsertMovie upsert a polochon Movie in the database
func UpsertMovie(db *sqlx.DB, pMovie *polochon.Movie) error {
mDB := NewMovieDB(pMovie)
r, err := db.NamedQuery(upsertMovieQuery, mDB)
if err != nil {
return err
}
defer r.Close()
return nil
}
// NewMovieDB returns a Movie ready to be put in DB from a
// polochon Movie
func NewMovieDB(m *polochon.Movie) movieDB {
genres := []string{}
if m.Genres != nil {
genres = m.Genres
}
return movieDB{
ImdbID: m.ImdbID,
Title: m.Title,
Rating: m.Rating,
Votes: m.Votes,
Plot: m.Plot,
TmdbID: m.TmdbID,
Year: m.Year,
OriginalTitle: m.OriginalTitle,
Runtime: m.Runtime,
SortTitle: m.SortTitle,
Tagline: m.Tagline,
Genres: genres,
}
}