Created
September 4, 2017 20:59
-
-
Save lyoshenka/2b969e6461978e6a096501bca5cdb369 to your computer and use it in GitHub Desktop.
A simple, neat way to wrap code in an sql transaction with proper committing/rollbacking and error handling.
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
// TxFunc is a function that can be wrapped in a transaction | |
type TxFunc func(tx *sql.Tx) error | |
// WithTx wraps a function in an sql transaction. After the function returns, the transaction is | |
// committed if there's no error, or rolled back if there is one. | |
func WithTx(db *sql.DB, f TxFunc) (err error) { | |
tx, err := db.Begin() | |
if err != nil { | |
return err | |
} | |
defer func() { | |
if p := recover(); p != nil { | |
tx.Rollback() | |
panic(p) | |
} else if err != nil { | |
tx.Rollback() | |
} else { | |
err = tx.Commit() | |
} | |
}() | |
return f(tx) | |
} |
Hi,
You're not checking errors on Rollback()'s. 'gometalinter' can help you with detecting these errors at compile-time.
Cheers,
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a simple example: