forked from mtusi2026/mtusi2026lab2
уровень 5 трек 1
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
DSN string
|
||||
MaxConns int32
|
||||
MinConns int32
|
||||
ConnMaxLifetime time.Duration
|
||||
ConnTimeout time.Duration
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.DSN)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
poolCfg.MaxConnLifetime = cfg.ConnMaxLifetime
|
||||
|
||||
connCtx, cancel := context.WithTimeout(ctx, cfg.ConnTimeout)
|
||||
defer cancel()
|
||||
pool, err := pgxpool.NewWithConfig(connCtx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel2 := context.WithTimeout(ctx, cfg.ConnTimeout)
|
||||
defer cancel2()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping db: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
Reference in New Issue
Block a user