Skip to content

Instantly share code, notes, and snippets.

@bkeroackdsc
Last active Dec 10, 2018
Embed
What would you like to do?
// example of using a txn
import "github.com/pkg/errors"
import "database/sql"
// ...
// UpdateUserEmailAddress updates a user's email address and adds a user event, or returns an error
func (ds *Datastore) UpdateUserEmailAddress(id uint64, emailAddress string) (err error) {
tx, err := ds.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil {
return errors.Wrap(err, "error starting txn")
}
defer func() {
if err != nil {
_ = tx.Rollback()
}
}()
_, execErr := tx.Exec(`UPDATE users SET email = ? WHERE id = ?;`, emailAddress, id)
if execErr != nil {
return errors.Wrap(err, "error updating users record")
}
_, execErr = tx.Exec(`INSERT INTO user_events (id, event_msg) VALUES (?,?);`, id, "email updated to "+emailAddress)
if execErr != nil {
return errors.Wrap(err, "error adding user event")
}
if err := tx.Commit(); err != nil {
return errors.Wrap(err, "error committing txn")
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment