-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.go
48 lines (38 loc) · 850 Bytes
/
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
package db
import (
"fmt"
"log"
"time"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var dbClient *gorm.DB
func InitDb(cfg *Config) error {
var err error
cnn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s TimeZone=Asia/Tehran",
cfg.Host, cfg.Port, cfg.User, cfg.Password,
cfg.DbName, cfg.SSLMode)
dbClient, err = gorm.Open(postgres.Open(cnn), &gorm.Config{})
if err != nil {
dbClient = nil
return err
}
sqlDb, _ := dbClient.DB()
err = sqlDb.Ping()
if err != nil {
dbClient = nil
return err
}
sqlDb.SetMaxIdleConns(cfg.MaxIdleConns)
sqlDb.SetMaxOpenConns(cfg.MaxOpenConns)
sqlDb.SetConnMaxLifetime(cfg.ConnMaxLifetime * time.Minute)
log.Println("Db connection established")
return nil
}
func GetDb() *gorm.DB {
return dbClient
}
func CloseDb() {
cnn, _ := dbClient.DB()
cnn.Close()
}