-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathconnection_psql.go
64 lines (54 loc) · 1.4 KB
/
connection_psql.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
package goutils
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
postgres "gorm.io/driver/postgres"
"gorm.io/gorm"
"strconv"
"time"
)
/*
ConnectionBDPostgreSQL o antigo nome era: ConexaoDB
*/
func ConnectionBDPostgreSQL() *sql.DB {
var host, dbname, user, password string
var port int
host = Godotenv("host")
dbname = Godotenv("dbname")
port, _ = strconv.Atoi(Godotenv("port_banco"))
user = Godotenv("user")
password = Godotenv("password")
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
db.SetMaxOpenConns(5)
db.SetMaxIdleConns(1)
db.SetConnMaxLifetime(1 * time.Minute)
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
time.Sleep(2 * time.Second)
return ConnectionBDPostgreSQL()
}
return db
}
/*
ConnectionBDPostgreSQLORM o antigo nome era: ConexaoBDORM
*/
func ConnectionBDPostgreSQLORM() (DB *gorm.DB) {
var host, dbname, user, password string
var port int
host = Godotenv("host")
dbname = Godotenv("dbname")
port, _ = strconv.Atoi(Godotenv("port_banco"))
user = Godotenv("user")
password = Godotenv("password")
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
db, err := gorm.Open(postgres.Open(psqlInfo), &gorm.Config{})
if err != nil {
panic(err)
}
return db
}