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

@ -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)