GoScrobble/internal/goscrobble/db.go

74 lines
1.4 KiB
Go
Raw Normal View History

2021-03-23 08:43:44 +00:00
package goscrobble
import (
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/golang-migrate/migrate"
"github.com/golang-migrate/migrate/database/mysql"
2021-03-24 09:28:05 +00:00
_ "github.com/golang-migrate/migrate/source/file"
2021-03-23 08:43:44 +00:00
)
2021-03-24 09:28:05 +00:00
var db *sql.DB
2021-03-23 08:43:44 +00:00
// InitDb - Boots up a DB connection
func InitDb() {
dbHost := os.Getenv("MYSQL_HOST")
dbUser := os.Getenv("MYSQL_USER")
dbPass := os.Getenv("MYSQL_PASS")
dbName := os.Getenv("MYSQL_DB")
2021-03-24 09:28:05 +00:00
dbConn, err := sql.Open("mysql", dbUser+":"+dbPass+"@tcp("+dbHost+")/"+dbName+"?multiStatements=true")
2021-03-23 08:43:44 +00:00
if err != nil {
panic(err)
}
dbConn.SetConnMaxLifetime(time.Minute * 3)
dbConn.SetMaxOpenConns(25)
dbConn.SetMaxIdleConns(10)
err = dbConn.Ping()
if err != nil {
panic(err)
}
2021-03-24 09:28:05 +00:00
db = dbConn
2021-03-23 08:43:44 +00:00
2021-03-24 09:28:05 +00:00
runMigrations()
2021-03-23 08:43:44 +00:00
}
// CloseDbConn - Closes DB connection
func CloseDbConn() {
2021-03-24 09:28:05 +00:00
db.Close()
2021-03-23 08:43:44 +00:00
}
2021-03-24 09:28:05 +00:00
func runMigrations() {
driver, err := mysql.WithInstance(db, &mysql.Config{})
2021-03-23 08:43:44 +00:00
if err != nil {
log.Fatalf("Unable to run migrations! %v", err)
}
2021-03-24 09:28:05 +00:00
m, err := migrate.NewWithDatabaseInstance(
"file://migrations",
2021-03-23 08:43:44 +00:00
"mysql",
driver,
)
2021-03-24 09:28:05 +00:00
if err != nil {
panic(fmt.Errorf("Error fetching DB Migrations %v", err))
}
2021-03-23 08:43:44 +00:00
2021-03-24 09:28:05 +00:00
err = m.Up()
if err != nil {
// Skip 'no change'. This is fine. Everything is fine.
if err.Error() == "no change" {
return
}
2021-03-23 08:43:44 +00:00
2021-03-24 09:28:05 +00:00
panic(fmt.Errorf("Error running DB Migrations %v", err))
}
2021-03-23 08:43:44 +00:00
}