-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgresql.go
76 lines (58 loc) · 1.79 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package gorm_db_env_connector
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
"log"
)
type PgParams struct {
Url string
Database string
Username string
Password string
Port string
SSLMode string
}
type PgEnv struct {
UrlEnvVar string
PortEnvVar string
DatabaseEnvVar string
UsernameEnvVar string
PasswordEnvVar string
SSLModeEnvVar string
UrlDefault string
PortDefault string
DatabaseDefault string
UsernameDefault string
PasswordDefault string
SSLModeDefault string
}
func (env *PgEnv) resolve() PgParams {
return PgParams{
Url: resolveEnvOrDefault(env.UrlEnvVar, env.UrlDefault),
Database: resolveEnvOrDefault(env.DatabaseEnvVar, env.DatabaseDefault),
Username: resolveEnvOrDefault(env.UsernameEnvVar, env.UsernameDefault),
Password: resolveEnvOrDefault(env.PasswordEnvVar, env.PasswordDefault),
Port: resolveEnvOrDefault(env.PortEnvVar, env.PortDefault),
SSLMode: resolveEnvOrDefault(env.SSLModeEnvVar, env.SSLModeDefault),
}
}
func PgConnectEnv(env PgEnv) *gorm.DB {
return PgConnect(env.resolve())
}
func PgConnect(pgParams PgParams) *gorm.DB {
databaseName := pgParams.Url+ "/" + pgParams.Database
log.Println("Initializing connection to database " + databaseName)
dsn := "host=" + pgParams.Url + " user=" + pgParams.Username + " password=" + pgParams.Password + " dbname=" + pgParams.Database + " port=" + pgParams.Port + " sslmode=" + pgParams.SSLMode
_db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("Connection to database " + databaseName + " failed")
}
log.Println("Connection to database " + databaseName + " completed")
_ddb, err := _db.DB()
if err != nil {
panic("Setting connection pool failed")
}
_ddb.SetMaxIdleConns(10)
_ddb.SetMaxOpenConns(50)
return _db
}