Last active
December 10, 2018 23:50
-
-
Save bkeroackdsc/9aabf1994412e3d111fdbde1b2e0ff56 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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