Prevent panics caused by attempting to close an already closed pgxpool.Pool.

This commit is contained in:
Matt Schultz 2021-03-16 18:07:24 -05:00 committed by Jack Christensen
parent a0028cbd0d
commit fe366b2cf3
2 changed files with 19 additions and 2 deletions

View File

@ -326,8 +326,14 @@ func ParseConfig(connString string) (*Config, error) {
// Close closes all connections in the pool and rejects future Acquire calls. Blocks until all connections are returned
// to pool and closed.
func (p *Pool) Close() {
close(p.closeChan)
p.p.Close()
// Check to see if the closeChan is closed before attempting to close it again, which can result in a panic.
select {
case <-p.closeChan:
// NOOP because the channel is already closed.
default:
close(p.closeChan)
p.p.Close()
}
}
func (p *Pool) backgroundHealthCheck() {

View File

@ -789,3 +789,14 @@ func TestTxBeginFuncNestedTransactionRollback(t *testing.T) {
require.NoError(t, err)
require.EqualValues(t, 2, n)
}
func TestIdempotentPoolClose(t *testing.T) {
pool, err := pgxpool.Connect(context.Background(), os.Getenv("PGX_TEST_DATABASE"))
require.NoError(t, err)
// Close the open pool.
require.NotPanics(t, func() { pool.Close() })
// Close the already closed pool.
require.NotPanics(t, func() { pool.Close() })
}