-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstance.go
262 lines (217 loc) · 7.53 KB
/
instance.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package migrate
import (
"database/sql"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"sort"
"time"
"github.com/octacian/metadb"
)
// ErrNoVersion is returned by Goto when the requested version does not exist.
type ErrNoVersion struct {
Version int
Target int
}
// Error implements the error interface for ErrNoVersion.
func (err *ErrNoVersion) Error() string {
return fmt.Sprintf("Instance.Goto: migration for version '%d', on the way to version "+
"'%d', does not exist", err.Version, err.Target)
}
// ErrNoMigrations is returned by Goto and Latest when there are no more
// migrations to apply.
type ErrNoMigrations struct {
Version int
}
// Error implements the error interface for ErrNoMigrations.
func (err *ErrNoMigrations) Error() string {
return fmt.Sprintf("Instance.Goto: no migrations to apply, current version %d == latest version %d",
err.Version, err.Version)
}
// Instance represents a single collective set of migrations. With the
// exception of the Output field, instance is not intended to be directly
// created and manipulated, but rather managed by NewInstance and a variety of
// methods.
type Instance struct {
db *sql.DB
meta *metadb.Instance
migrations map[int]*Migration
// Output controls the destination for messages emitted by the Instance.
Output io.Writer
}
// NewInstance takes a pointer to a database object and a directory path. It
// loops through this directory, attempting to interpret each sub-directory
// as an individual Migration. Within these sub-directories can be any number
// of files, each representing a single Part. NewInstance returns a pointer to
// an Instance if successful. NewInstance returns an error if there is a gap
// between two migration versions or if any other error occurs.
func NewInstance(db *sql.DB, root string) (*Instance, error) {
if db == nil {
return nil, NewFatalf("NewInstance: got nil database handle")
}
meta, err := metadb.NewInstance(db)
if err != nil {
return nil, NewFatalf("NewInstance: got error while creating metadb instance:\n%s", err)
}
instance := &Instance{db: db, meta: meta, migrations: make(map[int]*Migration, 0), Output: os.Stdout}
directories, err := ioutil.ReadDir(root)
if err != nil {
return nil, err
}
for _, directory := range directories {
if !directory.IsDir() {
continue
}
migration, err := NewMigration(path.Join(root, directory.Name()))
if err != nil {
return nil, err
}
instance.migrations[migration.Version] = migration
}
// if no migrations were added, return an error
if len(instance.migrations) == 0 {
return nil, NewFatalf("NewInstance: no migrations found in '%s'", root)
}
keys := make([]int, 0)
for key := range instance.migrations {
keys = append(keys, key)
}
sort.Ints(keys)
lastVersion := 0
// Check for gaps in migration version
for _, key := range keys {
if key != lastVersion+1 {
return nil, NewFatalf("NewInstance: found gap between migration version %d and %d", lastVersion, key)
}
lastVersion++
}
return instance, nil
}
// Version returns an integer representing which Migration the database is
// currently on. Version panics if the metadata entry in which the version is
// stored exists but cannot be fetched for some reason.
func (instance *Instance) Version() int {
res, err := instance.meta.Get("migrateVersion")
if err != nil {
if _, ok := err.(*metadb.ErrNoEntry); ok {
return 0
}
panic(fmt.Sprint("Instance.Version: got error:\n", err))
}
return res.(int)
}
// List returns a slice of integers holding the version numbers of all
// available Migrations.
func (instance *Instance) List() []int {
versions := make([]int, 0)
for i := 1; i <= len(instance.migrations); i++ {
versions = append(versions, i)
}
return versions
}
// Goto applies any migrations necessary to bring the database schema to the
// state defined by the migration version specified. Goto employs transactions,
// ensuring that if anything fails, the database is automatically reverted to
// how it was before Goto was called.
func (instance *Instance) Goto(target int) error {
currentVersion := instance.Version()
todo := make([]*Migration, 0)
direction := "up"
jump := 1
start := time.Now()
addToTodo := func(i int) error {
midway, ok := instance.migrations[i]
if !ok {
return &ErrNoVersion{Version: i, Target: target}
}
todo = append(todo, midway)
return nil
}
// if requested version is greater than the current version, migrate up
if target > currentVersion {
for i := currentVersion + 1; i <= target; i++ {
if err := addToTodo(i); err != nil {
return err
}
}
jump = target - currentVersion
} else if target < currentVersion { // else if requested version is less than the current version, migrate down
for i := currentVersion; i > target; i-- {
if err := addToTodo(i); err != nil {
return err
}
}
direction = "down"
jump = currentVersion - target
} else { // else, specified version is the same as the current version, return an error
return &ErrNoMigrations{target}
}
if jump > 1 {
fmt.Fprintf(instance.Output, "\033[1mmigrate: Preparing to migrate over %d version(s)...\033[0m\n", jump)
}
transaction, err := instance.db.Begin()
if err != nil {
return NewFatalf("Instance.Goto: got error while starting a transaction:\n%s", err)
}
// Loop through and apply migrations
for key, migration := range todo {
fromVersion := currentVersion + key
toVersion := migration.Version
if direction == "down" {
fromVersion = currentVersion - key
toVersion--
}
fmt.Fprintf(instance.Output, "\033[1mmigrate: Beginning migration %s from version %d to %d...\033[0m\n",
direction, fromVersion, toVersion)
applied := make([]int, 0)
failed := make([]int, 0)
// Apply all migration parts as per direction
for key, part := range migration.Parts {
var err error
if direction == "up" {
_, err = transaction.Exec(part.Up)
} else {
_, err = transaction.Exec(part.Down)
}
// if an error was returned, application of the part failed
if err != nil {
fmt.Fprintf(instance.Output, "\033[31;1m- Failed to apply '%s': %s\033[0m\n", part.Name, err)
failed = append(failed, key)
continue
}
applied = append(applied, key)
fmt.Fprintf(instance.Output, "- Applied '%s'\n", part.Name)
}
// if any migration parts failed, cancel transaction and exit
if len(failed) > 0 {
fmt.Fprintf(instance.Output, "\n\033[1mmigrate: %d parts failed to apply, reverting %d successfully "+
"applied parts...\033[0m\n", len(failed), len(applied))
transaction.Rollback()
return NewFatalf("Instance.Goto: got error while applying migrations")
}
fmt.Fprintf(instance.Output, "\033[1mmigrate: Successfully applied %d migration part(s)\n", len(applied))
}
if err := transaction.Commit(); err != nil {
return NewFatalf("Instance.Goto: got error while committing transaction:\n%s", err)
}
if err := instance.meta.Set("migrateVersion", target); err != nil {
return NewFatalf("Instance.Goto: got error while updating migrate version:\n%s", err)
}
fmt.Fprintf(instance.Output, "\n\033[1mmigrate: Successfully applied migrations in %s\033[0m\n", time.Since(start))
return nil
}
// Latest applies any new migrations available. Transactions are employed,
// ensuring that if anything fails, the database is automatically reverted to
// how it was before Latest was called.
func (instance *Instance) Latest() error {
latestVersion := 0
// Find highest available version
for _, migration := range instance.migrations {
if migration.Version > latestVersion {
latestVersion = migration.Version
}
}
return instance.Goto(latestVersion)
}