diff --git a/store/cmd_hist.go b/store/cmd_hist.go index 2736f32f..0e89a90e 100644 --- a/store/cmd_hist.go +++ b/store/cmd_hist.go @@ -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) } } diff --git a/store/sqlutil.go b/store/sqlutil.go index b3af9df9..ff9a934f 100644 --- a/store/sqlutil.go +++ b/store/sqlutil.go @@ -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 +}