-
Notifications
You must be signed in to change notification settings - Fork 2
/
tableInit.go
60 lines (49 loc) · 1.25 KB
/
tableInit.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
package orm
import (
"fmt"
"sync"
"github.com/asaskevich/EventBus"
"github.com/spf13/viper"
"github.com/techquest-tech/gin-shared/pkg/core"
"go.uber.org/zap"
"gorm.io/gorm"
)
var entities = make([]interface{}, 0)
func AppendEntity(entity ...interface{}) {
entities = append(entities, entity...)
}
var ormOnce sync.Once
func ApplyMigrate() error {
return core.Container.Invoke(core.Container.Invoke(func(db *gorm.DB, logger *zap.Logger, bus core.OptionalParam[EventBus.Bus]) {
ormOnce.Do(func() {
if viper.GetBool(KeyInitDB) {
MigrateTableAndView(db, logger, bus.P)
}
})
}))
}
func MigrateTableAndView(db *gorm.DB, logger *zap.Logger, bus EventBus.Bus) {
logger.Info("init all tables")
for _, item := range entities {
name := fmt.Sprintf("%T", item)
zap.L().Info("applied entity", zap.String("entity", name))
}
err := db.AutoMigrate(entities...)
if err != nil {
logger.Error("init tables failed", zap.Error(err))
} else {
if bus != nil {
bus.Publish("sys.db.inited")
}
logger.Info("init tables done")
}
err = InitMysqlViews(db, logger)
if err != nil {
logger.Error("init views failed", zap.Error(err))
} else {
logger.Info("init views done.")
}
}
// func init() {
// AppendEntity(&schedule.JobSchedule{})
// }