-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrefresh.go
93 lines (84 loc) · 2.08 KB
/
refresh.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
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 NewRefresh(app contracts.Application) contracts.Command {
dir, _ := os.Getwd()
if str, exists := app.Get("migrations.dir").(string); exists && str != "" {
dir += "/" + str
} else {
dir += "/migrations"
}
return &Refresh{
Command: commands.Base("migrate:refresh", "execute migrations"),
conn: app.Get("db").(contracts.DBConnection),
dir: dir,
}
}
type Refresh struct {
commands.Command
conn contracts.DBConnection
dir string
}
func (cmd Refresh) Handle() any {
logs.Default().Info("执行 refresh")
initTable(cmd.conn)
var items []MigrateMsg
var dir = cmd.StringOptional("path", cmd.dir)
if Migrations().Count() > 0 {
var batch = cmd.IntOptional("batch", int(Migrations().Max("batch")))
Migrations().Get().Map(func(i int, migration Migration) {
sqlBytes, err := os.ReadFile(fmt.Sprintf("%s/%s", dir, strings.ReplaceAll(migration.Path, ".sql", ".down.sql")))
if err != nil {
panic(err)
}
now := time.Now()
_, e := cmd.conn.Exec(string(sqlBytes))
if e != nil {
panic(e)
}
items = append(items, MigrateMsg{
Batch: batch,
Path: migration.Path,
Action: "rollback",
Time: time.Now().Sub(now),
})
Migrations().Where("id", migration.Id).Delete()
})
}
var files = collection.New(getFiles(dir)).Filter(func(i int, s string) bool {
return !strings.HasSuffix(s, ".down.sql")
}).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: 1,
Path: path,
Time: time.Now().Sub(now),
})
Migrations().Create(contracts.Fields{
"batch": 1,
"path": path,
"created_at": time.Now(),
})
}
table.Output(items)
return nil
}