Skip to content

Commit d15cc95

Browse files
dharjujackc
authored andcommitted
Add fix for using a context with a value in BeforeConnect
1 parent 3edc1b5 commit d15cc95

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

pgxpool/pool.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ func ConnectConfig(ctx context.Context, config *Config) (*Pool, error) {
265265
)
266266

267267
if !config.LazyConnect {
268-
if err := p.checkMinConns(); err != nil {
268+
if err := p.checkMinConnsWithContext(ctx); err != nil {
269269
// Couldn't create resources for minpool size. Close unhealthy pool.
270270
p.Close()
271271
return nil, err
@@ -485,17 +485,21 @@ func (p *Pool) checkConnsHealth() bool {
485485
return destroyed
486486
}
487487

488-
func (p *Pool) checkMinConns() error {
488+
func (p *Pool) checkMinConnsWithContext(ctx context.Context) error {
489489
// TotalConns can include ones that are being destroyed but we should have
490490
// sleep(500ms) around all of the destroys to help prevent that from throwing
491491
// off this check
492492
toCreate := p.minConns - p.Stat().TotalConns()
493493
if toCreate > 0 {
494-
return p.createIdleResources(context.Background(), int(toCreate))
494+
return p.createIdleResources(ctx, int(toCreate))
495495
}
496496
return nil
497497
}
498498

499+
func (p *Pool) checkMinConns() error {
500+
return p.checkMinConnsWithContext(context.Background())
501+
}
502+
499503
func (p *Pool) createIdleResources(parentCtx context.Context, targetResources int) error {
500504
ctx, cancel := context.WithCancel(parentCtx)
501505
defer cancel()

pgxpool/pool_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,26 @@ func TestLazyConnect(t *testing.T) {
7373
assert.Equal(t, context.Canceled, err)
7474
}
7575

76+
func TestBeforeConnectWithContextWithValueAndOneMinConn(t *testing.T) {
77+
t.Parallel()
78+
79+
config, err := pgxpool.ParseConfig(os.Getenv("PGX_TEST_DATABASE"))
80+
assert.NoError(t, err)
81+
config.MinConns = 1
82+
config.BeforeConnect = func(ctx context.Context, config *pgx.ConnConfig) error {
83+
val := ctx.Value("key")
84+
if val == nil {
85+
return errors.New("no value found with key 'key'")
86+
}
87+
return nil
88+
}
89+
90+
ctx := context.WithValue(context.Background(), "key", "value")
91+
92+
_, err = pgxpool.ConnectConfig(ctx, config)
93+
assert.NoError(t, err)
94+
}
95+
7696
func TestConstructorIgnoresContext(t *testing.T) {
7797
t.Parallel()
7898

0 commit comments

Comments
 (0)