-
Notifications
You must be signed in to change notification settings - Fork 13
/
seed_db.go
82 lines (62 loc) · 1.6 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
package scripts
import (
"context"
"log"
"os"
"github.com/latolukasz/beeorm"
"github.com/coretrix/hitrix/pkg/entity"
"github.com/coretrix/hitrix/service"
"github.com/coretrix/hitrix/service/component/app"
)
type DBSeedScript struct {
SeedsPerProject map[string][]Seed
}
func (script *DBSeedScript) Run(_ context.Context, _ app.IExit) {
ormService := service.DI().OrmEngine()
appService := service.DI().App()
Seeder(script.SeedsPerProject, ormService, appService)
}
func (script *DBSeedScript) Infinity() bool {
return true
}
func (script *DBSeedScript) Unique() bool {
return true
}
func (script *DBSeedScript) Description() string {
return "Seed Database"
}
type Seed interface {
Execute(*beeorm.Engine)
Environments() []string
Name() string
}
func Seeder(seedsPerProject map[string][]Seed, ormService *beeorm.Engine, appService *app.App) {
for project, seeds := range seedsPerProject {
if project != os.Getenv("PROJECT_NAME") {
continue
}
for _, seed := range seeds {
supportCurrentEnv := false
for _, env := range seed.Environments() {
if env == appService.Mode {
supportCurrentEnv = true
break
}
}
if !supportCurrentEnv {
continue
}
seederEntity := &entity.SeederEntity{}
whereStmt := beeorm.NewWhere("`Name` = ?", seed.Name())
found := ormService.SearchOne(whereStmt, seederEntity)
if found {
continue
}
seed.Execute(ormService)
seederEntity.Name = seed.Name()
seederEntity.CreatedAt = service.DI().Clock().Now()
ormService.Flush(seederEntity)
log.Println("Seeder " + seed.Name() + " has been executed")
}
}
}