forked from PepperSalt42/api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
41 lines (36 loc) · 1.05 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main
import (
"fmt"
"os"
log "github.com/Sirupsen/logrus"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
var db gorm.DB
// InitDB opens the database with the informations from the env.
// Automigrate all the tables.
func InitDB() {
var err error
user := os.Getenv("MYSQL_USER")
password := os.Getenv("MYSQL_PASSWORD")
dbname := os.Getenv("MYSQL_DATABASE")
sqlConnection := fmt.Sprintf("%s:%s@tcp(db:3306)/%s?charset=utf8&parseTime=True&loc=Local", user, password, dbname)
db, err = gorm.Open("mysql", sqlConnection)
if err != nil {
log.WithFields(log.Fields{
"user": user,
"password": password,
"dbname": dbname,
"err": err,
}).Fatal("Can't open mysql database")
log.Fatal(err)
}
db.AutoMigrate(&Answer{}, &AnswerEntry{}, &Image{}, &Message{}, &Question{}, &User{})
}
// InsertOrUpdateDB inserts or updates the values in the database.
func InsertOrUpdateDB(query, out interface{}) error {
if db.Where(query).First(out).RecordNotFound() {
return db.Create(out).Error
}
return db.Save(out).Error
}