Add item 2 db
This commit is contained in:
parent
e01312c15e
commit
d451f8f904
BIN
ZPRP_Rental
BIN
ZPRP_Rental
Binary file not shown.
10
db/main.go
10
db/main.go
|
@ -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
|
||||
}
|
|
@ -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
27
main.go
|
@ -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)
|
||||
}
|
Loading…
Reference in New Issue