-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
697 lines (562 loc) · 22 KB
/
main.go
File metadata and controls
697 lines (562 loc) · 22 KB
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
package main
import (
"bufio"
"context"
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"sort"
"strings"
"time"
"github.com/jackc/pgx/v4"
)
const (
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = "5432"
DEFAULT_USER = "postgres"
DEFAULT_PASSWORD = ""
DEFAULT_DATABASE = "postgres"
CONST_ENV_VAR_POSTGRESQL_USER = "POSTGRESQL_USER"
CONST_ENV_VAR_POSTGRESQL_HOST = "POSTGRESQL_HOST"
CONST_ENV_VAR_POSTGRESQL_PORT = "POSTGRESQL_PORT"
CONST_ENV_VAR_POSTGRESQL_PASSWORD = "POSTGRESQL_PASSWORD"
CONST_ENV_VAR_POSTGRESQL_PASSWORD_FILE = "POSTGRESQL_PASSWORD_FILE"
CONST_ENV_VAR_POSTGRESQL_DATABASE = "POSTGRESQL_DATABASE"
CONST_MIGRATIONS_FOLDER = "postgresql-migrations"
CONST_DATABASE_INFO_FILENAME = "postgresql-connection-string.txt"
CONST_POSTGRESQL_TABLE_NAME = "_go_simple_postgresql_migrate"
CONST_POSTGRESQL_TABLE_SCHEMA = "CREATE TABLE IF NOT EXISTS %s (id serial, created_at timestamp with time zone DEFAULT NOW(), filename text, UNIQUE(filename))"
CONST_TEMPLATE = "--\n-- %s\n--\n-- created: %s\n--\n-- FORWARD (UP) migration is below this line:\n--\n\n\n%s\n\n"
CONST_TEMPLATE_UNDO_MARKER = "\n--\n-- UNDO (DOWN) migration is below this line:\n-- (do not change this block!)\n--\n"
)
var postgreSQLConnection *pgx.Conn
// output help
func cmd_help() {
fmt.Printf("%v {init|up|down|create name..|destroy}\n", os.Args[0])
fmt.Println(`
init ask for database credentials and create migrations folder
create add a new migration file
create-here add a new migration file in current folder (no checks)
up do forward migrations until database is up to date
down do exactly ONE backwards migration
destroy do all backwards migrations at once
`)
fmt.Printf(`
Hint: Provide the PostgreSQL connection string via environment variables:
%s (default: "%s")
%s (default: "%s") or from file via %s
%s (default: "%s")
%s (default: "%s")
%s (default: "%s")
`,
CONST_ENV_VAR_POSTGRESQL_USER, DEFAULT_USER,
CONST_ENV_VAR_POSTGRESQL_PASSWORD, DEFAULT_PASSWORD, CONST_ENV_VAR_POSTGRESQL_PASSWORD_FILE,
CONST_ENV_VAR_POSTGRESQL_DATABASE, DEFAULT_DATABASE,
CONST_ENV_VAR_POSTGRESQL_HOST, DEFAULT_HOST,
CONST_ENV_VAR_POSTGRESQL_PORT, DEFAULT_PORT)
os.Exit(0)
}
// log error messages
func logError(message string, args ...interface{}) {
fmt.Fprintf(os.Stderr, message+"\n", args...)
}
// read user input from STDIN (allows default value)
func readFromStdIn(what string, defaultValue string) string {
reader := bufio.NewReader(os.Stdin)
if len(defaultValue) > 0 {
fmt.Printf("%s [%s]: ", what, defaultValue)
} else {
fmt.Printf("%s: ", what)
}
// read from STDIN
userInput, _ := reader.ReadString('\n')
userInput = strings.TrimSpace(userInput)
// check if user typed something in
if len(userInput) == 0 {
if len(defaultValue) > 0 {
return defaultValue
} else {
// need to try again
return readFromStdIn(what, defaultValue)
}
}
return userInput
}
// retrieve connection details from user
func getDatabaseConnectionStringFromUser() string {
fmt.Println()
fmt.Println("Please type in the PostgreSQL credentials you want to use:")
// ask user to type in connection details
host := readFromStdIn("host", DEFAULT_HOST)
port := readFromStdIn("port", DEFAULT_PORT)
user := readFromStdIn("user", DEFAULT_USER)
password := readFromStdIn("password", DEFAULT_PASSWORD)
database := readFromStdIn("database", DEFAULT_DATABASE)
// convert into PostgreSQL connection string
connectionString := fmt.Sprintf("postgresql://%s:%s@%s:%s/%s",
user, password, host, port, database)
// if successful, return connection string
return connectionString
}
// write string to file
func writeStringToFile(filePath string, strData string) {
file, err := os.Create(filePath)
if err != nil {
logError("Error: unable to create file: %s", filePath)
panic(err)
}
file.WriteString(strData)
file.Close()
}
// get connection string from environment
func getDatabaseConnectionStringFromEnvironment() string {
useConnectionStringFromEnvironment := false
user := DEFAULT_USER
if len(os.Getenv(CONST_ENV_VAR_POSTGRESQL_USER)) > 0 {
user = os.Getenv(CONST_ENV_VAR_POSTGRESQL_USER)
useConnectionStringFromEnvironment = true
}
password := DEFAULT_PASSWORD
if len(os.Getenv(CONST_ENV_VAR_POSTGRESQL_PASSWORD)) > 0 {
password = os.Getenv(CONST_ENV_VAR_POSTGRESQL_PASSWORD)
useConnectionStringFromEnvironment = true
}
if len(os.Getenv(CONST_ENV_VAR_POSTGRESQL_PASSWORD_FILE)) > 0 {
filePath := os.Getenv(CONST_ENV_VAR_POSTGRESQL_PASSWORD_FILE)
fileContent, err := ioutil.ReadFile(filePath)
if err != nil {
panic(err)
}
password = string(fileContent)
}
host := DEFAULT_HOST
if len(os.Getenv(CONST_ENV_VAR_POSTGRESQL_HOST)) > 0 {
host = os.Getenv(CONST_ENV_VAR_POSTGRESQL_HOST)
useConnectionStringFromEnvironment = true
}
port := DEFAULT_PORT
if len(os.Getenv(CONST_ENV_VAR_POSTGRESQL_PORT)) > 0 {
port = os.Getenv(CONST_ENV_VAR_POSTGRESQL_PORT)
useConnectionStringFromEnvironment = true
}
database := DEFAULT_DATABASE
if len(os.Getenv(CONST_ENV_VAR_POSTGRESQL_DATABASE)) > 0 {
database = os.Getenv(CONST_ENV_VAR_POSTGRESQL_DATABASE)
useConnectionStringFromEnvironment = true
}
if !useConnectionStringFromEnvironment {
return ""
}
return "postgresql://" + user + ":" + password + "@" + host + ":" + port + "/" + database
}
// initiate the versioning
func cmd_init() {
// check if migrations folder exists
_, err := os.Stat(CONST_MIGRATIONS_FOLDER)
// if not, then create it
if os.IsNotExist(err) {
os.Mkdir(CONST_MIGRATIONS_FOLDER, 0700)
fmt.Println("created migrations folder", CONST_MIGRATIONS_FOLDER)
}
filePathDatabaseConnectionString := path.Join(CONST_MIGRATIONS_FOLDER, CONST_DATABASE_INFO_FILENAME)
// check if database info has already been stored as file
_, err = os.Stat(filePathDatabaseConnectionString)
if !os.IsNotExist(err) {
logError("Error: PostgreSQL connection information already stored in %s",
filePathDatabaseConnectionString)
logError("Hint: Remove the file if you want to continue")
os.Exit(1)
}
// get connection info from environment variable
connectionString := getDatabaseConnectionStringFromEnvironment()
storeConnectionStringAsFile := false
// ask user for connection info
if len(connectionString) == 0 {
connectionString = getDatabaseConnectionStringFromUser()
storeConnectionStringAsFile = true
}
// attempt DB connection
connectToPostgreSQL(connectionString)
// store connection string in file
if storeConnectionStringAsFile {
writeStringToFile(filePathDatabaseConnectionString, connectionString)
}
// establish database connection
connectToStoredDatabaseConnection()
// create initial tables
_, err = postgreSQLConnection.Exec(
context.Background(),
fmt.Sprintf(CONST_POSTGRESQL_TABLE_SCHEMA, CONST_POSTGRESQL_TABLE_NAME))
if err != nil {
logError("Error: Failed to create initial table")
panic(err)
}
fmt.Println("Successfully set up migrations table at", CONST_POSTGRESQL_TABLE_NAME)
os.Exit(0)
}
// get connection string from file
func getDatabaseConnectionStringFromFile() string {
filePath := path.Join(CONST_MIGRATIONS_FOLDER, CONST_DATABASE_INFO_FILENAME)
connectionString, err := ioutil.ReadFile(filePath)
// file does not exist or cannot be read
if err != nil {
logError("Error: Could not read connection details from: %s", filePath)
logError("Hint: Maybe you should run 'init' first?")
panic(err)
}
return string(connectionString)
}
// attempt PostgreSQL connection and return db object
func connectToPostgreSQL(connectionString string) {
var err error
postgreSQLConnection, err = pgx.Connect(context.Background(), connectionString)
if err != nil {
logError("Error: Failed to create database connection with connection string %s", connectionString)
panic(err)
}
}
// retrieve database cursor
func connectToStoredDatabaseConnection() {
// get connection info from environment variable
connectionString := getDatabaseConnectionStringFromEnvironment()
// fallback: attempt to read from file
if len(connectionString) == 0 {
connectionString = getDatabaseConnectionStringFromFile()
}
connectToPostgreSQL(connectionString)
}
// create new migration file
func cmd_create(fileName string) {
// check if DB config file already exists
filePath := path.Join(CONST_MIGRATIONS_FOLDER, CONST_DATABASE_INFO_FILENAME)
_, err := os.Stat(filePath)
if os.IsNotExist(err) {
logError("Error: Database configuration file not found: %s", filePath)
logError("Hint: Did you run the 'init' command? Are you in the wrong folder?")
os.Exit(1)
}
// sanitize filename
reFileName := regexp.MustCompile("[^a-zA-Z0-9-_]")
sanitizedFileName := string(reFileName.ReplaceAll([]byte(strings.TrimSpace(fileName)), []byte("")))
reTimestamp := regexp.MustCompile("[^0-9]")
timestamp := time.Now().UTC()
timestampForFileName := timestamp.Format(time.RFC3339)
timestampForFileName = string(reTimestamp.ReplaceAll([]byte(timestampForFileName), []byte("")))
migrationFileName := timestampForFileName + "-" + sanitizedFileName + ".sql"
// check if file already exists
filePath = path.Join(CONST_MIGRATIONS_FOLDER, migrationFileName)
_, err = os.Stat(filePath)
if !os.IsNotExist(err) {
logError("Error: migration file does already exist: %s", filePath)
os.Exit(1)
}
// write template to file
writeStringToFile(filePath, fmt.Sprintf(CONST_TEMPLATE,
sanitizedFileName,
timestamp.Format(time.RFC850),
CONST_TEMPLATE_UNDO_MARKER))
fmt.Println("created", filePath)
os.Exit(0)
}
// create new migration file right here in this folder
func cmd_create_here(fileName string) {
// sanitize filename
reFileName := regexp.MustCompile("[^a-zA-Z0-9-_]")
sanitizedFileName := string(reFileName.ReplaceAll([]byte(strings.TrimSpace(fileName)), []byte("")))
reTimestamp := regexp.MustCompile("[^0-9]")
timestamp := time.Now().UTC()
timestampForFileName := timestamp.Format(time.RFC3339)
timestampForFileName = string(reTimestamp.ReplaceAll([]byte(timestampForFileName), []byte("")))
migrationFileName := timestampForFileName + "-" + sanitizedFileName + ".sql"
// check if file already exists
workDir, _ := os.Getwd()
filePath := path.Join(workDir, migrationFileName)
_, err := os.Stat(filePath)
if !os.IsNotExist(err) {
logError("Error: migration file does already exist: %s", filePath)
os.Exit(1)
}
// write template to file
writeStringToFile(filePath, fmt.Sprintf(CONST_TEMPLATE,
sanitizedFileName,
timestamp.Format(time.RFC850),
CONST_TEMPLATE_UNDO_MARKER))
fmt.Println("created", filePath)
os.Exit(0)
}
// fetch migrations from database
func getMigrationsFromDatabase() []string {
connectToStoredDatabaseConnection()
rows, err := postgreSQLConnection.Query(context.Background(),
fmt.Sprintf("SELECT filename FROM %s ORDER BY id ASC", CONST_POSTGRESQL_TABLE_NAME))
if err != nil {
logError("Error: could not read migrations from database table %s", CONST_POSTGRESQL_TABLE_NAME)
panic(err)
}
var filename string
var migrationsInDatabase []string
for rows.Next() {
err := rows.Scan(&filename)
if err != nil {
logError("Error: could not read migrations from database table %s: unable to scan row into filename", CONST_POSTGRESQL_TABLE_NAME)
panic(err)
}
migrationsInDatabase = append(migrationsInDatabase, filename)
}
err = rows.Err()
if err != nil {
logError("Error: could not read migrations from database table %s: row error", CONST_POSTGRESQL_TABLE_NAME)
panic(err)
}
return migrationsInDatabase
}
// fetch migrations from filesystem
func getMigrationsFromFileSystem() []string {
files, err := ioutil.ReadDir(CONST_MIGRATIONS_FOLDER)
if err != nil {
panic(err)
}
reMigrationFile := regexp.MustCompile("^[0-9]{14}-[a-zA-Z0-9_-]+.sql$")
var migrationsInFileSystem []string
for _, file := range files {
if reMigrationFile.MatchString(file.Name()) {
migrationsInFileSystem = append(migrationsInFileSystem, file.Name())
}
}
sort.Strings(migrationsInFileSystem)
return migrationsInFileSystem
}
// read migration from file
func readMigrationFromFile(fileName string) (string, string) {
filePath := path.Join(CONST_MIGRATIONS_FOLDER, fileName)
fileContentBytes, err := ioutil.ReadFile(filePath)
if err != nil {
logError("Error: Could not read file %s", filePath)
panic(err)
}
fileContent := string(fileContentBytes)
// check if separator exists in in file
if !strings.Contains(fileContent, CONST_TEMPLATE_UNDO_MARKER) {
logError("Error: Could not find the separator in file %s", filePath)
logError("Hint: Make sure this string splits up the up/down migration in the file:")
logError(CONST_TEMPLATE_UNDO_MARKER)
os.Exit(1)
}
// split file content into up/down migration
arrParts := strings.Split(fileContent, CONST_TEMPLATE_UNDO_MARKER)
// check if array has sane length
if len(arrParts) != 2 {
logError("Error: Found separator in file %s, but after splitting there is an array with %d elements instead of 2 as we expected.",
filePath, len(arrParts))
os.Exit(2)
}
sqlMigrationForward := cleanUpSQLString(arrParts[0])
if len(sqlMigrationForward) == 0 {
logError("Error: Forward (UP) migration is empty in file %s", filePath)
os.Exit(3)
}
sqlMigrationBackward := cleanUpSQLString(arrParts[1])
if len(sqlMigrationBackward) == 0 {
logError("Error: Backward (DOWN) migration is empty in file %s", filePath)
os.Exit(3)
}
return sqlMigrationForward, sqlMigrationBackward
}
// clean up SQL string read from migration file
func cleanUpSQLString(sqlString string) string {
// remove SQL comments
reSQLComments := regexp.MustCompile("(?m)^--[^\n]*$")
sqlString = string(reSQLComments.ReplaceAll([]byte(sqlString), []byte("")))
// remove whitespace
sqlString = strings.TrimSpace(sqlString)
return sqlString
}
// check consistency of migrations in database & local filesystem
func checkConsistencyOfDatabaseAndLocalFileSystem() ([]string, []string) {
// read migrations files from local folder
migrationsInFileSystem := getMigrationsFromFileSystem()
// check if we have migrations at all
if len(migrationsInFileSystem) == 0 {
logError("Error: No migration files found in local folder %s", CONST_MIGRATIONS_FOLDER)
logError("Hint: Maybe you need to run 'create' first?")
os.Exit(1)
}
// check if local migration files are well-formed
for _, fileNameFromFileSystem := range migrationsInFileSystem {
_, _ = readMigrationFromFile(fileNameFromFileSystem)
}
// read migrations from database
migrationsInDatabase := getMigrationsFromDatabase()
// check if # of migrations makes sense
if len(migrationsInDatabase) > len(migrationsInFileSystem) {
logError("Error: Missing local migration files. There are more migrations stored in the database (%d) than in local folder %s (%d)",
len(migrationsInDatabase), CONST_MIGRATIONS_FOLDER, len(migrationsInFileSystem))
os.Exit(1)
}
// check if migrations listed in database also exist in file system
for index, filenameFromDatabase := range migrationsInDatabase {
if filenameFromDatabase != migrationsInFileSystem[index] {
logError("Error: Migration stored in database at position #%d (%s) does not match local migration file %s",
index, filenameFromDatabase, migrationsInFileSystem[index])
os.Exit(2)
}
}
return migrationsInFileSystem, migrationsInDatabase
}
// migrate towards latest version of db
func cmd_up() {
// perform consistency checks
migrationsInFileSystem, migrationsInDatabase := checkConsistencyOfDatabaseAndLocalFileSystem()
// is there anything to do?
if len(migrationsInDatabase) == len(migrationsInFileSystem) {
fmt.Printf("Database already up to date, with %d migrations applied.\nMost recent migration is %s\n",
len(migrationsInDatabase), migrationsInDatabase[len(migrationsInDatabase)-1])
os.Exit(0)
}
// calculate delta
delta := migrationsInFileSystem[len(migrationsInDatabase):]
// fmt.Println("delta", delta)
for _, fileName := range delta {
// get sql for forward migration
sqlMigrationForward, _ := readMigrationFromFile(fileName)
// perform migration
insertedId := migrateForward(fileName, sqlMigrationForward)
fmt.Printf("forward migration: %s (database id: %d)\n", fileName, insertedId)
}
}
// migrate forward
func migrateForward(fileName string, sqlMigrationForward string) int {
tx, err := postgreSQLConnection.Begin(context.Background())
if err != nil {
logError("Error: Failed to start forward transaction")
logError("Error while processing file: %s", fileName)
panic(err)
}
defer tx.Rollback(context.Background())
// execute sql code of migration
_, err = tx.Exec(context.Background(), sqlMigrationForward)
if err != nil {
logError("Error: Forward transaction failed")
logError("Error while processing file: %s", fileName)
logError(sqlMigrationForward)
panic(err)
}
// store migration in table
var insertedId int
err = tx.QueryRow(context.Background(),
fmt.Sprintf("INSERT INTO %s (filename) VALUES ($1) RETURNING id", CONST_POSTGRESQL_TABLE_NAME),
fileName).Scan(&insertedId)
if err != nil {
logError("Error: Failed to store forward migration info in %s", CONST_POSTGRESQL_TABLE_NAME)
logError("Error while processing file: %s", fileName)
panic(err)
}
err = tx.Commit(context.Background())
if err != nil {
logError("Error: Failed to commit forward transaction")
logError("Error while processing file: %s", fileName)
panic(err)
}
return insertedId
}
// migrate backwards
func migrateBackward(fileName string, sqlMigrationBackward string) {
tx, err := postgreSQLConnection.Begin(context.Background())
if err != nil {
logError("Error: Failed to start backward transaction")
logError("Error while processing file: %s", fileName)
panic(err)
}
defer tx.Rollback(context.Background())
// check that most recent transaction is the one we are trying to undo
var mostRecentMigrationFileName string
var mostRecentMigrationId int
err = tx.QueryRow(context.Background(),
fmt.Sprintf(
"SELECT id, filename FROM %s ORDER BY created_at DESC LIMIT 1",
CONST_POSTGRESQL_TABLE_NAME)).Scan(
&mostRecentMigrationId, &mostRecentMigrationFileName)
if err != nil {
logError("Error: Cannot fetch most recent migration")
logError("Error while processing file: %s", fileName)
panic(err)
}
// execute sql code of migration
_, err = tx.Exec(context.Background(), sqlMigrationBackward)
if err != nil {
logError("Error: background migration failed")
logError("Error while processing file: %s", fileName)
logError(sqlMigrationBackward)
panic(err)
}
// store migration in table
_, err = tx.Exec(context.Background(),
fmt.Sprintf("DELETE FROM %s WHERE id = $1", CONST_POSTGRESQL_TABLE_NAME),
mostRecentMigrationId)
if err != nil {
logError("Error: Failed to remove backward migration #%d from database table %s",
mostRecentMigrationId, CONST_POSTGRESQL_TABLE_NAME)
logError("Error while processing file: %s", fileName)
panic(err)
}
err = tx.Commit(context.Background())
if err != nil {
logError("Error: Failed to commit backward transaction")
logError("Error while processing file: %s", fileName)
panic(err)
}
}
// migrate one step backwards
func cmd_down() {
// perform consistency checks
_, migrationsInDatabase := checkConsistencyOfDatabaseAndLocalFileSystem()
// is there anything to do?
if len(migrationsInDatabase) == 0 {
fmt.Println("There are no further migrations that can be reverted.")
os.Exit(0)
}
// get filename of last migration from array
mostRecentMigrationFileName := migrationsInDatabase[len(migrationsInDatabase)-1]
// get the sql query
_, sqlMigrationBackward := readMigrationFromFile(mostRecentMigrationFileName)
// perform backwards migration with database transaction
migrateBackward(mostRecentMigrationFileName, sqlMigrationBackward)
fmt.Println("undo:", mostRecentMigrationFileName)
}
// migrate all steps backwards
func cmd_destroy() {
for {
cmd_down()
}
}
func main() {
if len(os.Args) < 2 {
cmd_help()
}
switch os.Args[1] {
case "init":
if len(os.Args) == 2 {
cmd_init()
}
case "create":
cmd_create(strings.Join(os.Args[2:], "-"))
case "create-here":
cmd_create_here(strings.Join(os.Args[2:], "-"))
case "up":
if len(os.Args) == 2 {
cmd_up()
}
case "down":
if len(os.Args) == 2 {
cmd_down()
}
case "destroy":
if len(os.Args) == 2 {
cmd_destroy()
}
default:
cmd_help()
}
}