forked from cloudloyalty/db
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate.go
72 lines (60 loc) · 1.18 KB
/
migrate.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
package db
import (
"context"
"database/sql"
"strings"
)
const InitialMigration = `
CREATE TABLE IF NOT EXISTS migrations (version INT NOT NULL PRIMARY KEY);
INSERT INTO migrations VALUES (1);
`
type Migrate struct {
db *sql.DB
}
type Migration struct {
Version int
Sql string
}
func NewMigrate(db *sql.DB) *Migrate {
return &Migrate{
db: db,
}
}
func (m *Migrate) Run(migrations []Migration) error {
latest, err := m.getLatestVersion()
if err != nil {
return err
}
tx, err := m.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
ctx := context.Background()
for _, m := range migrations {
if err != nil {
break
}
if m.Version > latest {
_, err = tx.Exec(m.Sql)
latest = m.Version
}
}
if err == nil {
_, err := Exec(ctx, tx, "UPDATE migrations SET version = :latest", Params{"latest": latest})
if err != nil {
return err
}
tx.Commit()
}
return err
}
func (m *Migrate) getLatestVersion() (int, error) {
var latest int
row := m.db.QueryRow("SELECT version FROM migrations")
err := row.Scan(&latest)
if err != nil && err != sql.ErrNoRows && !strings.Contains(err.Error(), "migrations") {
return 0, err
}
return latest, nil
}