forked from mtusi2026/mtusi2026lab3
57 lines
944 B
Go
57 lines
944 B
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func NewPostgresPool(
|
|
ctx context.Context,
|
|
databaseURL string,
|
|
) (*pgxpool.Pool, error) {
|
|
config, err := pgxpool.ParseConfig(databaseURL)
|
|
if err != nil {
|
|
return nil, fmt.Errorf(
|
|
"invalid database config: %w",
|
|
err,
|
|
)
|
|
}
|
|
|
|
config.MaxConns = 10
|
|
config.MinConns = 1
|
|
config.MaxConnLifetime = 30 * time.Minute
|
|
config.MaxConnIdleTime = 5 * time.Minute
|
|
config.HealthCheckPeriod = time.Minute
|
|
config.ConnConfig.ConnectTimeout = 5 * time.Second
|
|
|
|
connectCtx, cancel := context.WithTimeout(
|
|
ctx,
|
|
10*time.Second,
|
|
)
|
|
defer cancel()
|
|
|
|
pool, err := pgxpool.NewWithConfig(
|
|
connectCtx,
|
|
config,
|
|
)
|
|
if err != nil {
|
|
return nil, fmt.Errorf(
|
|
"create postgres pool: %w",
|
|
err,
|
|
)
|
|
}
|
|
|
|
if err := pool.Ping(connectCtx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf(
|
|
"postgres unavailable: %w",
|
|
err,
|
|
)
|
|
}
|
|
|
|
return pool, nil
|
|
}
|