On Wed, 5 Dec 2018 at 18:55, 'Eric Johnson' via golang-nuts < golang-nuts@googlegroups.com> wrote:
> I always go with the approach that uses the equivalent of the "Transact()" > method. > > On top of that, rather than use a generic *sql.Tx parameter to the > "txFunc" function, I pass an interface that is specific to the operations > of the database layer for my application. > That's an interesting idea. For the record, this is the code we use: package transaction import ( "context" "database/sql" "fmt" "gopkg.in/errgo.v1" ) // WithTxn executes a function inside a transaction context. func WithTxn(db *sql.DB, ctx context.Context, f func(*sql.Tx) error) error { txn, err := db.BeginTx(ctx, nil) if err != nil { return errgo.Mask(err) } if err := f(txn); err != nil { return rollback(txn, err) } return rollback(txn, txn.Commit()) } func rollback(txn *sql.Tx, err error) error { if err == nil { return nil } errRollback := txn.Rollback() if errRollback != nil { return errgo.NoteMask(err, fmt.Sprintf("failed to roll back (error: %v) after", errRollback), errgo.Any) } return err } > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.