settings section
This commit is contained in:
63
pkg/client/postgresql/postgresql.go
Executable file
63
pkg/client/postgresql/postgresql.go
Executable file
@@ -0,0 +1,63 @@
|
||||
package postgresql
|
||||
|
||||
import (
|
||||
"online-back/internal/config"
|
||||
repeatable "online-back/pkg/utils"
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgconn"
|
||||
"github.com/jackc/pgx/v4"
|
||||
"github.com/jackc/pgx/v4/pgxpool"
|
||||
)
|
||||
|
||||
type Client interface {
|
||||
Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
|
||||
Begin(ctx context.Context) (pgx.Tx, error)
|
||||
}
|
||||
|
||||
func NewClient(ctx context.Context, maxAttempts int, sc config.StorageConfig) (*pgxpool.Pool, error) {
|
||||
dsn := fmt.Sprintf(
|
||||
"postgresql://%s:%s@%s:%s/%s",
|
||||
url.QueryEscape(sc.Username),
|
||||
url.QueryEscape(sc.Password),
|
||||
sc.Host, sc.Port, sc.Database,
|
||||
)
|
||||
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse pg config: %w", err)
|
||||
}
|
||||
|
||||
cfg.MaxConns = int32(sc.PgPoolMaxConn)
|
||||
cfg.HealthCheckPeriod = 2 * time.Second
|
||||
cfg.MaxConnLifetime = 24 * time.Hour
|
||||
cfg.MaxConnIdleTime = 2 * time.Second
|
||||
|
||||
cfg.ConnConfig.ConnectTimeout = 1 * time.Second
|
||||
cfg.ConnConfig.DialFunc = (&net.Dialer{
|
||||
KeepAlive: cfg.HealthCheckPeriod,
|
||||
Timeout: cfg.ConnConfig.ConnectTimeout,
|
||||
}).DialContext
|
||||
|
||||
var pool *pgxpool.Pool
|
||||
err = repeatable.DoWithTries(func() error {
|
||||
p, err := pgxpool.ConnectConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool = p
|
||||
return nil
|
||||
}, maxAttempts, 5*time.Second)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error connecting to postgresql after retries: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
Reference in New Issue
Block a user