From 0eda0109cad12658a03874462f88c1f55b5effd9 Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Sat, 30 Jul 2022 12:22:29 -0500 Subject: [PATCH] Add Pool.Reset() --- pgxpool/pool.go | 9 +++++++++ pgxpool/pool_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/pgxpool/pool.go b/pgxpool/pool.go index c9d79696..c7601a38 100644 --- a/pgxpool/pool.go +++ b/pgxpool/pool.go @@ -534,6 +534,15 @@ func (p *Pool) AcquireAllIdle(ctx context.Context) []*Conn { return conns } +// Reset closes all connections, but leaves the pool open. It is intended for use when an error is detected that would +// disrupt all connections (such as a network interruption or a server state change). +// +// It is safe to reset a pool while connections are checked out. Those connections will be closed when they are returned +// to the pool. +func (p *Pool) Reset() { + p.p.Reset() +} + // Config returns a copy of config that was used to initialize this pool. func (p *Pool) Config() *Config { return p.config.Copy() } diff --git a/pgxpool/pool_test.go b/pgxpool/pool_test.go index b5ce9ad7..cfebca7c 100644 --- a/pgxpool/pool_test.go +++ b/pgxpool/pool_test.go @@ -349,6 +349,31 @@ func TestPoolAcquireAllIdle(t *testing.T) { } } +func TestPoolReset(t *testing.T) { + t.Parallel() + + db, err := pgxpool.New(context.Background(), os.Getenv("PGX_TEST_DATABASE")) + require.NoError(t, err) + defer db.Close() + + conns := make([]*pgxpool.Conn, 3) + for i := range conns { + conns[i], err = db.Acquire(context.Background()) + assert.NoError(t, err) + } + + db.Reset() + + for _, c := range conns { + if c != nil { + c.Release() + } + } + waitForReleaseToComplete() + + require.EqualValues(t, 0, db.Stat().TotalConns()) +} + func TestConnReleaseChecksMaxConnLifetime(t *testing.T) { t.Parallel()