-
Notifications
You must be signed in to change notification settings - Fork 326
/
db.go
51 lines (44 loc) · 1.38 KB
/
db.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
package db
import (
"errors"
"fmt"
"os"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
_ "github.com/jinzhu/gorm/dialects/postgres"
// _ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/qor/l10n"
"github.com/qor/media"
"github.com/qor/publish2"
"github.com/qor/qor-example/config"
"github.com/qor/sorting"
"github.com/qor/validations"
)
// DB Global DB connection
var DB *gorm.DB
func init() {
var err error
dbConfig := config.Config.DB
if config.Config.DB.Adapter == "mysql" {
DB, err = gorm.Open("mysql", fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?parseTime=True&loc=Local", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Name))
// DB = DB.Set("gorm:table_options", "CHARSET=utf8")
} else if config.Config.DB.Adapter == "postgres" {
DB, err = gorm.Open("postgres", fmt.Sprintf("postgres://%v:%v@%v/%v?sslmode=disable", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Name))
} else if config.Config.DB.Adapter == "sqlite" {
DB, err = gorm.Open("sqlite3", fmt.Sprintf("%v/%v", os.TempDir(), dbConfig.Name))
} else {
panic(errors.New("not supported database adapter"))
}
if err == nil {
if os.Getenv("DEBUG") != "" {
DB.LogMode(true)
}
l10n.RegisterCallbacks(DB)
sorting.RegisterCallbacks(DB)
validations.RegisterCallbacks(DB)
media.RegisterCallbacks(DB)
publish2.RegisterCallbacks(DB)
} else {
panic(err)
}
}