-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreset.go
64 lines (56 loc) · 1.37 KB
/
reset.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
package migration
import (
"fmt"
"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 NewReset(app contracts.Application) contracts.Command {
dir, _ := os.Getwd()
if str, exists := app.Get("migrations.dir").(string); exists && str != "" {
dir += "/" + str
} else {
dir += "/migrations"
}
return &Reset{
Command: commands.Base("migrate:reset", "Rollback all database migrations"),
conn: app.Get("db").(contracts.DBConnection),
dir: dir,
}
}
type Reset struct {
commands.Command
conn contracts.DBConnection
dir string
}
func (cmd Reset) Handle() any {
logs.Default().Info("执行重置")
initTable(cmd.conn)
var items []MigrateMsg
var migrated = Migrations().Get()
var dir = cmd.StringOptional("path", cmd.dir)
migrated.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: migration.Batch,
Path: migration.Path,
Action: "reset",
Time: time.Now().Sub(now),
})
Migrations().Where("id", migration.Id).Delete()
})
table.Output(items)
return nil
}