-
Notifications
You must be signed in to change notification settings - Fork 35
/
apply.go
99 lines (83 loc) · 2.4 KB
/
apply.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
94
95
96
97
98
99
package main
import (
"fmt"
"github.com/elwinar/rambler/log"
"github.com/urfave/cli"
)
// Apply available migrations based on the provided context.
func Apply(ctx *cli.Context) error {
return apply(service, ctx.Bool("all"), !ctx.Bool("no-save"), ctx.String("migration"), logger)
}
func apply(service Servicer, all, save bool, migration string, logger *log.Logger) error {
logger.Debug("checking database state")
initialized, err := service.Initialized()
if err != nil {
return fmt.Errorf("unable to check for database state: %s", err)
}
if !initialized {
logger.Info("initializing database")
err := service.Initialize()
if err != nil {
return fmt.Errorf("unable to initialize database: %s", err)
}
}
var targets []*Migration
if migration != "" {
logger.Debug("fetching migration")
m, err := NewMigration(migration)
if err != nil {
return fmt.Errorf("unable to retrieve migration: %s", err)
}
targets = append(targets, m)
} else {
logger.Debug("fetching available migrations")
available, err := service.Available()
if err != nil {
return fmt.Errorf("unable to retrieve available migrations: %s", err)
}
logger.Info("found %d available migrations", len(available))
logger.Debug("fetching applied migrations")
applied, err := service.Applied()
if err != nil {
return fmt.Errorf("unable to retrieve applied migrations: %s", err)
}
logger.Info("found %d applied migrations", len(applied))
logger.Debug("comparing available and applied migrations")
var i, j = 0, 0
for i < len(available) && j < len(applied) {
logger.Debug("comparing %s and %s", available[i].Name, applied[j].Name)
if available[i].Name == applied[j].Name {
i++
j++
continue
}
if available[i].Name < applied[j].Name {
return fmt.Errorf("out of order migration: %s", available[i].Name)
}
if available[i].Name > applied[j].Name {
return fmt.Errorf("missing migration: %s", applied[j].Name)
}
}
if j != len(applied) {
return fmt.Errorf("missing migration: %s", applied[j].Name)
}
targets = available[i:]
}
if len(targets) == 0 {
logger.Info("no migration to apply")
return nil
}
logger.Info("%d migrations to apply", len(targets))
for _, migration := range targets {
logger.Info("applying %s", migration.Name)
err := service.Apply(migration, save)
if err != nil {
return err
}
if !all {
break
}
}
logger.Info("done")
return nil
}