]> Cypherpunks repositories - gostls13.git/commitdiff
database/sql: provide stats on number of open connections to the database.
authorAndrei Korzhevskii <a.korzhevskiy@gmail.com>
Mon, 23 Mar 2015 15:23:53 +0000 (18:23 +0300)
committerBrad Fitzpatrick <bradfitz@golang.org>
Wed, 1 Apr 2015 15:24:53 +0000 (15:24 +0000)
This change provides a convenient way to monitor database connection pool.

Change-Id: I4b3757855b43f3b254acf9312e2a16e2f87840d0
Reviewed-on: https://go-review.googlesource.com/7950
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
src/database/sql/sql.go
src/database/sql/sql_test.go

index 1ce679d8a6edea29acfb268653799c2b03b89229..b0e889467399486eb94794c91222cce5a4769041 100644 (file)
@@ -572,6 +572,22 @@ func (db *DB) SetMaxOpenConns(n int) {
        }
 }
 
+// DBStats contains database statistics.
+type DBStats struct {
+       // OpenConnections is the number of open connections to the database.
+       OpenConnections int
+}
+
+// Stats returns database statistics.
+func (db *DB) Stats() DBStats {
+       db.mu.Lock()
+       stats := DBStats{
+               OpenConnections: db.numOpen,
+       }
+       db.mu.Unlock()
+       return stats
+}
+
 // Assumes db.mu is locked.
 // If there are connRequests and the connection limit hasn't been reached,
 // then tell the connectionOpener to open new connections.
index 60bdefa07625f5c4431cbe096c0768e0c3f29a89..e225ffe6fa74dc967f51dea08b84c888374f12cf 100644 (file)
@@ -1093,6 +1093,26 @@ func TestSingleOpenConn(t *testing.T) {
        }
 }
 
+func TestStats(t *testing.T) {
+       db := newTestDB(t, "people")
+       stats := db.Stats()
+       if got := stats.OpenConnections; got != 1 {
+               t.Errorf("stats.OpenConnections = %d; want 1", got)
+       }
+
+       tx, err := db.Begin()
+       if err != nil {
+               t.Fatal(err)
+       }
+       tx.Commit()
+
+       closeDB(t, db)
+       stats = db.Stats()
+       if got := stats.OpenConnections; got != 0 {
+               t.Errorf("stats.OpenConnections = %d; want 0", got)
+       }
+}
+
 // golang.org/issue/5323
 func TestStmtCloseDeps(t *testing.T) {
        if testing.Short() {