połączenie z bazą danych

This commit is contained in:
Ewelina Wizła 2018-12-16 16:27:33 +01:00
parent 5bd873ae0b
commit f13947defa
8 changed files with 122 additions and 0 deletions

2
server/.env Normal file
View File

@ -0,0 +1,2 @@
db_name = Ewelina
db_pass = p455w0rd

17
server/main.go Normal file
View File

@ -0,0 +1,17 @@
package main
import (
"ExpiryDatesManager/server/model"
"fmt"
)
func main() {
fmt.Printf("hello, world\n")
defer model.GetDB().Close()
fmt.Println("udalo sie")
}

39
server/model/base.go Normal file
View File

@ -0,0 +1,39 @@
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", 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")
}
func GetDB() *gorm.DB {
return db
}

10
server/model/company.go Normal file
View File

@ -0,0 +1,10 @@
package model
import (
"github.com/jinzhu/gorm"
)
type Company struct {
gorm.Model
Name string
}

13
server/model/product.go Normal file
View File

@ -0,0 +1,13 @@
package model
import (
"github.com/jinzhu/gorm"
)
type Product struct {
gorm.Model
Name string
Company Company
CompanyID uint
Code string `gorm:"unique; unique_index"`
}

View File

@ -0,0 +1,15 @@
package model
import (
"time"
"github.com/jinzhu/gorm"
)
type ProductExpiryPosition struct {
gorm.Model
ExpiryDate time.Time
BatchNumber string
Product Product
ProductID uint
}

11
server/model/report.go Normal file
View File

@ -0,0 +1,11 @@
package model
import (
"github.com/jinzhu/gorm"
)
type Report struct {
gorm.Model
Company Company
CompanyID uint
}

View File

@ -0,0 +1,15 @@
package model
import (
"github.com/jinzhu/gorm"
)
type ReportPosition struct {
gorm.Model
PositionNumber int
Quantity int
ProductExpiryPosition ProductExpiryPosition
ProductExpiryPositionID uint
Report Report
ReportID uint
}