zhangqian
2023-08-26 5193dcb9336e853502baf8a539d3f45efebe2f86
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
71
package system
 
import (
    "context"
    "github.com/pkg/errors"
    "gorm.io/gorm"
    sysModel "srm/model/system"
    "srm/service/system"
)
 
const initOrderDict = initOrderCasbin + 1
 
type initDict struct{}
 
// auto run
func init() {
    system.RegisterInit(initOrderDict, &initDict{})
}
 
func (i *initDict) MigrateTable(ctx context.Context) (context.Context, error) {
    db, ok := ctx.Value("db").(*gorm.DB)
    if !ok {
        return ctx, system.ErrMissingDBContext
    }
    return ctx, db.AutoMigrate(&sysModel.SysDictionary{})
}
 
func (i *initDict) TableCreated(ctx context.Context) bool {
    db, ok := ctx.Value("db").(*gorm.DB)
    if !ok {
        return false
    }
    return db.Migrator().HasTable(&sysModel.SysDictionary{})
}
 
func (i initDict) InitializerName() string {
    return sysModel.SysDictionary{}.TableName()
}
 
func (i *initDict) InitializeData(ctx context.Context) (next context.Context, err error) {
    db, ok := ctx.Value("db").(*gorm.DB)
    if !ok {
        return ctx, system.ErrMissingDBContext
    }
    True := true
    entities := []sysModel.SysDictionary{
        {Name: "性别", Type: "gender", Status: &True, Desc: "性别字典"},
        {Name: "数据库int类型", Type: "int", Status: &True, Desc: "int类型对应的数据库类型"},
        {Name: "数据库时间日期类型", Type: "time.Time", Status: &True, Desc: "数据库时间日期类型"},
        {Name: "数据库浮点型", Type: "float64", Status: &True, Desc: "数据库浮点型"},
        {Name: "数据库字符串", Type: "string", Status: &True, Desc: "数据库字符串"},
        {Name: "数据库bool类型", Type: "bool", Status: &True, Desc: "数据库bool类型"},
    }
 
    if err = db.Create(&entities).Error; err != nil {
        return ctx, errors.Wrap(err, sysModel.SysDictionary{}.TableName()+"表数据初始化失败!")
    }
    next = context.WithValue(ctx, i.InitializerName(), entities)
    return next, nil
}
 
func (i *initDict) DataInserted(ctx context.Context) bool {
    db, ok := ctx.Value("db").(*gorm.DB)
    if !ok {
        return false
    }
    if errors.Is(db.Where("type = ?", "bool").First(&sysModel.SysDictionary{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
        return false
    }
    return true
}