-
Notifications
You must be signed in to change notification settings - Fork 0
/
product.go
84 lines (72 loc) · 1.78 KB
/
product.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
82
83
84
package db
import (
"database/sql"
"github.com/jefersonalmeida/go-hexagonal/application"
_ "github.com/mattn/go-sqlite3"
)
type ProductDb struct {
db *sql.DB
}
func NewProductDb(db *sql.DB) *ProductDb {
return &ProductDb{db: db}
}
func (p *ProductDb) Get(id string) (application.ProductInterface, error) {
var product application.Product
stmt, err := p.db.Prepare("select id, name, price, status from products where id=?")
if err != nil {
return nil, err
}
err = stmt.QueryRow(id).Scan(&product.ID, &product.Name, &product.Price, &product.Status)
if err != nil {
return nil, err
}
return &product, nil
}
func (p *ProductDb) Save(product application.ProductInterface) (application.ProductInterface, error) {
var rows int
p.db.QueryRow("select id from products where id=?", product.GetID()).Scan(&rows)
if rows == 0 {
_, err := p.create(product)
if err != nil {
return nil, err
}
} else {
_, err := p.update(product)
if err != nil {
return nil, err
}
}
return product, nil
}
func (p *ProductDb) create(product application.ProductInterface) (application.ProductInterface, error) {
stmt, err := p.db.Prepare(`insert into products(id, name, price, status) values(?,?,?,?)`)
if err != nil {
return nil, err
}
_, err = stmt.Exec(
product.GetID(),
product.GetName(),
product.GetPrice(),
product.GetStatus(),
)
if err != nil {
return nil, err
}
err = stmt.Close()
if err != nil {
return nil, err
}
return product, nil
}
func (p *ProductDb) update(product application.ProductInterface) (application.ProductInterface, error) {
_, err := p.db.Exec(`update products set name=?, price=?, status=? where id=?`,
product.GetName(),
product.GetPrice(),
product.GetStatus(),
product.GetID(),
)
if err != nil {
return nil, err
}
return product, nil
}