-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate.go
84 lines (74 loc) · 1.81 KB
/
migrate.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
package migration
import (
"fmt"
"github.com/goal-web/collection"
"github.com/goal-web/contracts"
"github.com/goal-web/supports/commands"
"github.com/goal-web/supports/logs"
"github.com/modood/table"
"os"
"strings"
"time"
)
func NewMigrate(app contracts.Application) contracts.Command {
dir, _ := os.Getwd()
if str, exists := app.Get("migrations.dir").(string); exists && str != "" {
dir += "/" + str
} else {
dir += "/migrations"
}
return &Migrate{
Command: commands.Base("migrate", "execute migrations"),
conn: app.Get("db").(contracts.DBConnection),
dir: dir,
}
}
type Migrate struct {
commands.Command
conn contracts.DBConnection
dir string
}
type MigrateMsg struct {
Batch int `json:"batch"`
Path string `json:"path"`
Action string `json:"action"`
Time time.Duration `json:"time"`
}
func (cmd Migrate) Handle() any {
logs.Default().Info("执行迁移")
initTable(cmd.conn)
var batch int
if Migrations().Count() > 0 {
batch = int(Migrations().Max("batch"))
}
var dir = cmd.StringOptional("path", cmd.dir)
var items []MigrateMsg
var migrated = Migrations().Get()
var files = collection.New(getFiles(dir)).Filter(func(i int, s string) bool {
return !strings.HasSuffix(s, ".down.sql") && migrated.Where("path", s).Count() == 0
}).ToArray()
for _, path := range files {
sqlBytes, err := os.ReadFile(fmt.Sprintf("%s/%s", dir, path))
if err != nil {
panic(err)
}
now := time.Now()
_, e := cmd.conn.Exec(string(sqlBytes))
if e != nil {
panic(e)
}
items = append(items, MigrateMsg{
Action: "migrate",
Batch: batch + 1,
Path: path,
Time: time.Now().Sub(now),
})
Migrations().Create(contracts.Fields{
"batch": batch + 1,
"path": path,
"created_at": time.Now(),
})
}
table.Output(items)
return nil
}