Skip to content

Commit

Permalink
Broken DB connection no longer causes panic
Browse files Browse the repository at this point in the history
  • Loading branch information
Calebjh committed Dec 10, 2018
1 parent 0c9e9ea commit 57fe82a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
11 changes: 10 additions & 1 deletion gorm/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gorm
import (
"context"
"errors"
"reflect"
"sync"

"github.com/infobloxopen/atlas-app-toolkit/rpc/errdetails"
Expand Down Expand Up @@ -89,6 +90,9 @@ func (t *Transaction) Rollback() error {
if t.current == nil {
return nil
}
if reflect.ValueOf(t.current.CommonDB()).IsNil() {
return status.Error(codes.Unavailable, "Database connection not available")
}
t.mu.Lock()
defer t.mu.Unlock()

Expand All @@ -101,7 +105,7 @@ func (t *Transaction) Rollback() error {
// Commit finishes transaction by calling `*gorm.DB.Commit()`
// Reset current transaction and returns an error if any.
func (t *Transaction) Commit(ctx context.Context) error {
if t.current == nil {
if t.current == nil || reflect.ValueOf(t.current.CommonDB()).IsNil() {
return nil
}
t.mu.Lock()
Expand Down Expand Up @@ -150,6 +154,11 @@ func UnaryServerInterceptor(db *gorm.DB) grpc.UnaryServerInterceptor {
if terr == nil {
return
}
// Catch the status: UNAVAILABLE error that Rollback might return
if _, ok := status.FromError(terr); ok {
err = terr
return
}

st := status.Convert(err)
st, serr := st.WithDetails(errdetails.New(codes.Internal, "gorm", terr.Error()))
Expand Down
10 changes: 10 additions & 0 deletions gorm/transaction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gorm
import (
"context"
"errors"
"reflect"
"testing"

"github.com/DATA-DOG/go-sqlmock"
Expand Down Expand Up @@ -240,6 +241,15 @@ func TestTransaction_Rollback(t *testing.T) {
if txn.current != nil {
t.Error("failed to reset current gorm instance - txn.current is not nil")
}

fdb, err := gorm.Open("postgres", db)
fdb.Close()
txn = &Transaction{parent: gdb}

txn.Begin()
if err := txn.Rollback(); !reflect.DeepEqual(err, status.Error(codes.Unavailable, "Database connection not available")) {
t.Errorf("Did not receive proper error for broken DB - %s", err)
}
}

func TestContext(t *testing.T) {
Expand Down

0 comments on commit 57fe82a

Please sign in to comment.