-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmigration_sql.go
80 lines (64 loc) · 2.01 KB
/
migration_sql.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
package main
import (
"database/sql"
"fmt"
"io/ioutil"
"log"
"path/filepath"
"strings"
)
// Run a migration specified in raw SQL.
//
// Sections of the script can be annotated with a special comment,
// starting with "-- +goose" to specify whether the section should
// be applied during an Up or Down migration
//
// All statements following an Up or Down directive are grouped together
// until another direction directive is found.
func runSQLMigration(db *sql.DB, script string, v int64, direction int) error {
txn, err := db.Begin()
if err != nil {
log.Fatal("db.Begin:", err)
}
f, err := ioutil.ReadFile(script)
if err != nil {
log.Fatal(err)
}
// ensure we don't apply a query until we're sure it's going
// in the direction we're interested in
directionIsActive := false
// find each statement, checking annotations for up/down direction
// and execute each of them in the current transaction
stmts := strings.Split(string(f), ";")
for _, query := range stmts {
query = strings.TrimSpace(query)
if strings.HasPrefix(query, "-- +goose Up") {
directionIsActive = direction == 1
} else if strings.HasPrefix(query, "-- +goose Down") {
directionIsActive = direction == 0
}
if !directionIsActive || query == "" {
continue
}
if _, err = txn.Exec(query); err != nil {
txn.Rollback()
log.Fatalf("FAIL %s (%v), quitting migration.", filepath.Base(script), err)
return err
}
}
if err = finalizeMigration(txn, direction, v); err != nil {
log.Fatalf("error finalizing migration %s, quitting. (%v)", filepath.Base(script), err)
}
return nil
}
// Update the version table for the given migration,
// and finalize the transaction.
func finalizeMigration(txn *sql.Tx, direction int, v int64) error {
// XXX: drop goose_db_version table on some minimum version number?
versionStmt := fmt.Sprintf("INSERT INTO goose_db_version (version_id, is_applied) VALUES (%d, %d);", v, direction)
if _, err := txn.Exec(versionStmt); err != nil {
txn.Rollback()
return err
}
return txn.Commit()
}