-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigrate.go
219 lines (187 loc) · 4.22 KB
/
migrate.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
214
215
216
217
218
219
package gograte
import (
"bufio"
"context"
"database/sql"
"log"
"net/url"
"os"
"strings"
)
type migrationFile struct {
Name string
Timestamp int
// FileName string
Path string
IsNewFile bool
}
type ValidData []string
func (v *ValidData) String() string {
output := ""
length := len(*v)
for index, item := range *v {
if index == length-1 {
output += item
} else {
output += item + ", "
}
}
return output
}
// argument indexes
var DRIVER = 1
var DB_URL = 2
var ACTION = 3
var VERSION = 4
func Migrate(args []string) {
driver := args[DRIVER]
dbURL := args[DB_URL]
action := args[ACTION]
version := ""
if !ValidateDbDriver(driver) {
log.Fatalf("Invalid database driver. Supported databases are: %s\n", DB_DRIVERS.String())
}
driver = GetSQLDriver(driver)
validatedURL, err := validateDbURL(dbURL)
if err != nil {
log.Fatalln("Invalid database URL. Please provide a valid URL.")
}
if !validateAction(action) {
log.Fatalf("Invalid action. Supported actions are: %s\n", ACTIONS.String())
}
if action == "up-to" || action == "down-to" {
if len(args) != 5 {
log.Fatalln("Invalid number of arguments. Please provide a version number.")
}
version = args[VERSION]
}
db, err := sql.Open(driver, validatedURL.String())
if err != nil {
log.Fatalf("Error opening database: %v\n", err)
}
defer db.Close()
conn, err := db.Conn(context.Background())
if err != nil {
log.Fatalf("Error database connection: %v\n", err)
}
defer conn.Close()
_, err = CreateMigrationTableIfNotExist(db)
if err != nil {
log.Fatalf("Error creating migration table: %v\n", err)
}
switch action {
case "up":
upAllMigrate(db)
case "up-one":
upOneMigrate(db)
case "up-to":
upToMigrate(version, db)
case "down":
downAllMigrate(db)
case "down-one":
downOneMigrate(db)
case "down-to":
downToMigrate(version, db)
default:
log.Fatalf("Invalid action. Supported actions are: %s\n", ACTIONS.String())
}
}
func startMigrate(migrationFiles []migrationFile, db *sql.DB, action string) {
for _, m := range migrationFiles {
file, err := os.Open(m.Path)
if err != nil {
log.Fatalf("Error migration opening file: %v\n", err)
return
}
defer file.Close()
info, err := file.Stat()
if err != nil || info.IsDir() {
continue
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var statement string
hasPassedDownMigrateCmt := false
for scanner.Scan() {
line := scanner.Text()
isDownMigrate := strings.HasPrefix(line, downMigrateComment)
if action == "up" {
if isDownMigrate {
break
}
isComment := strings.HasPrefix(line, commentSyntax)
if isComment {
continue
}
statement += line
}
if action == "down" {
if !isDownMigrate && !hasPassedDownMigrateCmt {
continue
}
if !hasPassedDownMigrateCmt {
hasPassedDownMigrateCmt = true
continue
}
isComment := strings.HasPrefix(line, commentSyntax)
if isComment {
continue
}
statement += line
}
}
tx, err := db.Begin()
if err != nil {
log.Fatalf("Error beginning transaction: %v\n", err)
}
_, err = runMigration(tx, statement)
if err != nil {
log.Printf("Error executing migration: %v\n", err)
err = tx.Rollback()
if err != nil {
log.Printf("Error rolling-back transaction: %v\n", err)
}
return
}
switch action {
case "up":
err = onUpMigrate(&m, tx)
case "down":
err = onDownMigrate(&m, tx)
}
if err != nil {
return
}
err = tx.Commit()
if err != nil {
log.Fatalf("Error committing transaction: %v\n", err)
return
}
log.Printf("OK %d_%s.sql\n", m.Timestamp, m.Name)
}
}
var DB_DRIVERS ValidData = []string{"mysql", "postgres", "sqlite3"}
func ValidateDbDriver(inputDriver string) bool {
for _, name := range DB_DRIVERS {
if name == inputDriver {
return true
}
}
return false
}
func validateDbURL(inputDbURL string) (*url.URL, error) {
u, err := url.ParseRequestURI(inputDbURL)
if err != nil {
return nil, err
}
return u, nil
}
var ACTIONS ValidData = []string{"up", "down", "up-one", "down-one", "up-to", "down-to"}
func validateAction(inputAction string) bool {
for _, action := range ACTIONS {
if action == inputAction {
return true
}
}
return false
}