Add item 2 db

This commit is contained in:
Kameleoonik 2018-12-20 11:57:54 +01:00
parent e01312c15e
commit d451f8f904
4 changed files with 38 additions and 9 deletions

Binary file not shown.

View File

@ -7,7 +7,7 @@ import (
pg "github.com/go-pg/pg"
)
func Connect() {
func Connect() *pg.DB {
opts := &pg.Options{
User: "postgres",
Password: "",
@ -21,11 +21,5 @@ func Connect() {
}
log.Printf("Connected :)")
CreateProductItemsTable(db)
closeErr := db.Close()
if closeErr != nil {
log.Printf("Error with close connection", closeErr)
os.Exit(100)
}
log.Printf("Connection closed")
return
return db
}

View File

@ -25,6 +25,16 @@ type ProductItem struct {
IsActive bool `sql:"is_active"`
}
func (pi *ProductItem) Save(db *pg.DB) error {
insertErr := db.Insert(pi)
if insertErr != nil {
log.Printf("Blad z dodaniem do DB, Reseon: %v\n", insertErr)
return insertErr
}
log.Printf("Produkt %s dodany.\n", pi.Name)
return nil
}
func CreateProductItemsTable(db *pg.DB) error {
opts := &orm.CreateTableOptions{
IfNotExists: true,

27
main.go
View File

@ -2,9 +2,34 @@ package main
import (
"log"
"time"
db "./db"
pg "github.com/go-pg/pg"
)
func main() {
log.Printf("Yelo!\n")
db.Connect()
pg_db := db.Connect()
SaveProduct(pg_db)
}
func SaveProduct(dbRef *pg.DB) {
newPI := &db.ProductItem {
Name: "Product 1",
Desc: "Product 1 desc",
Image: "This is image path",
Price: 4.5,
Features: struct {
Name string
Desc string
Imp int
}{
Name: "F1",
Desc: "F1 Desc",
Imp: 3,
},
CreateAt: time.Now(),
UpdateAt: time.Now(),
IsActive: true,
}
newPI.Save(dbRef)
}