2016-05-24 11:55:48 +02:00
|
|
|
package db
|
2016-01-05 00:32:53 +01:00
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2016-03-16 22:49:43 +01:00
|
|
|
|
|
|
|
"github.com/ansible-semaphore/semaphore/util"
|
2016-01-05 00:32:53 +01:00
|
|
|
_ "github.com/go-sql-driver/mysql" // imports mysql driver
|
|
|
|
"gopkg.in/gorp.v1"
|
|
|
|
)
|
|
|
|
|
|
|
|
var Mysql *gorp.DbMap
|
|
|
|
|
|
|
|
// Mysql database
|
2016-04-18 02:58:29 +02:00
|
|
|
func Connect() error {
|
2016-04-30 14:28:47 +02:00
|
|
|
db, err := connect()
|
2016-01-05 00:32:53 +01:00
|
|
|
if err != nil {
|
2016-04-18 02:58:29 +02:00
|
|
|
return err
|
2016-01-05 00:32:53 +01:00
|
|
|
}
|
|
|
|
|
2016-04-30 07:54:29 +02:00
|
|
|
if err := db.Ping(); err != nil {
|
2016-04-30 14:28:47 +02:00
|
|
|
if err := createDb(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
db, err = connect()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := db.Ping(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2016-01-05 00:32:53 +01:00
|
|
|
}
|
|
|
|
|
2016-04-30 14:28:47 +02:00
|
|
|
Mysql = &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{Engine: "InnoDB", Encoding: "UTF8"}}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func createDb() error {
|
|
|
|
cfg := util.Config.MySQL
|
|
|
|
url := cfg.Username + ":" + cfg.Password + "@tcp(" + cfg.Hostname + ")/?parseTime=true&interpolateParams=true"
|
|
|
|
|
|
|
|
db, err := sql.Open("mysql", url)
|
|
|
|
if err != nil {
|
2016-04-30 09:52:33 +02:00
|
|
|
return err
|
2016-04-30 07:54:29 +02:00
|
|
|
}
|
2016-04-18 02:58:29 +02:00
|
|
|
|
2016-04-30 14:28:47 +02:00
|
|
|
if _, err := db.Exec("create database if not exists " + cfg.DbName); err != nil {
|
2016-04-30 09:52:33 +02:00
|
|
|
return err
|
2016-04-30 07:54:29 +02:00
|
|
|
}
|
|
|
|
|
2016-04-18 02:58:29 +02:00
|
|
|
return nil
|
2016-01-05 00:32:53 +01:00
|
|
|
}
|
2016-04-30 14:28:47 +02:00
|
|
|
|
|
|
|
func connect() (*sql.DB, error) {
|
|
|
|
cfg := util.Config.MySQL
|
|
|
|
url := cfg.Username + ":" + cfg.Password + "@tcp(" + cfg.Hostname + ")/" + cfg.DbName + "?parseTime=true&interpolateParams=true"
|
|
|
|
|
|
|
|
return sql.Open("mysql", url)
|
|
|
|
}
|