-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcmd_list.go
More file actions
90 lines (76 loc) · 1.95 KB
/
Copy pathcmd_list.go
File metadata and controls
90 lines (76 loc) · 1.95 KB
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
package main
import (
"database/sql"
"errors"
"fmt"
"path/filepath"
"github.com/jmoiron/sqlx"
"github.com/spf13/cobra"
"github.com/makiuchi-d/migy/dbstate"
"github.com/makiuchi-d/migy/migrations"
)
var cmdList = &cobra.Command{
Use: "list [flags] [DUMP_FILE | --host HOST DB_NAME | --dsn DSN]",
Short: "List migration files needed to reach the target state",
Long: `Lists migration files needed to reach the target migration number by
comparing the migration directory with the database or dump file.`,
RunE: func(cmd *cobra.Command, args []string) error {
db, err := openDBorDumpfile(args)
if err != nil {
return err
}
if db == nil {
return errors.New("data source or dump file is required")
}
return printFilesToApply(db, targetDir, targetNum)
},
}
func init() {
cmd.AddCommand(cmdList)
addFlagNumber(cmdList)
addFlagsForDB(cmdList)
}
func printFilesToApply(db *sqlx.DB, dir string, num int) error {
files, err := listFilesToApply(db, dir, num)
if err != nil {
return err
}
for _, file := range files {
fmt.Println(filepath.Join(dir, file))
}
return nil
}
func listFilesToApply(db *sqlx.DB, dir string, num int) ([]string, error) {
migs, err := migrations.Load(dir)
if err != nil {
return nil, err
}
if num < 0 {
num = migs.Last().Number
}
err = dbstate.HasMigrationTable(db)
if err != nil {
if !errors.Is(err, dbstate.ErrNoMigrationTable) {
return nil, err
}
// show files from snapshot
i, err := migs.FindNumber(num)
if err != nil {
return nil, err
}
return migs[:i+1].FileNamesFromSnapshot()
}
hists, err := migrations.LoadHistories(db)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, errors.New("'_migrations' table found but not initialized")
}
return nil, err
}
cur := hists.CurrentNum()
ms := make(migrations.Migrations, 0, len(migs))
for s := range migrations.BuildStatus(migs, hists) {
ms = append(ms, s.Migration)
}
return ms.FileNamesToApply(cur, num)
}