107 lines
2.5 KiB
Go
107 lines
2.5 KiB
Go
package models
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
polochon "github.com/odwrtw/polochon/lib"
|
|
)
|
|
|
|
const (
|
|
upsertShowQuery = `
|
|
INSERT INTO shows (imdb_id, title, rating, plot, tvdb_id, year, first_aired)
|
|
VALUES (:imdb_id, :title, :rating, :plot, :tvdb_id, :year, :first_aired)
|
|
ON CONFLICT (imdb_id)
|
|
DO UPDATE
|
|
SET imdb_id=:imdb_id, title=:title, rating=:rating, plot=:plot,
|
|
tvdb_id=:tvdb_id, year=:year, first_aired=:first_aired
|
|
RETURNING id;`
|
|
|
|
getShowQueryByImdbID = `
|
|
SELECT *
|
|
FROM shows_with_rating WHERE imdb_id=$1;`
|
|
)
|
|
|
|
// showDB represents the Show in the DB
|
|
type showDB struct {
|
|
ID string `db:"id"`
|
|
ImdbID string `db:"imdb_id"`
|
|
TvdbID int `db:"tvdb_id"`
|
|
TrackedSeason *int `db:"season"`
|
|
TrackedEpisode *int `db:"episode"`
|
|
Title string `db:"title"`
|
|
Rating float32 `db:"rating"`
|
|
Votes int `db:"votes"`
|
|
Plot string `db:"plot"`
|
|
Year int `db:"year"`
|
|
FirstAired time.Time `db:"first_aired"`
|
|
Created time.Time `db:"created_at"`
|
|
Updated time.Time `db:"updated_at"`
|
|
}
|
|
|
|
// UpsertShow a show in the database
|
|
func UpsertShow(db *sqlx.DB, s *polochon.Show) error {
|
|
sDB := NewShowFromPolochon(s)
|
|
// Upsert the show
|
|
r, err := db.NamedQuery(upsertShowQuery, sDB)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer r.Close()
|
|
|
|
for _, e := range s.Episodes {
|
|
// Upsert its episodes
|
|
err = UpsertEpisode(db, e)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// NewShowFromPolochon returns an showDB from a polochon Show
|
|
func NewShowFromPolochon(s *polochon.Show) *showDB {
|
|
sDB := showDB{
|
|
ImdbID: s.ImdbID,
|
|
TvdbID: s.TvdbID,
|
|
Title: s.Title,
|
|
Rating: s.Rating,
|
|
Plot: s.Plot,
|
|
Year: s.Year,
|
|
}
|
|
if s.FirstAired != nil {
|
|
sDB.FirstAired = *s.FirstAired
|
|
}
|
|
return &sDB
|
|
}
|
|
|
|
// GetShow fills a show from the DB
|
|
func GetShow(db *sqlx.DB, pShow *polochon.Show) error {
|
|
var err error
|
|
var sDB showDB
|
|
if pShow.ImdbID != "" {
|
|
err = db.QueryRowx(getShowQueryByImdbID, pShow.ImdbID).StructScan(&sDB)
|
|
} else {
|
|
err = fmt.Errorf("Can't get show details, you have to specify an ID or ImdbID")
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Fill the show from the showDB
|
|
FillShowFromDB(&sDB, pShow)
|
|
return nil
|
|
}
|
|
|
|
// FillShowFromDB returns a Show from a showDB extracted from the DB
|
|
func FillShowFromDB(sDB *showDB, pShow *polochon.Show) {
|
|
pShow.ImdbID = sDB.ImdbID
|
|
pShow.Title = sDB.Title
|
|
pShow.Rating = sDB.Rating
|
|
pShow.Plot = sDB.Plot
|
|
pShow.TvdbID = sDB.TvdbID
|
|
pShow.Year = sDB.Year
|
|
pShow.FirstAired = &sDB.FirstAired
|
|
}
|