Skip to content

Commit

Permalink
sqlx.Connect: Close db connection if db.Ping() fails
Browse files Browse the repository at this point in the history
If the db open succeeds but the Ping() fails, close the
connection and return nil along with the error to prevent
resource leakage.

Fixes jmoiron#366
  • Loading branch information
somersf committed Nov 29, 2017
1 parent 3379e59 commit dcc25de
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 dcc25de

Please sign in to comment.