-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgx.go
77 lines (64 loc) · 1.81 KB
/
pgx.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package postgres
import (
"context"
"database/sql"
"fmt"
"log"
"net/url"
"sync"
"time"
"github.com/exaring/otelpgx"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
"github.com/sangianpatrick/go-codebase-fiber/config"
pgxUUID "github.com/vgarvardt/pgx-google-uuid/v5"
semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
)
var (
db *sql.DB
syncOnce sync.Once
)
func constructPgx() *sql.DB {
c := config.Get()
purl := &url.URL{}
purl.Scheme = "postgres"
purl.User = url.UserPassword(c.Postgres.Username, c.Postgres.Password)
purl.Host = fmt.Sprintf("%s:%s", c.Postgres.Host, c.Postgres.Port)
purl.Path = c.Postgres.Database
qs := purl.Query()
qs.Set("search_path", c.Postgres.Schema)
qs.Set("sslmode", c.Postgres.SSLMode)
qs.Set("pool_min_conns", fmt.Sprint(c.Postgres.PoolMinConns))
qs.Set("pool_max_conns", fmt.Sprint(c.Postgres.PoolMaxConns))
qs.Set("pool_max_conn_lifetime", (time.Duration(c.Postgres.MaxConnLifetime) * time.Second).String())
qs.Set("pool_max_conn_idle_time", (time.Duration(c.Postgres.MaxConnIdleTime) * time.Second).String())
purl.RawQuery = qs.Encode()
pgxConfig, err := pgxpool.ParseConfig(purl.String())
if err != nil {
log.Println(err)
pgxConfig = &pgxpool.Config{}
}
pgxConfig.ConnConfig.Tracer = otelpgx.NewTracer(
otelpgx.WithAttributes(
semconv.DBSystemPostgreSQL,
),
otelpgx.WithIncludeQueryParameters(),
)
pgxConfig.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
pgxUUID.Register(conn.TypeMap())
return nil
}
pgxConnPool, err := pgxpool.NewWithConfig(context.Background(), pgxConfig)
if err != nil {
log.Println(err)
pgxConnPool = &pgxpool.Pool{}
}
return stdlib.OpenDBFromPool(pgxConnPool)
}
func GetDatabase() *sql.DB {
syncOnce.Do(func() {
db = constructPgx()
})
return db
}