1
0
mirror of https://github.com/xorcare/testing-go-code-with-postgres.git synced 2024-12-27 16:33:05 +02:00

Make a singleton for *pgxpool.Pool

This should reduce the number of parasitic connection reopenings.
This commit is contained in:
Vasiliy Vasilyuk 2023-07-12 21:08:04 +03:00
parent 4bb736475b
commit 59c4d2e3e1
No known key found for this signature in database
GPG Key ID: CD966F83D6FAFF48

View File

@ -9,6 +9,7 @@ import (
"fmt" "fmt"
"net/url" "net/url"
"os" "os"
"sync"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
@ -34,6 +35,7 @@ type Postgres struct {
ref string ref string
conn *pgxpool.Pool conn *pgxpool.Pool
once sync.Once
} }
func newPostgres(t TestingT) *Postgres { func newPostgres(t TestingT) *Postgres {
@ -67,15 +69,11 @@ func (p *Postgres) URL() string {
} }
func (p *Postgres) PgxPool() *pgxpool.Pool { func (p *Postgres) PgxPool() *pgxpool.Pool {
pool, err := pgxpool.New(context.Background(), p.URL()) p.once.Do(func() {
require.NoError(p.t, err) p.conn = newPGxPool(p.t, p.URL())
// Automatically close connection after the test is completed.
p.t.Cleanup(func() {
pool.Close()
}) })
return pool return p.conn
} }
func (p *Postgres) cloneFromReference(t TestingT) *Postgres { func (p *Postgres) cloneFromReference(t TestingT) *Postgres {
@ -117,3 +115,18 @@ func replaceDBName(t TestingT, dataSourceURL, dbname string) string {
r.Path = dbname r.Path = dbname
return r.String() return r.String()
} }
func newPGxPool(t TestingT, dataSourceURL string) *pgxpool.Pool {
ctx, done := context.WithTimeout(context.Background(), 1*time.Second)
defer done()
pool, err := pgxpool.New(ctx, dataSourceURL)
require.NoError(t, err)
// Automatically close connection after the test is completed.
t.Cleanup(func() {
pool.Close()
})
return pool
}