-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgresql.go
55 lines (46 loc) · 1.18 KB
/
postgresql.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
package postgresql
import (
"context"
"fmt"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/matster07/user-balance-service/internal/app/configs"
"github.com/matster07/user-balance-service/internal/pkg/logging"
"github.com/matster07/user-balance-service/internal/pkg/utils"
"time"
)
func NewClient(ctx context.Context, maxAttempts int, sc *configs.Config) (pool *pgxpool.Pool, err error) {
dsn := fmt.Sprintf(
"postgresql://%s:%s@%s:%d/%s?search_path=%s",
sc.DatabaseUsername,
sc.DatabasePassword,
sc.DatabaseHost,
sc.DatabasePort,
sc.DatabaseTable,
sc.DatabaseSchema)
err = repeatable.DoWithTries(func() error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
pool, err = pgxpool.Connect(ctx, dsn)
if err != nil {
return err
}
return nil
}, maxAttempts, 5*time.Second)
if err != nil {
logging.GetLogger().Fatal(err)
}
return pool, nil
}
func RollbackTx(tx pgx.Tx) {
err := tx.Rollback(context.TODO())
if err != nil {
logging.GetLogger().Trace("Rollback transaction")
}
}
func CommitTx(tx pgx.Tx) {
err := tx.Commit(context.TODO())
if err != nil {
logging.GetLogger().Trace("Commit transaction")
}
}