-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmigration.go
87 lines (76 loc) · 1.8 KB
/
migration.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
package migrator
import "database/sql"
type executableSQL interface {
Exec(query string, args ...interface{}) (sql.Result, error)
}
// Migration represents migration entity
//
// Name should be a unique name to specify migration. It is up to you to choose the name you like
// Up() should return Schema with prepared commands to be migrated
// Down() should return Schema with prepared commands to be reverted
// Transaction optinal flag to enable transaction for migration
//
// Example:
// var migration = migrator.Migration{
// Name: "19700101_0001_create_posts_table",
// Up: func() migrator.Schema {
// var s migrator.Schema
// posts := migrator.Table{Name: "posts"}
//
// posts.UniqueID("id")
// posts.Column("title", migrator.String{Precision: 64})
// posts.Column("content", migrator.Text{})
// posts.Timestamps()
//
// s.CreateTable(posts)
//
// return s
// },
// Down: func() migrator.Schema {
// var s migrator.Schema
//
// s.DropTableIfExists("posts")
//
// return s
// },
// }
type Migration struct {
Name string
Up func() Schema
Down func() Schema
Transaction bool
}
func (m Migration) exec(db *sql.DB, commands ...command) error {
if m.Transaction {
return runInTransaction(db, commands...)
}
return run(db, commands...)
}
func runInTransaction(db *sql.DB, commands ...command) error {
tx, err := db.Begin()
if err != nil {
return err
}
err = run(tx, commands...)
if err != nil {
tx.Rollback()
return err
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func run(db executableSQL, commands ...command) error {
for _, command := range commands {
sql := command.toSQL()
if sql == "" {
return ErrNoSQLCommandsToRun
}
if _, err := db.Exec(sql); err != nil {
return err
}
}
return nil
}