forked from rubenv/sql-migrate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command_common.go
90 lines (78 loc) · 2 KB
/
command_common.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
package main
import (
"fmt"
"github.com/rubenv/sql-migrate"
)
func ApplyMigrations(dir migrate.MigrationDirection, dryrun, enablePatch bool, limit int) error {
env, err := GetEnvironment()
if err != nil {
return fmt.Errorf("Could not parse config: %s", err)
}
db, dialect, err := GetConnection(env)
if err != nil {
return err
}
source := migrate.FileMigrationSource{
Dir: env.Dir,
}
if dryrun {
if enablePatch {
migrationsPatch, _, err := migrate.PlanMigrationPatch(db, dialect, source, dir, limit)
if err != nil {
return fmt.Errorf("Cannot plan migration: %s", err)
}
for _, m := range migrationsPatch {
PrintMigrationPatch(m, dir)
}
return nil
}
migrations, _, err := migrate.PlanMigration(db, dialect, source, dir, limit)
if err != nil {
return fmt.Errorf("Cannot plan migration: %s", err)
}
for _, m := range migrations {
PrintMigration(m, dir)
}
} else {
n, err := migrate.ExecMax(db, dialect, source, dir, limit)
if err != nil {
return fmt.Errorf("Migration failed: %s", err)
}
if n == 1 {
ui.Output("Applied 1 migration")
} else {
ui.Output(fmt.Sprintf("Applied %d migrations", n))
}
}
return nil
}
func PrintMigration(m *migrate.PlannedMigration, dir migrate.MigrationDirection) {
if dir == migrate.Up {
ui.Output(fmt.Sprintf("==> Would apply migration %s (up)", m.Id))
for _, q := range m.Up {
ui.Output(q)
}
} else if dir == migrate.Down {
ui.Output(fmt.Sprintf("==> Would apply migration %s (down)", m.Id))
for _, q := range m.Down {
ui.Output(q)
}
} else {
panic("Not reached")
}
}
func PrintMigrationPatch(m *migrate.PlannedMigrationPatch, dir migrate.MigrationDirection) {
if dir == migrate.Up {
ui.Output(fmt.Sprintf("==> Would apply migration %s (up)", m.Name))
for _, q := range m.Up {
ui.Output(q)
}
} else if dir == migrate.Down {
ui.Output(fmt.Sprintf("==> Would apply migration %s (down)", m.Name))
for _, q := range m.Down {
ui.Output(q)
}
} else {
panic("Not reached")
}
}