// update the CloseJira status into the database
Problem Statement - Golang how and where to call autogeneratedjiraclose() function to run some operation if rollback trigger.
func CloseJira(qMonName string) {
tx, err := dbCon.Begin()
notifier.CheckErr(err, "CloseJira() -> tx -> dbCon.Begin()", dbErrLog)
defer tx.Rollback()
stmt, errDBPrepare := tx.Prepare("update TABLE1 set
Key=NULL, StatusKey='Closed', Statustime_UTC=? where Name=?")
//Update db table record
notifier.CheckErr(errDBPrepare, "updateCloseJira() -> dbCon.Prepare()",
dbErrLog)
defer stmt.Close() // danger!
res, errStmtExec := stmt.Exec(time.Now().UTC(), qMonName)
notifier.CheckErr(errStmtExec, "CloseJira() -> stmt.Exec()", dbErrLog)
err = tx.Commit()
notifier.CheckErr(err, "CloseJira() -> err -> tx.Commit()", dbErrLog)
_, errRowAffected := res.RowsAffected()
notifier.CheckErr(errRowAffected, "CloseJira() -> res.RowsAffected()",
dbErrLog)
}
Here is pattern I use often when I need a transaction:
func Foo() (err error) {
var tx *sql.Tx
tx, err = db.Begin()
if err != nil {
return err
}
defer func() {
if err == nil {
tx.Commit()
} else {
tx.Rollback()
}
}()
// Do whatever you want here.
}
The trick is that here, the deferred function will always run at the end. If your function returns with an error, you can get it and rollback (and take whatever other action you want to), and if the function returns normally, you can commit the transaction.