1
0
mirror of https://github.com/xorcare/testing-go-code-with-postgres.git synced 2025-07-03 23:30:31 +02:00

Make a lazy loading for opening a connection

In the current approach, the connection logic is only triggered at the
moment of immediate need for connection.

We also get a single connection opening point.
This commit is contained in:
Vasiliy Vasilyuk
2023-07-12 20:55:14 +03:00
parent c2e0810c2c
commit 4bb736475b

View File

@ -28,6 +28,8 @@ func New(t TestingT) *Postgres {
} }
type Postgres struct { type Postgres struct {
t TestingT
url string url string
ref string ref string
@ -51,6 +53,8 @@ func newPostgres(t TestingT) *Postgres {
require.NoError(t, err) require.NoError(t, err)
return &Postgres{ return &Postgres{
t: t,
url: urlStr, url: urlStr,
ref: refDatabase, ref: refDatabase,
@ -63,26 +67,28 @@ func (p *Postgres) URL() string {
} }
func (p *Postgres) PgxPool() *pgxpool.Pool { func (p *Postgres) PgxPool() *pgxpool.Pool {
return p.conn pool, err := pgxpool.New(context.Background(), p.URL())
require.NoError(p.t, err)
// Automatically close connection after the test is completed.
p.t.Cleanup(func() {
pool.Close()
})
return pool
} }
func (p *Postgres) cloneFromReference(t TestingT) *Postgres { func (p *Postgres) cloneFromReference(t TestingT) *Postgres {
cfg, err := pgxpool.ParseConfig(p.url)
require.NoError(t, err)
pool, err := pgxpool.New(context.Background(), p.url)
require.NoError(t, err)
newDatabaseName := uuid.New().String() newDatabaseName := uuid.New().String()
const sqlTemplate = `CREATE DATABASE %q WITH TEMPLATE %s OWNER %s;` const sqlTemplate = `CREATE DATABASE %q WITH TEMPLATE %s;`
sql := fmt.Sprintf( sql := fmt.Sprintf(
sqlTemplate, sqlTemplate,
newDatabaseName, newDatabaseName,
p.ref, p.ref,
cfg.ConnConfig.User,
) )
_, err = pool.Exec(context.Background(), sql)
_, err := p.PgxPool().Exec(context.Background(), sql)
require.NoError(t, err) require.NoError(t, err)
// Automatically drop database copy after the test is completed. // Automatically drop database copy after the test is completed.
@ -96,20 +102,17 @@ func (p *Postgres) cloneFromReference(t TestingT) *Postgres {
require.NoError(t, err) require.NoError(t, err)
}) })
urlString := replaceDBName(t, cfg, newDatabaseName) urlString := replaceDBName(t, p.URL(), newDatabaseName)
newPool, err := pgxpool.New(context.Background(), urlString)
require.NoError(t, err)
return &Postgres{ return &Postgres{
t: p.t,
url: urlString, url: urlString,
ref: newDatabaseName, ref: newDatabaseName,
conn: newPool,
} }
} }
func replaceDBName(t TestingT, cfg *pgxpool.Config, dbname string) string { func replaceDBName(t TestingT, dataSourceURL, dbname string) string {
r, err := url.Parse(cfg.ConnString()) r, err := url.Parse(dataSourceURL)
require.NoError(t, err) require.NoError(t, err)
r.Path = dbname r.Path = dbname
return r.String() return r.String()