-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql_product.go
113 lines (98 loc) · 2.26 KB
/
mysql_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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package mysql
import (
"context"
"database/sql"
"log"
"github.com/dihanto/golang-basic/17-database-mysql/entity"
)
type mysqlProductRepository struct {
Conn *sql.DB
}
func NewMysqlProductRepostitory(conn *sql.DB) entity.ProductRepository {
return &mysqlProductRepository{conn}
}
func (m *mysqlProductRepository) Insert(ctx context.Context, product *entity.Product) (err error) {
query := `INSERT products SET name=?, price=?`
stmt, err := m.Conn.PrepareContext(ctx, query)
if err != nil {
return
}
res, err := stmt.ExecContext(ctx, product.Name, product.Price)
if err != nil {
return
}
lastID, err := res.LastInsertId()
if err != nil {
return
}
product.ID = lastID
return
}
func (m *mysqlProductRepository) FindAll(ctx context.Context) (products []entity.Product, err error) {
query := `SELECT id, name, price FROM products`
rows, err := m.Conn.QueryContext(ctx, query)
if err != nil {
log.Println(err)
return
}
defer func() {
errRow := rows.Close()
if errRow != nil {
log.Println(errRow)
}
}()
for rows.Next() {
product := entity.Product{}
err = rows.Scan(
&product.ID,
&product.Name,
&product.Price,
)
if err != nil {
log.Println(err)
return
}
products = append(products, product)
}
return
}
func (m *mysqlProductRepository) Update(ctx context.Context, product *entity.Product) (err error) {
query := `UPDATE products SET name=?, price=? WHERE id=?`
stmt, err := m.Conn.PrepareContext(ctx, query)
if err != nil {
return
}
_, err = stmt.ExecContext(ctx, product.Name, product.Price, product.ID)
if err != nil {
return
}
// rowsAffected, err := result.RowsAffected()
// if err != nil {
// return
// }
// if rowsAffected != 1 {
// err = fmt.Errorf("weird behavior. rows affected : %d", rowsAffected)
// return
// }
return
}
func (m *mysqlProductRepository) Delete(ctx context.Context, id int) (err error) {
query := `Delete from products WHERE id=?`
stmt, err := m.Conn.PrepareContext(ctx, query)
if err != nil {
return
}
_, err = stmt.ExecContext(ctx, id)
if err != nil {
return
}
// rowsAffected, err := result.RowsAffected()
// if err != nil {
// return
// }
// if rowsAffected != 1 {
// err = fmt.Errorf("weird behavior. rows affected : %d", rowsAffected)
// return
// }
return
}