From db5300358a14c176a55627536da74d077aff92ae Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Mon, 25 May 2015 09:54:28 -0500 Subject: [PATCH] Allow ConnPool to have MaxConnections of 1 --- conn_pool.go | 4 ++-- conn_pool_test.go | 14 -------------- stdlib/sql.go | 6 ++++++ 3 files changed, 8 insertions(+), 16 deletions(-) diff --git a/conn_pool.go b/conn_pool.go index 6a02382e..041ac830 100644 --- a/conn_pool.go +++ b/conn_pool.go @@ -37,8 +37,8 @@ func NewConnPool(config ConnPoolConfig) (p *ConnPool, err error) { if p.maxConnections == 0 { p.maxConnections = 5 } - if p.maxConnections < 2 { - return nil, errors.New("MaxConnections must be at least 2") + if p.maxConnections < 1 { + return nil, errors.New("MaxConnections must be at least 1") } p.afterConnect = config.AfterConnect diff --git a/conn_pool_test.go b/conn_pool_test.go index 724fcf42..f6ce75da 100644 --- a/conn_pool_test.go +++ b/conn_pool_test.go @@ -67,20 +67,6 @@ func TestNewConnPoolDefaultsTo5MaxConnections(t *testing.T) { } } -func TestNewConnPoolMaxConnectionsCannotBeLessThan2(t *testing.T) { - t.Parallel() - - config := pgx.ConnPoolConfig{ConnConfig: *defaultConnConfig, MaxConnections: 1} - pool, err := pgx.NewConnPool(config) - if err == nil { - pool.Close() - t.Fatal(`Expected NewConnPool to fail with "MaxConnections must be at least 2" error, but it succeeded`) - } - if err.Error() != "MaxConnections must be at least 2" { - t.Fatalf(`Expected NewConnPool to fail with "MaxConnections must be at least 2" error, but it failed with %v`, err) - } -} - func TestPoolAcquireAndReleaseCycle(t *testing.T) { t.Parallel() diff --git a/stdlib/sql.go b/stdlib/sql.go index 5871f36c..2292f1c3 100644 --- a/stdlib/sql.go +++ b/stdlib/sql.go @@ -109,6 +109,8 @@ func (d *Driver) Open(name string) (driver.Conn, error) { // *sql.DB and typecasting to *stdlib.Driver a reference to the pgx.ConnPool can // be reaquired later. This allows fast paths targeting pgx to be used while // still maintaining compatibility with other databases and drivers. +// +// pool connection size must be at least 2. func OpenFromConnPool(pool *pgx.ConnPool) (*sql.DB, error) { d := &Driver{Pool: pool} name := fmt.Sprintf("pgx-%d", openFromConnPoolCount) @@ -126,6 +128,10 @@ func OpenFromConnPool(pool *pgx.ConnPool) (*sql.DB, error) { // that would mean that prepared statements would be lost (which kills // performance if the prepared statements constantly have to be reprepared) stat := pool.Stat() + + if stat.MaxConnections <= 2 { + return nil, errors.New("pool connection size must be at least 2") + } db.SetMaxIdleConns(stat.MaxConnections - 2) db.SetMaxOpenConns(stat.MaxConnections)