store: Factor out a transaction helper.

This commit is contained in:
Qi Xiao 2016-02-13 12:49:27 +01:00
parent 4ca023cd4d
commit 149433ae9b
2 changed files with 17 additions and 11 deletions

View File

@ -15,17 +15,7 @@ func init() {
if err != nil {
return err
}
tx, err := db.Begin()
if err != nil {
return err
}
err = addLastAmongDup(tx)
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
return err
return transaction(db, addLastAmongDup)
}
}

View File

@ -25,3 +25,19 @@ func hasColumn(rows *sql.Rows, colname string) (bool, error) {
}
return false, rows.Err()
}
// transaction creates a Tx and calls f on it. It commits or rollbacks the
// transaction depending on whether f suceeded.
func transaction(db *sql.DB, f func(*sql.Tx) error) error {
tx, err := db.Begin()
if err != nil {
return err
}
err = f(tx)
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
return err
}