Last active
May 16, 2016 22:45
-
-
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
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
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