52 lines
1.4 KiB
Go
52 lines
1.4 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func OpenPostgres(ctx context.Context, passwordFile string) (*pgxpool.Pool, error) {
|
|
password, err := os.ReadFile(passwordFile)
|
|
if err != nil {
|
|
return nil, errors.New("cannot read PostgreSQL password file")
|
|
}
|
|
secret := strings.TrimRight(string(password), "\r\n")
|
|
if secret == "" {
|
|
return nil, errors.New("PostgreSQL password file is empty")
|
|
}
|
|
|
|
config, err := pgxpool.ParseConfig(
|
|
"host=postgres port=5432 dbname=messenger user=messenger sslmode=disable",
|
|
)
|
|
if err != nil {
|
|
return nil, errors.New("invalid PostgreSQL configuration")
|
|
}
|
|
config.ConnConfig.Password = secret
|
|
config.ConnConfig.ConnectTimeout = 3 * time.Second
|
|
config.ConnConfig.RuntimeParams["statement_timeout"] = "3000"
|
|
config.ConnConfig.RuntimeParams["lock_timeout"] = "2000"
|
|
config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab2"
|
|
config.MaxConns = 10
|
|
config.MinConns = 0
|
|
config.MaxConnLifetime = 30 * time.Minute
|
|
config.MaxConnIdleTime = 5 * time.Minute
|
|
|
|
connectCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
|
|
pool, err := pgxpool.NewWithConfig(connectCtx, config)
|
|
if err != nil {
|
|
return nil, errors.New("cannot create PostgreSQL pool")
|
|
}
|
|
if err := pool.Ping(connectCtx); err != nil {
|
|
pool.Close()
|
|
return nil, errors.New("PostgreSQL connection check failed")
|
|
}
|
|
return pool, nil
|
|
}
|