-
Notifications
You must be signed in to change notification settings - Fork 52
/
index.go
69 lines (57 loc) · 1.4 KB
/
index.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
package dao
import (
commConsts "github.com/easysoft/zentaoatf/internal/pkg/consts"
"github.com/easysoft/zentaoatf/internal/server/modules/v1/model"
logUtils "github.com/easysoft/zentaoatf/pkg/lib/log"
"github.com/fatih/color"
"github.com/glebarez/sqlite"
"gorm.io/gorm/schema"
"gorm.io/plugin/dbresolver"
"path/filepath"
"time"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var (
db *gorm.DB
)
// GetDB 数据库单例
func GetDB() *gorm.DB {
if db != nil {
return db
}
conn := DBFile()
dialector := sqlite.Open(conn)
var err error
db, err = gorm.Open(dialector, &gorm.Config{
SkipDefaultTransaction: false,
Logger: logger.Default.LogMode(logger.Info),
NamingStrategy: schema.NamingStrategy{
TablePrefix: "",
SingularTable: false,
},
})
if err != nil {
logUtils.Infof(color.RedString("open db failed, error: %s.", err.Error()))
}
_ = db.Use(
dbresolver.Register(
dbresolver.Config{ /* xxx */ }).
SetConnMaxIdleTime(time.Hour).
SetConnMaxLifetime(24 * time.Hour).
SetMaxIdleConns(100).
SetMaxOpenConns(200),
)
db.Session(&gorm.Session{FullSaveAssociations: true, AllowGlobalUpdate: false})
err = db.AutoMigrate(
model.Models...,
)
if err != nil {
logUtils.Infof(color.RedString("migrate models failed, error: %s.", err.Error()))
}
return db
}
func DBFile() string {
path := filepath.Join(commConsts.WorkDir, commConsts.App+".db")
return path
}