1
0
mirror of https://github.com/golang/go synced 2024-11-23 23:50:08 -07:00

database/sql: close connection if db.numOpen > db.maxOpen

Bug Description:
When reduce db.maxOpen via db.SetMaxOpenConns, the unnecssary
connections won't been released until all other connections are free.

Fixes #9453

Change-Id: I9afb2e4b184139b31029ae53d7f5fd1fdb8d8d7e
Reviewed-on: https://go-review.googlesource.com/2200
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
This commit is contained in:
Jiong Du 2014-12-30 16:12:50 +08:00 committed by Brad Fitzpatrick
parent b40421f32c
commit cce127a75f
2 changed files with 54 additions and 0 deletions

View File

@ -782,6 +782,9 @@ func (db *DB) putConn(dc *driverConn, err error) {
// If a connRequest was fulfilled or the *driverConn was placed in the
// freeConn list, then true is returned, otherwise false is returned.
func (db *DB) putConnDBLocked(dc *driverConn, err error) bool {
if db.maxOpen > 0 && db.numOpen > db.maxOpen {
return false
}
if c := len(db.connRequests); c > 0 {
req := db.connRequests[0]
// This copy is O(n) but in practice faster than a linked list.

View File

@ -1070,6 +1070,57 @@ func TestMaxOpenConns(t *testing.T) {
}
}
// Issue 9453: tests that SetMaxOpenConns can be lowered at runtime
// and affects the subsequent release of connections.
func TestMaxOpenConnsOnBusy(t *testing.T) {
defer setHookpostCloseConn(nil)
setHookpostCloseConn(func(_ *fakeConn, err error) {
if err != nil {
t.Errorf("Error closing fakeConn: %v", err)
}
})
db := newTestDB(t, "magicquery")
defer closeDB(t, db)
db.SetMaxOpenConns(3)
conn0, err := db.conn()
if err != nil {
t.Fatalf("db open conn fail: %v", err)
}
conn1, err := db.conn()
if err != nil {
t.Fatalf("db open conn fail: %v", err)
}
conn2, err := db.conn()
if err != nil {
t.Fatalf("db open conn fail: %v", err)
}
if g, w := db.numOpen, 3; g != w {
t.Errorf("free conns = %d; want %d", g, w)
}
db.SetMaxOpenConns(2)
if g, w := db.numOpen, 3; g != w {
t.Errorf("free conns = %d; want %d", g, w)
}
conn0.releaseConn(nil)
conn1.releaseConn(nil)
if g, w := db.numOpen, 2; g != w {
t.Errorf("free conns = %d; want %d", g, w)
}
conn2.releaseConn(nil)
if g, w := db.numOpen, 2; g != w {
t.Errorf("free conns = %d; want %d", g, w)
}
}
func TestSingleOpenConn(t *testing.T) {
db := newTestDB(t, "people")
defer closeDB(t, db)