Skip to content

Commit

Permalink
database/sql: correctly report MaxIdleClosed stat
Browse files Browse the repository at this point in the history
Previously the MaxIdleClosed counter was incremented when added
to the free connection list, rather then when it wasn't added
to the free connection list. Flip this logic to correct.

Fixes golang#27792

Change-Id: I405302c14fb985369dab48fbe845e5651afc4ccf
Reviewed-on: https://go-review.googlesource.com/c/138578
Run-TryBot: Daniel Theophanes <[email protected]>
TryBot-Result: Gobot Gobot <[email protected]>
Reviewed-by: Brad Fitzpatrick <[email protected]>
  • Loading branch information
kardianos committed Oct 2, 2018
1 parent 9aed4cc commit 7db509e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/database/sql/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -1322,11 +1322,13 @@ func (db *DB) putConnDBLocked(dc *driverConn, err error) bool {
err: err,
}
return true
} else if err == nil && !db.closed && db.maxIdleConnsLocked() > len(db.freeConn) {
db.freeConn = append(db.freeConn, dc)
} else if err == nil && !db.closed {
if db.maxIdleConnsLocked() > len(db.freeConn) {
db.freeConn = append(db.freeConn, dc)
db.startCleanerLocked()
return true
}
db.maxIdleClosed++
db.startCleanerLocked()
return true
}
return false
}
Expand Down
52 changes: 52 additions & 0 deletions src/database/sql/sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3415,6 +3415,58 @@ func TestConnectionLeak(t *testing.T) {
wg.Wait()
}

func TestStatsMaxIdleClosedZero(t *testing.T) {
db := newTestDB(t, "people")
defer closeDB(t, db)

db.SetMaxOpenConns(1)
db.SetMaxIdleConns(1)
db.SetConnMaxLifetime(0)

preMaxIdleClosed := db.Stats().MaxIdleClosed

for i := 0; i < 10; i++ {
rows, err := db.Query("SELECT|people|name|")
if err != nil {
t.Fatal(err)
}
rows.Close()
}

st := db.Stats()
maxIdleClosed := st.MaxIdleClosed - preMaxIdleClosed
t.Logf("MaxIdleClosed: %d", maxIdleClosed)
if maxIdleClosed != 0 {
t.Fatal("expected 0 max idle closed conns, got: ", maxIdleClosed)
}
}

func TestStatsMaxIdleClosedTen(t *testing.T) {
db := newTestDB(t, "people")
defer closeDB(t, db)

db.SetMaxOpenConns(1)
db.SetMaxIdleConns(0)
db.SetConnMaxLifetime(0)

preMaxIdleClosed := db.Stats().MaxIdleClosed

for i := 0; i < 10; i++ {
rows, err := db.Query("SELECT|people|name|")
if err != nil {
t.Fatal(err)
}
rows.Close()
}

st := db.Stats()
maxIdleClosed := st.MaxIdleClosed - preMaxIdleClosed
t.Logf("MaxIdleClosed: %d", maxIdleClosed)
if maxIdleClosed != 10 {
t.Fatal("expected 0 max idle closed conns, got: ", maxIdleClosed)
}
}

type nvcDriver struct {
fakeDriver
skipNamedValueCheck bool
Expand Down

0 comments on commit 7db509e

Please sign in to comment.