Refresh the imdb ratings in a transaction

https://w000t.me/c140729392
This commit is contained in:
Lucas BEE 2019-05-15 13:07:59 +00:00
parent bd20acd9e5
commit d4e633283d
2 changed files with 20 additions and 12 deletions

View File

@ -25,13 +25,8 @@ type ImdbRating struct {
Updated time.Time `db:"updated_at"`
}
// UpsertImdbRating upsert a ImdbRating in the database
func UpsertImdbRating(db *sqlx.DB, rating *ImdbRating) error {
r, err := db.NamedQuery(upsertRatingQuery, rating)
if err != nil {
// TxUpsertImdbRating upsert a ImdbRating in a transaction
func TxUpsertImdbRating(t *sqlx.Tx, rating *ImdbRating) error {
_, err := t.NamedExec(upsertRatingQuery, rating)
return err
}
defer r.Close()
return nil
}

View File

@ -49,6 +49,11 @@ func Refresh(env *web.Env) error {
return err
}
tx, err := env.Database.Beginx()
if err != nil {
return err
}
// Read it
scanner := bufio.NewScanner(r)
for scanner.Scan() {
@ -69,16 +74,24 @@ func Refresh(env *web.Env) error {
continue
}
movie := &backend.ImdbRating{
videoRating := &backend.ImdbRating{
ImdbID: elmts[0],
Rating: float32(rating),
Votes: int(numVote),
}
err = backend.UpsertImdbRating(env.Database, movie)
err = backend.TxUpsertImdbRating(tx, videoRating)
if err != nil {
log.WithFields(logrus.Fields{
"error": err,
}).Error("got error while upserting rating, rollback!")
if rollbackErr := tx.Rollback(); err != nil {
log.WithFields(logrus.Fields{
"error": rollbackErr,
}).Error("unable to rollack")
}
return err
}
}
return nil
return tx.Commit()
}