diff --git a/pgxpool/pool.go b/pgxpool/pool.go index 0fa7c98f..83fa02d3 100644 --- a/pgxpool/pool.go +++ b/pgxpool/pool.go @@ -112,6 +112,11 @@ type Config struct { // HealthCheckPeriod is the duration between checks of the health of idle connections. HealthCheckPeriod time.Duration + // If set to true, pool doesn't do any I/O operation on initialization. + // And connects to the server only when the pool starts to be used. + // The default is false. + LazyConnect bool + createdByParseConfig bool // Used to enforce created by ParseConfig rule. } @@ -180,13 +185,15 @@ func ConnectConfig(ctx context.Context, config *Config) (*Pool, error) { go p.backgroundHealthCheck() - // Initially establish one connection - res, err := p.p.Acquire(ctx) - if err != nil { - p.p.Close() - return nil, err + if !config.LazyConnect { + // Initially establish one connection + res, err := p.p.Acquire(ctx) + if err != nil { + p.p.Close() + return nil, err + } + res.Release() } - res.Release() return p, nil } diff --git a/pgxpool/pool_test.go b/pgxpool/pool_test.go index 57fbb401..89f324a6 100644 --- a/pgxpool/pool_test.go +++ b/pgxpool/pool_test.go @@ -41,6 +41,23 @@ func TestConnectCancel(t *testing.T) { assert.Equal(t, context.Canceled, err) } +func TestLazyConnect(t *testing.T) { + t.Parallel() + + config, err := pgxpool.ParseConfig(os.Getenv("PGX_TEST_DATABASE")) + assert.NoError(t, err) + config.LazyConnect = true + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + pool, err := pgxpool.ConnectConfig(ctx, config) + assert.NoError(t, err) + + _, err = pool.Exec(ctx, "SELECT 1") + assert.Equal(t, context.Canceled, err) +} + func TestConnectConfigRequiresConnConfigFromParseConfig(t *testing.T) { t.Parallel()