Skip to content

Instantly share code, notes, and snippets.

@nesv
Last active May 16, 2016 22:45
Show Gist options
  • Save nesv/db63d3f35ce88c9bb411bd6beb4cc60f to your computer and use it in GitHub Desktop.
Save nesv/db63d3f35ce88c9bb411bd6beb4cc60f to your computer and use it in GitHub Desktop.
A function that wraps your SQL interactions in a transaction, and handles errors
var db *sql.DB
func WithTx(fn func(*sql.Tx) error) error {
tx, err := db.Begin()
if err != nil {
return err
}
if err := fn(tx); err != nil {
if err := tx.Rollback(); err != nil {
return fmt.Errorf("failed to rollback transaction: %v", err)
}
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %v", err)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment