GoScrobble/internal/goscrobble/db.go

89 lines
1.7 KiB
Go
Raw Normal View History

2021-03-23 08:43:44 +00:00
package goscrobble
import (
"database/sql"
2021-03-25 23:21:28 +00:00
"errors"
2021-03-23 08:43:44 +00:00
"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")
dbConn, err := sql.Open("mysql", dbUser+":"+dbPass+"@tcp("+dbHost+")/"+dbName+"?multiStatements=true&parseTime=true&loc=Etc%2FUTC")
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() {
fmt.Println("Checking database migrations")
2021-03-24 09:28:05 +00:00
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" {
fmt.Println("Database already up to date")
2021-03-24 09:28:05 +00:00
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))
}
fmt.Println("Database migrations complete")
2021-03-23 08:43:44 +00:00
}
2021-03-25 23:21:28 +00:00
func getDbCount(query string, args ...interface{}) (int, error) {
var result int
err := db.QueryRow(query, args...).Scan(&result)
if err != nil {
return 0, errors.New("Error fetching data")
}
return result, nil
}