-
Notifications
You must be signed in to change notification settings - Fork 13
/
seed_db.go
95 lines (74 loc) · 2.2 KB
/
seed_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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package scripts
import (
"context"
"encoding/json"
"github.com/coretrix/hitrix/service/component/app"
"github.com/latolukasz/beeorm"
"github.com/coretrix/hitrix/pkg/entity"
"github.com/coretrix/hitrix/service"
)
type DBSeedScript struct {
Seeds map[string]Seed
}
func (script *DBSeedScript) Run(_ context.Context, _ app.IExit) {
ormService := service.DI().OrmEngine()
Seeder(script.Seeds, ormService)
}
func (script *DBSeedScript) Unique() bool {
return true
}
func (script *DBSeedScript) Description() string {
return "Seed Database"
}
type Seed interface {
Execute(*beeorm.Engine)
Version() int
}
func Seeder(seeds map[string]Seed, ormService *beeorm.Engine) {
var setting entity.SettingsEntity
whereStmt := beeorm.NewWhere("`Key` = ?", entity.HitrixSettingAll.Seeds)
var hasExecutedSeedsSetting = ormService.SearchOne(whereStmt, &setting)
var executedSeeds entity.SettingSeedsValue
if hasExecutedSeedsSetting {
if err := json.Unmarshal([]byte(setting.Value), &executedSeeds); err != nil {
panic(err.Error())
}
}
var newSeeds entity.SettingSeedsValue = make(entity.SettingSeedsValue)
for k, seed := range seeds {
_, hasExecutedSeed := executedSeeds[k]
if !hasExecutedSeedsSetting || !hasExecutedSeed ||
(hasExecutedSeed && executedSeeds[k] < seed.Version()) {
seed.Execute(ormService)
newSeeds[k] = seed.Version()
}
}
if len(newSeeds) > 0 {
saveNewSeeds(ormService, newSeeds)
}
}
func saveNewSeeds(ormService *beeorm.Engine, newSeeds entity.SettingSeedsValue) {
settingsEntity := &entity.SettingsEntity{}
query := &beeorm.RedisSearchQuery{}
query.FilterString("Key", entity.HitrixSettingAll.Seeds)
hasExecutedSeedsSetting := ormService.RedisSearchOne(settingsEntity, query)
if hasExecutedSeedsSetting {
var oldSeeds entity.SettingSeedsValue
if err := json.Unmarshal([]byte(settingsEntity.Value), &oldSeeds); err != nil {
panic(err.Error())
}
// overwrite old with newSeeds
for k, v := range newSeeds {
oldSeeds[k] = v
}
newSeeds = oldSeeds
} else {
settingsEntity.Key = entity.HitrixSettingAll.Seeds
}
str, err := json.Marshal(newSeeds)
if err != nil {
panic(err.Error())
}
settingsEntity.Value = string(str)
ormService.Flush(settingsEntity)
}