ExpiryDatesManager/server/model/base.go
2018-12-20 20:50:01 +01:00

43 lines
1.2 KiB
Go

package model
import (
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/jinzhu/gorm"
"os"
"fmt"
"github.com/joho/godotenv"
)
var db *gorm.DB
func init() {
error := godotenv.Load()
if error != nil {
fmt.Println(error)
}
username := os.Getenv("db_name")
password := os.Getenv("db_pass")
connectionstring := fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/expirydates?charset=utf8&parseTime=True&loc=Local", username, password)
conn, err := gorm.Open("mysql", connectionstring)
if err != nil {
fmt.Println(err)
}
db = conn
db.AutoMigrate(&Company{}, &Product{}, &ProductExpiryPosition{}, &Report{}, &ReportPosition{})
db.Model(&Product{}).AddForeignKey("company_id", "companies(id)", "RESTRICT", "RESTRICT")
db.Model(&ProductExpiryPosition{}).AddForeignKey("product_id", "product_expiry_positions(id)", "RESTRICT", "RESTRICT")
db.Model(&Report{}).AddForeignKey("company_id", "companies(id)", "RESTRICT", "RESTRICT")
db.Model(&ReportPosition{}).AddForeignKey("report_id", "reports(id)", "RESTRICT", "RESTRICT")
db.Model(&ReportPosition{}).AddForeignKey("product_expiry_position_id", "product_expiry_positions(id)", "RESTRICT", "RESTRICT")
db.LogMode(true)
db = db.Set("gorm:auto_preload", true)
}
func GetDB() *gorm.DB {
return db
}