From 4b90b7a28a0c1a849eed765cc511eacbae4d2651 Mon Sep 17 00:00:00 2001 From: INADA Naoki Date: Wed, 26 Oct 2016 17:11:13 +0900 Subject: database/sql: add Pinger interface to driver Conn Change-Id: If6eb3a7c9ad48a517e584567b1003479c1df6cca Reviewed-on: https://go-review.googlesource.com/32136 Reviewed-by: Daniel Theophanes Reviewed-by: Brad Fitzpatrick Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot --- src/database/sql/sql.go | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) (limited to 'src/database/sql/sql.go') diff --git a/src/database/sql/sql.go b/src/database/sql/sql.go index 3cef4b6404..6d2dcb8c73 100644 --- a/src/database/sql/sql.go +++ b/src/database/sql/sql.go @@ -553,15 +553,27 @@ func Open(driverName, dataSourceName string) (*DB, error) { // PingContext verifies a connection to the database is still alive, // establishing a connection if necessary. func (db *DB) PingContext(ctx context.Context) error { - // TODO(bradfitz): give drivers an optional hook to implement - // this in a more efficient or more reliable way, if they - // have one. - dc, err := db.conn(ctx, cachedOrNewConn) + var dc *driverConn + var err error + + for i := 0; i < maxBadConnRetries; i++ { + dc, err = db.conn(ctx, cachedOrNewConn) + if err != driver.ErrBadConn { + break + } + } + if err == driver.ErrBadConn { + dc, err = db.conn(ctx, alwaysNewConn) + } if err != nil { return err } - db.putConn(dc, nil) - return nil + + if pinger, ok := dc.ci.(driver.Pinger); ok { + err = pinger.Ping(ctx) + } + db.putConn(dc, err) + return err } // Ping verifies a connection to the database is still alive, -- cgit v1.3