This repository has been archived by the owner on Mar 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
command.go
213 lines (166 loc) · 5.32 KB
/
command.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package cli
import (
"database/sql"
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
"text/template"
"time"
"code.cloudfoundry.org/lager"
"github.com/concourse/voyager"
"github.com/concourse/voyager/migrations"
"github.com/gobuffalo/packr"
)
var defaultMigrationDir = "../../migrations/"
var advisoryLockID = 14656
type MigrationType string
const (
SQL MigrationType = "sql"
Go MigrationType = "go"
)
type MigrationCommand struct {
//TODO : use commands shortcuts.
GenerateCommand GenerateCommand `command:"generate"`
CurrentVersionCommand CurrentVersionCommand `command:"current-version"`
MigrateCommand MigrateCommand `command:"migrate"`
}
type MigrateCommand struct {
MigrationDirectory string `short:"d" long:"directory" default:"migrations" description:"The directory to which the migration files should be written"`
Version string `short:"v" long:"version" default:"latest" description:"The migration version to migrate up or down to. Use 'latest' to migrate to the latest available version"`
ConnectionString string `short:"c" long:"connection-string" description:"connection string for db"`
}
type GenerateCommand struct {
MigrationDirectory string `short:"d" long:"directory" default:"migrations" description:"The directory to which the migration files should be written"`
MigrationName string `short:"n" long:"name" description:"The name of the migration"`
Type MigrationType `short:"t" long:"type" description:"The file type of the migration"`
}
type CurrentVersionCommand struct {
ConnectionString string `short:"c" long:"connection-string"`
}
func (c *CurrentVersionCommand) Execute(args []string) error {
logger := lager.NewLogger("voyager")
logger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.INFO))
db, err := sql.Open("postgres", c.ConnectionString)
if err != nil {
return err
}
migrator := voyager.NewMigrator(advisoryLockID, nil, nil, nil)
version, err := migrator.CurrentVersion(logger, db)
if err != nil {
return err
}
fmt.Println("Last successfully applied migration:", version)
return nil
}
func (c *GenerateCommand) Execute(args []string) error {
if c.Type == SQL {
return c.generateSQLMigration()
} else if c.Type == Go {
return c.generateGoMigration()
}
return fmt.Errorf("unsupported migration type %s. Supported types include %s and %s", c.Type, SQL, Go)
}
func (c *GenerateCommand) generateSQLMigration() error {
currentTime := time.Now().Unix()
fileNameFormat := "%d_%s.%s.sql"
upMigrationFileName := fmt.Sprintf(fileNameFormat, currentTime, c.MigrationName, "up")
downMigrationFileName := fmt.Sprintf(fileNameFormat, currentTime, c.MigrationName, "down")
contents := ""
err := ioutil.WriteFile(path.Join(c.MigrationDirectory, upMigrationFileName), []byte(contents), 0644)
if err != nil {
return err
}
err = ioutil.WriteFile(path.Join(c.MigrationDirectory, downMigrationFileName), []byte(contents), 0644)
if err != nil {
return err
}
return nil
}
func (c *MigrateCommand) Execute(args []string) error {
logger := lager.NewLogger("voyager")
logger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.INFO))
db, err := sql.Open("postgres", c.ConnectionString)
if err != nil {
return err
}
box := packr.NewBox(defaultMigrationDir)
migrator := voyager.NewMigrator(advisoryLockID, source{box}, migrations.NewMigrationsRunner(), nil)
var toVersion int
if c.Version == "latest" {
toVersion = 0
} else {
toVersion, err = strconv.Atoi(c.Version)
if err != nil {
return err
}
}
err = migrator.Migrate(logger, db, toVersion)
if err != nil {
return fmt.Errorf("an error occurred while running migrations: %s", err.Error())
}
fmt.Println("Successfully migrated to version", c.Version)
return nil
}
type migrationInfo struct {
MigrationId int64
Direction string
}
const goMigrationTemplate = `package migrations
// implement the migration in this function
func {{ .Direction }}_{{ .MigrationId }}() error {
return nil
}`
func renderGoMigrationToFile(filePath string, state migrationInfo) error {
migrationFile, err := os.Create(filePath)
if err != nil {
return err
}
defer migrationFile.Close()
tmpl, err := template.New("go-migration-template").Parse(goMigrationTemplate)
if err != nil {
return err
}
err = tmpl.Execute(migrationFile, state)
if err != nil {
return err
}
return nil
}
func (c *GenerateCommand) generateGoMigration() error {
currentTime := time.Now().Unix()
fileNameFormat := "%d_%s.%s.go"
upMigrationFileName := fmt.Sprintf(fileNameFormat, currentTime, c.MigrationName, "up")
downMigrationFileName := fmt.Sprintf(fileNameFormat, currentTime, c.MigrationName, "down")
err := renderGoMigrationToFile(path.Join(c.MigrationDirectory, upMigrationFileName), migrationInfo{
MigrationId: currentTime,
Direction: "Up",
})
if err != nil {
return err
}
err = renderGoMigrationToFile(path.Join(c.MigrationDirectory, downMigrationFileName), migrationInfo{
MigrationId: currentTime,
Direction: "Down",
})
if err != nil {
return err
}
return nil
}
type source struct {
packr.Box
}
func (s source) AssetNames() []string {
migrations := make([]string, 0)
for _, name := range s.List() {
if name != "migrations.go" {
migrations = append(migrations, name)
}
}
return migrations
}
func (s source) Asset(name string) ([]byte, error) {
return s.MustBytes(name)
}