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"` Updated time.Time `db:"updated_at"`
} }
// UpsertImdbRating upsert a ImdbRating in the database // TxUpsertImdbRating upsert a ImdbRating in a transaction
func UpsertImdbRating(db *sqlx.DB, rating *ImdbRating) error { func TxUpsertImdbRating(t *sqlx.Tx, rating *ImdbRating) error {
r, err := db.NamedQuery(upsertRatingQuery, rating) _, err := t.NamedExec(upsertRatingQuery, rating)
if err != nil { return err
return err
}
defer r.Close()
return nil
} }

View File

@ -49,6 +49,11 @@ func Refresh(env *web.Env) error {
return err return err
} }
tx, err := env.Database.Beginx()
if err != nil {
return err
}
// Read it // Read it
scanner := bufio.NewScanner(r) scanner := bufio.NewScanner(r)
for scanner.Scan() { for scanner.Scan() {
@ -69,16 +74,24 @@ func Refresh(env *web.Env) error {
continue continue
} }
movie := &backend.ImdbRating{ videoRating := &backend.ImdbRating{
ImdbID: elmts[0], ImdbID: elmts[0],
Rating: float32(rating), Rating: float32(rating),
Votes: int(numVote), Votes: int(numVote),
} }
err = backend.UpsertImdbRating(env.Database, movie) err = backend.TxUpsertImdbRating(tx, videoRating)
if err != nil { 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 err
} }
} }
return nil return tx.Commit()
} }