-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
59 lines (48 loc) · 1.52 KB
/
config.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 main
import (
"context"
"fmt"
"log/slog"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// PoolConfig function with error handling
func PoolConfig(dsn *string, logger *slog.Logger) (*pgxpool.Config, error) {
const defaultMaxConns = int32(4)
const defaultMinConns = int32(0)
const defaultMaxConnLifetime = time.Hour
const defaultMaxConnIdleTime = time.Minute * 15
const defaultHealthCheckPeriod = time.Minute
const defaultConnectTimeout = time.Second * 5
dbConfig, err := pgxpool.ParseConfig(*dsn)
if err != nil {
return nil, fmt.Errorf("failed to parse database configuration: %w", err)
}
dbConfig.MaxConns = defaultMaxConns
dbConfig.MinConns = defaultMinConns
dbConfig.MaxConnLifetime = defaultMaxConnLifetime
dbConfig.MaxConnIdleTime = defaultMaxConnIdleTime
dbConfig.HealthCheckPeriod = defaultHealthCheckPeriod
dbConfig.ConnConfig.ConnectTimeout = defaultConnectTimeout
dbConfig.BeforeConnect = func(ctx context.Context, c *pgx.ConnConfig) error {
logger.Debug("creating connection")
return nil
}
dbConfig.AfterConnect = func(ctx context.Context, c *pgx.Conn) error {
logger.Debug("connection created")
return nil
}
dbConfig.BeforeAcquire = func(ctx context.Context, c *pgx.Conn) bool {
logger.Debug("acquiring connection pool")
return true
}
dbConfig.AfterRelease = func(c *pgx.Conn) bool {
logger.Debug("releasing connection pool")
return true
}
dbConfig.BeforeClose = func(c *pgx.Conn) {
logger.Debug("closing connection pool")
}
return dbConfig, nil
}