-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.go
81 lines (71 loc) · 1.92 KB
/
model.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"database/sql"
"errors"
"fmt"
)
type product struct {
ID int `json:"id"`
Name string `json:"name"`
Quantity int `json:"quantity"`
Price float64 `json:"price"`
}
func getProducts(db *sql.DB) ([]product, error) {
query := "SELECT id, name, quantity, price FROM products"
rows, err := db.Query(query)
if err != nil {
return nil, err
}
products := []product{}
for rows.Next() {
var p product
err := rows.Scan(&p.ID, &p.Name, &p.Quantity, &p.Price)
if err != nil {
return nil, err
}
products = append(products, p)
}
return products, nil
}
func (p *product) getProduct(db *sql.DB) error {
query := fmt.Sprintf("SELECT name, quantity, price FROM products where id=%v", p.ID)
row := db.QueryRow(query)
// using a pointer must not return
err := row.Scan(&p.Name, &p.Quantity, &p.Price)
checkError(err)
return nil
}
func (p *product) createProduct(db *sql.DB) error {
// Database problem with price only 999.xx TODO: Database fix or error catching
query := fmt.Sprintf("INSERT INTO products(name, quantity, price) values('%v', %v, %v)", p.Name, p.Quantity, p.Price)
result, err := db.Exec(query)
checkError(err)
id, err := result.LastInsertId()
checkError(err)
p.ID = int(id)
return nil
}
func (p *product) updateProduct(db *sql.DB) error {
query := fmt.Sprintf("UPDATE products set name='%v', quantity=%v, price=%v WHERE id=%v", p.Name, p.Quantity, p.Price, p.ID)
result, err := db.Exec(query)
if err != nil {
fmt.Println(err)
}
rowsAffected, err := result.RowsAffected()
if rowsAffected == 0 {
return errors.New("no such row exists")
}
return err
}
func (p *product) deleteProduct(db *sql.DB) error {
query := fmt.Sprintf("DELETE FROM products WHERE id=%v", p.ID)
result, err := db.Exec(query)
if err != nil {
fmt.Println(err)
}
rowsAffected, err := result.RowsAffected()
if rowsAffected == 0 {
return errors.New("no such row deleted")
}
return err
}