2017-01-25 12:46:43 +00:00
|
|
|
package datastore
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
_ "github.com/go-sql-driver/mysql" // mysql driver
|
|
|
|
_ "github.com/lib/pq" // postgresql driver
|
2017-01-25 14:17:24 +00:00
|
|
|
"github.com/rubenv/sql-migrate"
|
|
|
|
"log"
|
|
|
|
"os"
|
2017-01-25 12:46:43 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// DB ...
|
|
|
|
var DB *sql.DB
|
|
|
|
|
|
|
|
// Init creates a database connection pool
|
|
|
|
func Init() *sql.DB {
|
|
|
|
driver := os.Getenv("ANA_DATABASE_DRIVER")
|
|
|
|
if driver == "" {
|
|
|
|
driver = "mysql"
|
|
|
|
}
|
|
|
|
|
|
|
|
DB = New(driver, getDSN(driver))
|
2017-01-25 14:17:24 +00:00
|
|
|
|
|
|
|
// run migrations
|
|
|
|
runMigrations(driver)
|
|
|
|
|
2017-01-25 12:46:43 +00:00
|
|
|
return DB
|
|
|
|
}
|
|
|
|
|
|
|
|
// New creates a new database pool
|
|
|
|
func New(driver string, config string) *sql.DB {
|
|
|
|
db, err := sql.Open(driver, config)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := db.Ping(); err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return db
|
|
|
|
}
|
|
|
|
|
|
|
|
func getDSN(driver string) string {
|
|
|
|
var dsn = fmt.Sprintf(
|
|
|
|
"%s:%s@%s/%s",
|
|
|
|
os.Getenv("ANA_DATABASE_USER"),
|
|
|
|
os.Getenv("ANA_DATABASE_PASSWORD"),
|
|
|
|
os.Getenv("ANA_DATABASE_HOST"),
|
|
|
|
os.Getenv("ANA_DATABASE_NAME"),
|
|
|
|
)
|
|
|
|
|
2017-01-25 14:17:24 +00:00
|
|
|
switch driver {
|
|
|
|
case "postgres":
|
2017-01-25 12:46:43 +00:00
|
|
|
dsn = "postgres://" + dsn
|
2017-01-25 14:17:24 +00:00
|
|
|
case "mysql":
|
|
|
|
dsn = dsn + "?parseTime=true"
|
2017-01-25 12:46:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return dsn
|
|
|
|
}
|
2017-01-25 14:17:24 +00:00
|
|
|
|
|
|
|
func runMigrations(driver string) {
|
|
|
|
migrations := migrate.FileMigrationSource{
|
|
|
|
Dir: "datastore/migrations",
|
|
|
|
}
|
|
|
|
|
|
|
|
migrate.SetTable("migrations")
|
|
|
|
n, err := migrate.Exec(DB, driver, migrations, migrate.Up)
|
2017-01-25 15:19:07 +00:00
|
|
|
|
2017-01-25 14:17:24 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal("Database migrations failed: ", err)
|
|
|
|
}
|
|
|
|
|
2017-01-25 15:19:07 +00:00
|
|
|
if n > 0 {
|
|
|
|
log.Printf("Applied %d database migrations!\n", n)
|
|
|
|
}
|
2017-01-25 14:17:24 +00:00
|
|
|
}
|