Total Lines | 61 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | package infrastructures |
||
2 | |||
3 | import ( |
||
4 | "context" |
||
5 | "sync" |
||
6 | |||
7 | "github.com/jackc/pgx/v5/pgxpool" |
||
8 | ) |
||
9 | |||
10 | type PgxConnSingleton struct { |
||
11 | conn *pgxpool.Pool |
||
12 | config PgxConfig |
||
13 | } |
||
14 | |||
15 | var ( |
||
16 | pgxInstance *PgxConnSingleton //nolint:gochecknoglobals //Singleton |
||
17 | pgxOnce sync.Once //nolint:gochecknoglobals //Singleton |
||
18 | ) |
||
19 | |||
20 | type PgxConfig struct { |
||
21 | DSN string |
||
22 | SQLMaxIdleConns int |
||
23 | SQLMaxOpenConns int |
||
24 | } |
||
25 | |||
26 | func GetPgxConnInstance() *PgxConnSingleton { |
||
27 | pgxOnce.Do(func() { |
||
28 | pgxInstance = &PgxConnSingleton{} |
||
29 | }) |
||
30 | return pgxInstance |
||
31 | } |
||
32 | |||
33 | func NewPgxConnInstance(config PgxConfig) *PgxConnSingleton { |
||
34 | return GetPgxConnInstance().WithConfig(config) |
||
35 | } |
||
36 | |||
37 | func (p *PgxConnSingleton) WithConfig(config PgxConfig) *PgxConnSingleton { |
||
38 | p.config = config |
||
39 | return p |
||
40 | } |
||
41 | |||
42 | func (p *PgxConnSingleton) GetPgxConn() *pgxpool.Pool { |
||
43 | return p.conn |
||
44 | } |
||
45 | |||
46 | func (p *PgxConnSingleton) ConnectPgx() error { |
||
47 | conn, err := pgxpool.New(context.Background(), p.config.DSN) |
||
48 | if err != nil { |
||
49 | return err |
||
50 | } |
||
51 | |||
52 | p.conn = conn |
||
53 | return nil |
||
54 | } |
||
55 | |||
56 | func (p *PgxConnSingleton) ClosePgx() { |
||
57 | p.conn.Close() |
||
58 | } |
||
59 | |||
60 | func GetPgxConn() *pgxpool.Pool { |
||
61 | return pgxInstance.GetPgxConn() |
||
62 | } |
||
63 |