Skip to content

Instantly share code, notes, and snippets.

@robdaemon
Created October 8, 2014 03:24
Show Gist options
  • Select an option

  • Save robdaemon/6213eb0cac14e1e0860f to your computer and use it in GitHub Desktop.

Select an option

Save robdaemon/6213eb0cac14e1e0860f to your computer and use it in GitHub Desktop.
pattern
db.StartTransaction
err := db.Execute
if err != nil {
db.Rollback
return
}
err := db.Execute
if err != nil {
db.Rollback
return
}
db.Commit
return
@jjhuff
Copy link

jjhuff commented Oct 8, 2014

Yeah, I agree, duplicating code like that is bad, but this is hardly a new problem that only exceptions can solve!

I'd consider most of the transaction handling code (Start/Rollback/Commit) boilerplate, so why not pull it out to begin with? Sort of a nano-framework. Or use goto, or defer.

I tossed a couple things together:
https://gist.github.com/jjhuff/77f61fb9daf72cff9e01

The first two options have the nice property that you can compose operations in the same transaction:
RunInTransaction(func(db *Database) error {
err := updateUserFullName(db)
if err == nil {
err = updatePassword(db)
}
return err
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment