Skip to content

Instantly share code, notes, and snippets.

@thoas
Created August 10, 2018 10:06
Show Gist options
  • Save thoas/93606d86de2b75c2ad41147317aa9e06 to your computer and use it in GitHub Desktop.
Save thoas/93606d86de2b75c2ad41147317aa9e06 to your computer and use it in GitHub Desktop.
func Transaction(driver Driver, handler func(driver Driver) error) error {
if driver == nil {
return errors.Wrap(ErrInvalidDriver, "sqlxx: cannot create a transaction")
}
tx, err := driver.Beginx()
if err != nil {
return errors.Wrap(err, "sqlxx: cannot create a transaction")
}
client := &Client{Node: tx}
err = handler(client)
if err != nil {
thr := tx.Rollback()
if thr != nil {
// TODO: Add an observer to collect this error.
thr = errors.Wrap(thr, "sqlxx: cannot rollback transaction")
_ = thr
}
return err
}
err = tx.Commit()
if err != nil {
return errors.Wrap(err, "sqlxx: cannot commit transaction")
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment