Skip to content

Commit

Permalink
Add database.go, Rollback()
Browse files Browse the repository at this point in the history
  • Loading branch information
bahlo committed Sep 1, 2015
1 parent 0ca411a commit 8af2599
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
17 changes: 17 additions & 0 deletions database.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package abutil

import (
"database/sql"
)

// Rollback does a rollback on the transaction and returns either the error
// from the rollback if there was one or the alternative.
// This is useful if you have multiple statments in a row but don't want to
// call rollback and check for errors every time.
func Rollback(tx *sql.Tx, alt error) error {
if err := tx.Rollback(); err != nil {
return err
}

return alt
}
58 changes: 58 additions & 0 deletions database_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package abutil

import (
"database/sql"
"errors"
"testing"

"github.com/DATA-DOG/go-sqlmock"
)

func mockDBContext(t *testing.T, fn func(*sql.DB)) {
db, err := sqlmock.New()
if err != nil {
t.Error(err)
}
defer db.Close()

fn(db)
}

func TestRollback(t *testing.T) {
mockDBContext(t, func(db *sql.DB) {
sqlmock.ExpectBegin()
sqlmock.ExpectRollback()

tx, err := db.Begin()
if err != nil {
t.Error(err)
}

alt := errors.New("Some alternative error")
err = Rollback(tx, alt)

if err != alt {
t.Errorf("Expected Rollback to return %v, but got %v", alt, err)
}
})
}

func TestRollbackFailing(t *testing.T) {
mockDBContext(t, func(db *sql.DB) {
rberr := errors.New("Some rollback error")

sqlmock.ExpectBegin()
sqlmock.ExpectRollback().
WillReturnError(rberr)

tx, err := db.Begin()
if err != nil {
t.Error(err)
}

err = Rollback(tx, errors.New("This should not be used"))
if err != rberr {
t.Errorf("Expected Rollback to return %v, but got %v", rberr, err)
}
})
}

0 comments on commit 8af2599

Please sign in to comment.