/
goway.go
181 lines (160 loc) · 4.59 KB
/
goway.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
/**
* Database schema migration framework.
*
* TODO: in the long run, open source this.
*
* Properties:
* - no "down" migrations, only "up"
* - plain text files containing sql statements
* - located in ${GOPATH}/setup/migrations
* - filename format: "v([1-9][0-9]?)-([a-zA-Z]*)\.sql"
*
* Migrations are applied in the increasing order of version in the filename. So
* in the example below, first the v1-InitialSchema migration is applied, then
* the v2-AddSchemaTable migration.
*
* Example:
* v1-InitialSchema.sql
* v2-AddSchemaTable.sql
*/
package goway
import (
"log"
"database/sql"
"errors"
"fmt"
"io/ioutil"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
var regex, _ = regexp.Compile("^v([1-9][0-9]?)-([a-zA-Z]+).sql$")
type SchemaVersion struct {
Number int
Name string
Applied time.Time
}
type Migration struct {
File os.FileInfo
Number int
Description string
}
type Migrations struct {
m []Migration
}
func (s Migrations) Less(i, j int) bool {
return s.m[i].Number < s.m[j].Number
}
func (s Migrations) Len() int {
return len(s.m)
}
func (s Migrations) Swap(i, j int) {
s.m[i], s.m[j] = s.m[j], s.m[i]
}
func getCurrentVersion(db *sql.DB) (schema *SchemaVersion, err error) {
rows, err := db.Query("SELECT version, name, applied FROM db_versions ORDER BY version DESC LIMIT 1")
// oh, I wish there was a better way to check this...
if err != nil {
if strings.Contains(err.Error(), "1146") {
_, err = db.Exec("CREATE TABLE db_versions (version INTEGER PRIMARY KEY NOT NULL, name VARCHAR(50) NOT NULL, applied DATETIME)")
if err != nil {
return nil, err
}
return &SchemaVersion{0, "-", time.Time{}}, nil
} else {
return nil, err
}
}
// don't forget to close the rows
defer rows.Close()
// try to get the schema version
// if the table didn't exist yet, create it
schema = &SchemaVersion{}
rows.Next()
err = rows.Scan(&schema.Number, &schema.Name, &schema.Applied)
if err != nil {
return nil, err
}
return schema, nil
}
func getAvailableMigrations(location string) ([]Migration, error) {
files, err := ioutil.ReadDir(location)
if err != nil {
return nil, err
}
migrations := make([]Migration, len(files))
i := 0
for _, file := range files {
matches := regex.FindAllStringSubmatch(file.Name(), -1)
if matches != nil && len(matches) == 1 {
version, _ := strconv.Atoi(matches[0][1])
migrations[i] = Migration{file, version, matches[0][2]}
i = i + 1
//} else {
// println(fmt.Sprintf("Ignoring migration file %s. Filename didn't match pattern!", files[idx].Name()))
}
}
sortable := Migrations{migrations[:i]}
sort.Sort(sortable)
return sortable.m, nil
}
func (migration Migration) apply(db *sql.DB, location string) error {
println(fmt.Sprintf("Applying migration %d - '%s'", migration.Number, migration.Description))
content, _ := ioutil.ReadFile(fmt.Sprintf("%s/%s", location, migration.File.Name()))
if len(content) == 0 {
return errors.New("Empty migrations file")
}
tx, err := db.Begin()
if err != nil {
return err
}
statements := strings.Split(string(content), ";")
for _, statement := range statements {
statement = strings.TrimSpace(statement)
if len(statement) > 0 {
_, err = tx.Exec(statement)
if err != nil {
tx.Rollback()
return err
}
}
}
_, err = tx.Exec("INSERT INTO db_versions (version, name, applied) VALUES (?, ?, NOW())", migration.Number, migration.Description)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
func Upgrade(db *sql.DB, location string) {
println("Performing db schema upgrade...")
// Get a list of available migrations.
migrations, err := getAvailableMigrations(location)
if err != nil {
log.Fatalf("Failed to get a list of available database schema migrations: %s", err.Error())
}
// Get the current version in the db.
current, err := getCurrentVersion(db)
if err != nil {
log.Fatalf("Failed to get the current database schema version: %s", err)
}
println(fmt.Sprintf("Current db version: %d, applied %s", current.Number, current.Applied))
// Apply the pending migrations one by one in statements
for _, migration := range migrations {
if migration.Number > current.Number {
err = migration.apply(db, location)
if err != nil {
panic(fmt.Sprintf("Failed to update the database schema to version %d: %s", migration.Number, err))
}
}
}
// Get the current version in the db.
current, err = getCurrentVersion(db)
if err != nil {
log.Fatalf("Failed to get the current database schema version: %s", err)
}
println(fmt.Sprintf("Updated db version: %d, applied %s", current.Number, current.Applied))
}