-
Notifications
You must be signed in to change notification settings - Fork 1
/
pgdb.go
49 lines (39 loc) · 1012 Bytes
/
pgdb.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
package pgdb
import (
"fmt"
"log"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type PostgresDbParams struct {
Host string
User string
Password string
Db string
Port string
Ssl string
Timezone string
}
type ReactRolesDatabase struct {
DB *gorm.DB
}
func getConnectionString(params PostgresDbParams) string {
return fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s timezone=%s",
params.Host, params.Port, params.User, params.Password, params.Db, params.Ssl, params.Timezone)
}
func runAutoMigrations(db *gorm.DB) {
// Migrate tables
db.AutoMigrate(&Role{})
}
func GetDatabase(params PostgresDbParams) *ReactRolesDatabase {
database, err := gorm.Open(postgres.Open(getConnectionString(params)), &gorm.Config{})
if err != nil {
log.Fatal(err)
} else {
log.Println("[PGDB] Connected to Postgres successfully")
}
runAutoMigrations(database)
return &ReactRolesDatabase{
DB: database,
}
}