Last active
August 29, 2015 14:02
-
-
Save alecthomas/bb00f91b0f1c884e01b9 to your computer and use it in GitHub Desktop.
CommitOrRollbackOnError commits or rolls back a transaction based on the value of an error reference.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// CommitOrRollbackOnError commits or rolls back a transaction based on the | |
// value of an error reference. It helps avoid error prone boilerplate | |
// rollback calls. | |
// | |
// Most useful in a defer statement: | |
// | |
// tx, err := db.Begin() | |
// if err != nil { | |
// return err | |
// } | |
// defer CommitOrRollbackOnError(tx, &err) | |
// | |
// _, err = tx.Exec("INSERT INTO x ...") | |
// if err != nil { | |
// return err | |
// } | |
// _, err = tx.Exec("INSERT INTO y ...") | |
// if err != nil { | |
// return err | |
// } | |
// | |
// return nil | |
// | |
// Replacing: | |
// | |
// tx, err := db.Begin() | |
// if err != nil { return err } | |
// | |
// // _, err = tx.Exec("INSERT INTO x ...") | |
// if err != nil { | |
// rx.Rollback() | |
// return err | |
// } | |
// _, err = tx.Exec("INSERT INTO y ...") | |
// if err != nil { | |
// tx.Rollback() | |
// return err | |
// } | |
// | |
// tx.Commit() | |
// return nil | |
// | |
// Note that error values assigned in nested scopes will create | |
// completely new variables and this trick will not work. | |
func CommitOrRollbackOnError(tx *sql.Tx, err *error) { | |
if *err == nil { | |
tx.Commit() | |
} else { | |
tx.Rollback() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment