-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
89 lines (73 loc) · 2.15 KB
/
main.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
package main
import (
"database/sql"
"flag"
"fmt"
"log"
"path/filepath"
"github.com/4396/goose-tinker/lib/goose"
)
// global options. available to any subcommands.
var flagPath = flag.String("path", "db", "folder containing db info")
var flagEnv = flag.String("env", "development", "which DB environment to use")
var flagPgSchema = flag.String("pgschema", "", "which postgres-schema to migrate (default = none)")
var strictMode = flag.Bool("strict", false, "strict mode (default = false)")
// helper to create a DBConf from the given flags
func dbConfFromFlags() (dbconf *goose.DBConf, err error) {
return goose.NewDBConf(*flagPath, *flagEnv, *flagPgSchema)
}
func main() {
flag.Parse()
conf, err := dbConfFromFlags()
if err != nil {
log.Fatal(err)
}
// collect all migrations
min := int64(0)
max := int64((1 << 63) - 1)
migrations, e := goose.CollectMigrations(conf.MigrationsDir, min, max)
if e != nil {
log.Fatal(e)
}
db, e := goose.OpenDBFromDBConf(conf)
if e != nil {
log.Fatal("couldn't open DB:", e)
}
defer db.Close()
// must ensure that the version table exists if we're running on a pristine DB
if _, e := goose.EnsureDBVersion(conf, db); e != nil {
log.Fatal(e)
}
fmt.Printf("goose: status for environment '%v'\n", conf.Env)
goose.SortMigrations(migrations, true)
for _, m := range migrations {
runPendingMigration(conf, db, m.Version, m.Source)
}
}
func runPendingMigration(conf *goose.DBConf, db *sql.DB, version int64, source string) {
var row goose.MigrationRecord
q := fmt.Sprintf("SELECT tstamp, is_applied FROM goose_db_version WHERE version_id=%d ORDER BY tstamp DESC LIMIT 1", version)
e := db.QueryRow(q).Scan(&row.TStamp, &row.IsApplied)
if e != nil && e != sql.ErrNoRows {
return
}
if row.IsApplied {
return
}
var err error
switch filepath.Ext(source) {
case ".go":
err = goose.RunGoMigration(conf, source, version, true)
case ".sql":
err = goose.RunSQLMigration(conf, db, source, version, true)
}
if err != nil {
if *strictMode {
log.Fatalf("FAIL %v, quitting migration", err)
}
fmt.Println("FAIL ", filepath.Base(source))
return
}
fmt.Println("OK ", filepath.Base(source))
return
}