-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.go
59 lines (49 loc) · 1.43 KB
/
postgres.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package postgres
import (
"context"
"fmt"
"time"
"github.com/dispenal/go-common/tracer"
common_utils "github.com/dispenal/go-common/utils"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
pgxUUID "github.com/vgarvardt/pgx-google-uuid/v5"
)
const (
maxConn = 50
healthCheckPeriod = 1 * time.Minute
maxConnIdleTime = 1 * time.Minute
maxConnLifetime = 3 * time.Minute
minConns = 10
lazyConnect = false
)
func NewPgxConn(cfg *common_utils.BaseConfig) (*pgxpool.Pool, error) {
ctx := context.Background()
dataSourceName := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s",
cfg.PostgresHost,
cfg.PostgresPort,
cfg.PostgresUser,
cfg.PostgresDb,
cfg.PostgresPassword,
)
common_utils.LogInfo(fmt.Sprintf("Connecting to postgres: %s", dataSourceName))
poolCfg, err := pgxpool.ParseConfig(dataSourceName)
if err != nil {
return nil, err
}
poolCfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
pgxUUID.Register(conn.TypeMap())
return nil
}
poolCfg.MaxConns = maxConn
poolCfg.HealthCheckPeriod = healthCheckPeriod
poolCfg.MaxConnIdleTime = maxConnIdleTime
poolCfg.MaxConnLifetime = maxConnLifetime
poolCfg.MinConns = minConns
poolCfg.ConnConfig.Tracer = new(tracer.PgxTracer)
connPool, err := pgxpool.NewWithConfig(ctx, poolCfg)
if err != nil {
return nil, common_utils.CustomErrorWithTrace(err, "pgxpool.NewWithConfig", 500)
}
return connPool, nil
}