/
gorm.go
55 lines (48 loc) · 1.11 KB
/
gorm.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
package injector
import (
"errors"
"os"
"path/filepath"
"github.com/jinzhu/gorm"
igorm "github.com/ops-cn/go-devops/admin/app/model/impl/gorm"
"github.com/ops-cn/go-devops/common/config"
)
// InitGormDB 初始化gorm存储
func InitGormDB() (*gorm.DB, func(), error) {
cfg := config.C.Gorm
db, cleanFunc, err := NewGormDB()
if err != nil {
return nil, cleanFunc, err
}
if cfg.EnableAutoMigrate {
err = igorm.AutoMigrate(db)
if err != nil {
return nil, cleanFunc, err
}
}
return db, cleanFunc, nil
}
// NewGormDB 创建DB实例
func NewGormDB() (*gorm.DB, func(), error) {
cfg := config.C
var dsn string
switch cfg.Gorm.DBType {
case "mysql":
dsn = cfg.MySQL.DSN()
case "sqlite3":
dsn = cfg.Sqlite3.DSN()
_ = os.MkdirAll(filepath.Dir(dsn), 0777)
case "postgres":
dsn = cfg.Postgres.DSN()
default:
return nil, nil, errors.New("unknown db")
}
return igorm.NewDB(&igorm.Config{
Debug: cfg.Gorm.Debug,
DBType: cfg.Gorm.DBType,
DSN: dsn,
MaxIdleConns: cfg.Gorm.MaxIdleConns,
MaxLifetime: cfg.Gorm.MaxLifetime,
MaxOpenConns: cfg.Gorm.MaxOpenConns,
})
}