-
Notifications
You must be signed in to change notification settings - Fork 5
/
migrator.go
68 lines (55 loc) · 1.32 KB
/
migrator.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
package main
import (
"database/sql"
"os"
"sort"
"strings"
"time"
"github.com/GeertJohan/go.rice"
"github.com/Sirupsen/logrus"
)
func migrate(db *sql.DB, box *rice.Box) error {
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.Exec(`create table if not exists migrations (name text not null unique, applied_at datetime not null);`); err != nil {
return err
}
var names []string
if err := box.Walk("", func(p string, m os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.HasSuffix(p, ".sql") {
names = append(names, p)
}
return nil
}); err != nil {
return err
}
sort.Strings(names)
for _, n := range names {
s, err := box.String(n)
if err != nil {
return err
}
logrus.WithField("file", n).Info("checking migration status")
var count int
if err := tx.QueryRow("select count(1) from migrations where name = $1", n).Scan(&count); err != nil {
return err
} else if count == 0 {
logrus.WithField("file", n).Info("applying migration")
if _, err := tx.Exec(s); err != nil {
return err
}
if _, err = tx.Exec("insert into migrations (name, applied_at) values($1, $2)", n, time.Now()); err != nil {
return err
}
} else {
logrus.WithField("file", n).Info("already applied")
}
}
return tx.Commit()
}