Skip to content

Commit

Permalink
Added migrations support
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashish Bhat committed Jul 26, 2019
1 parent f85afe6 commit 51d4490
Show file tree
Hide file tree
Showing 3 changed files with 136 additions and 1 deletion.
41 changes: 41 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@ package microapp

import (
"context"
"database/sql"
"net/http"

"time"

migrate "github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/mysql"
"github.com/golang-migrate/migrate/v4/source/file"
"github.com/gorilla/mux"
"github.com/islax/microapp/config"
"github.com/islax/microapp/event"
Expand Down Expand Up @@ -78,6 +82,43 @@ func (app *App) Logger(module string) *log.Entry {
})
}

// MigrateDB Looks for migrations directory and runs the migrations scripts in that directory
func (app *App) MigrateDB(connectionString string) {
logger := app.log

logger.Info("============ DB Migration Begin ============")
fsrc, err := (&file.File{}).Open("file://migrations")
if err != nil {
logger.Info("No migrations directory found. Skipping migrations. Error: ", err)
logger.Info("============ DB Migration End ============")
return
}
migrateDB, err := sql.Open("mysql", connectionString)
if err != nil {
logger.Fatal("Unable to open DB connection for migration: ", err)
}
migrateDBDriver, err := mysql.WithInstance(migrateDB, &mysql.Config{})
if err != nil {
logger.Error("Unable to prepare DB instance for migration: ", err)
}
m, err := migrate.NewWithInstance("file", fsrc, "mysql", migrateDBDriver)
if err != nil {
logger.Error("Unable to initialize DB instance for migration: ", err)
}
err = m.Up()
if err != nil {
if err.Error() == "no change" {
logger.Info("DB already in latest state.")
} else {
logger.Error("Failed to migrate DB: ", err)
// panic(err)
}
} else {
logger.Info("Successfully upgraded DB")
}
logger.Info("============ DB Migration End ============")
}

// Stop http server
func (app *App) Stop() {
wait, _ := time.ParseDuration("2m")
Expand Down
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ go 1.12

require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-sql-driver/mysql v1.4.1
github.com/golang-migrate/migrate/v4 v4.5.0
github.com/gorilla/mux v1.7.1
github.com/jinzhu/gorm v1.9.8
github.com/kr/pretty v0.1.0 // indirect
github.com/satori/go.uuid v1.2.0
github.com/sirupsen/logrus v1.4.1
github.com/spf13/viper v1.3.2
Expand Down
Loading

0 comments on commit 51d4490

Please sign in to comment.