forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
61 lines (52 loc) · 1.83 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
package schema
import (
"database/sql"
"errors"
migrate "github.com/rubenv/sql-migrate"
"github.com/stellar/go/support/db"
)
// MigrateDir represents a direction in which to perform schema migrations.
type MigrateDir string
const (
// MigrateUp causes migrations to be run in the "up" direction.
MigrateUp MigrateDir = "up"
// MigrateDown causes migrations to be run in the "down" direction.
MigrateDown MigrateDir = "down"
// MigrateRedo causes migrations to be run down, then up
MigrateRedo MigrateDir = "redo"
)
// Init installs the latest schema into db after clearing it first
func Init(db *db.Session, latest []byte) error {
return db.ExecAll(string(latest))
}
// Migrate performs schema migration. Migrations can occur in one of three
// ways:
//
// - up: migrations are performed from the currently installed version upwards.
// If count is 0, all unapplied migrations will be run.
//
// - down: migrations are performed from the current version downard. If count
// is 0, all applied migrations will be run in a downard direction.
//
// - redo: migrations are first ran downard `count` times, and then are rand
// upward back to the current version at the start of the process. If count is
// 0, a count of 1 will be assumed.
func Migrate(db *sql.DB, migrations migrate.MigrationSource, dir MigrateDir, count int) (int, error) {
switch dir {
case MigrateUp:
return migrate.ExecMax(db, "postgres", migrations, migrate.Up, count)
case MigrateDown:
return migrate.ExecMax(db, "postgres", migrations, migrate.Down, count)
case MigrateRedo:
if count == 0 {
count = 1
}
down, err := migrate.ExecMax(db, "postgres", migrations, migrate.Down, count)
if err != nil {
return down, err
}
return migrate.ExecMax(db, "postgres", migrations, migrate.Up, down)
default:
return 0, errors.New("Invalid migration direction")
}
}