/
database.go
70 lines (60 loc) · 1.85 KB
/
database.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
package db
import (
"fmt"
"github.com/antonioalfa22/GoGin-API-REST-Template/internal/pkg/config"
"github.com/antonioalfa22/GoGin-API-REST-Template/internal/pkg/models/users"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/postgres"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"time"
)
var (
DB *gorm.DB
err error
)
type Database struct {
*gorm.DB
}
// SetupDB opens a database and saves the reference to `Database` struct.
func SetupDB() {
var db = DB
configuration := config.GetConfig()
driver := configuration.Database.Driver
database := configuration.Database.Dbname
username := configuration.Database.Username
password := configuration.Database.Password
host := configuration.Database.Host
port := configuration.Database.Port
if driver == "sqlite" { // SQLITE
db, err = gorm.Open("sqlite3", "./"+database+".db")
if err != nil {
fmt.Println("db err: ", err)
}
} else if driver == "postgres" { // POSTGRES
db, err = gorm.Open("postgres", "host="+host+" port="+port+" user="+username+" dbname="+database+" sslmode=disable password="+password)
if err != nil {
fmt.Println("db err: ", err)
}
} else if driver == "mysql" { // MYSQL
db, err = gorm.Open("mysql", username+":"+password+"@tcp("+host+":"+port+")/"+database+"?charset=utf8&parseTime=True&loc=Local")
if err != nil {
fmt.Println("db err: ", err)
}
}
// Change this to true if you want to see SQL queries
db.LogMode(false)
db.DB().SetMaxIdleConns(configuration.Database.MaxIdleConns)
db.DB().SetMaxOpenConns(configuration.Database.MaxOpenConns)
db.DB().SetConnMaxLifetime(time.Duration(configuration.Database.MaxLifetime) * time.Second)
DB = db
migration()
}
// Auto migrate project models
func migration() {
DB.AutoMigrate(&users.User{})
DB.AutoMigrate(&users.UserRole{})
}
func GetDB() *gorm.DB {
return DB
}