From dcc25de2acca200848042df668b45d950d92aa25 Mon Sep 17 00:00:00 2001 From: Frank Somers Date: Wed, 29 Nov 2017 22:40:18 +0000 Subject: [PATCH] sqlx.Connect: Close db connection if db.Ping() fails If the db open succeeds but the Ping() fails, close the connection and return nil along with the error to prevent resource leakage. Fixes #366 --- sqlx.go | 8 ++++++-- sqlx_test.go | 5 ++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/sqlx.go b/sqlx.go index 4859d5ac..e95f23ff 100644 --- a/sqlx.go +++ b/sqlx.go @@ -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. diff --git a/sqlx_test.go b/sqlx_test.go index 5752773a..9502c13e 100644 --- a/sqlx_test.go +++ b/sqlx_test.go @@ -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) {