-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
92 lines (65 loc) · 1.3 KB
/
service.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
package coin
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
type UseCase interface {
GetAll()([]*Coin, error)
Get(ID int)(*Coin, error)
Store(c *Coin) error
}
type Service struct {
DB *sql.DB
}
func NewService (db *sql.DB) *Service {
return &Service{
DB:db,
}
}
func (s *Service) GetAll()([]*Coin, error) {
var result []*Coin
rows,err := s.DB.Query("SELECT id, name, value, risk from coin")
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var c Coin
err = rows.Scan(&c.Id, &c.Name, &c.Value, &c.Risk)
if err != nil {
return nil, err
}
result = append(result, &c)
}
return result, nil
}
func (s *Service) Get(ID int)(*Coin, error){
var c Coin
stmt, err := s.DB.Prepare("SELECT id, name, value, risk from coin where id = ?")
if err != nil {
return nil, err
}
defer stmt.Close()
err = stmt.QueryRow(ID).Scan(&c.Id, &c.Name, &c.Value, &c.Risk)
if err != nil {
return nil, err
}
return &c,nil
}
func (s *Service) Store(c *Coin)(error){
tx,err := s.DB.Begin()
if err != nil {
return err
}
stmt ,err := tx.Prepare("INSERT INTO coin (name, value, risk) VALUES (?,?,?)")
if err != nil {
return err
}
defer stmt.Close()
_,err = stmt.Exec(c.Name, c.Value, c.Risk)
if err != nil {
return err
}
tx.Commit()
return nil
}