Skip to content

Commit

Permalink
Merge pull request jmoiron#370 from somersf/connect-close-on-error
Browse files Browse the repository at this point in the history
sqlx.Connect: Close db connection if db.Ping() fails
  • Loading branch information
jmoiron authored Nov 29, 2017
2 parents 3379e59 + dcc25de commit 99f3ad6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
8 changes: 6 additions & 2 deletions sqlx.go
Original file line number Diff line number Diff line change
Expand Up @@ -627,10 +627,14 @@ func (r *Rows) StructScan(dest interface{}) error {
func Connect(driverName, dataSourceName string) (*DB, error) {
db, err := Open(driverName, dataSourceName)
if err != nil {
return db, err
return nil, err
}
err = db.Ping()
return db, err
if err != nil {
db.Close()
return nil, err
}
return db, nil
}

// MustConnect connects to a database and panics on error.
Expand Down
5 changes: 4 additions & 1 deletion sqlx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1296,10 +1296,13 @@ type Product struct {
// tests that sqlx will not panic when the wrong driver is passed because
// of an automatic nil dereference in sqlx.Open(), which was fixed.
func TestDoNotPanicOnConnect(t *testing.T) {
_, err := Connect("bogus", "hehe")
db, err := Connect("bogus", "hehe")
if err == nil {
t.Errorf("Should return error when using bogus driverName")
}
if db != nil {
t.Errorf("Should not return the db on a connect failure")
}
}

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

0 comments on commit 99f3ad6

Please sign in to comment.