/
store_sql_repository.go
91 lines (75 loc) · 1.85 KB
/
store_sql_repository.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
package sql
import (
"context"
"database/sql"
"fmt"
"github.com/aasumitro/goms/internal/store/domain/contract"
"github.com/aasumitro/goms/internal/store/domain/entity"
)
type storeSQLRepository struct {
db *sql.DB
}
func (r storeSQLRepository) Select(ctx context.Context, args ...string) (items []*entity.Store, err error) {
query := "SELECT * FROM stores"
if len(args) > 0 {
for _, arg := range args {
query += fmt.Sprintf(" %s", arg)
}
}
rows, err := r.db.QueryContext(ctx, query)
if err != nil {
return nil, err
}
defer func(rows *sql.Rows) { _ = rows.Close() }(rows)
for rows.Next() {
var store entity.Store
if err := rows.Scan(&store.ID, &store.Name); err != nil {
return nil, err
}
items = append(items, &store)
}
return items, nil
}
func (r storeSQLRepository) Insert(ctx context.Context, args ...*entity.Store) error {
tx, err := r.db.Begin()
if err != nil {
return err
}
query := "INSERT INTO stores (name) VALUES"
if len(args) > 0 {
for i, arg := range args {
query += fmt.Sprintf(" ('%s')", arg.Name)
if i != (len(args) - 1) {
query += ","
}
}
}
if _, err := tx.ExecContext(ctx, query); err != nil {
_ = tx.Rollback()
return err
}
if err := tx.Commit(); err != nil {
return err
}
return nil
}
func (r storeSQLRepository) Update(ctx context.Context, arg *entity.Store) error {
var store entity.Store
query := "UPDATE stores SET name = ? WHERE id = ? RETURNING *"
if err := r.db.QueryRowContext(
ctx, query, arg.Name, arg.ID,
).Scan(
&store.ID, &store.Name,
); err != nil {
return err
}
return nil
}
func (r storeSQLRepository) Delete(ctx context.Context, arg *entity.Store) error {
query := "DELETE FROM stores WHERE id = ?"
_, err := r.db.ExecContext(ctx, query, arg.ID)
return err
}
func NewStoreSQLRepository(db *sql.DB) contract.IStoreRepository {
return storeSQLRepository{db}
}