forked from thomaslanghorst/testify-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stocks.go
74 lines (55 loc) · 1.42 KB
/
stocks.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
package stocks
import (
"database/sql"
"fmt"
"time"
)
const (
dateFormat = "2006-01-02"
)
type PriceData struct {
Timestamp time.Time
Price float64
}
type PriceProvider interface {
Latest() (*PriceData, error)
List(date time.Time) ([]*PriceData, error)
}
type priceProvider struct {
db *sql.DB
}
func NewPriceProvider(db *sql.DB) PriceProvider {
return &priceProvider{
db: db,
}
}
func (p *priceProvider) Latest() (*PriceData, error) {
var priceData PriceData
err := p.db.QueryRow("SELECT * FROM stockprices ORDER BY timestamp DESC limit 1").Scan(&priceData.Timestamp, &priceData.Price)
if err != nil {
return &priceData, fmt.Errorf("unable to query table. Error %s", err.Error())
}
return &priceData, nil
}
func (p *priceProvider) List(date time.Time) ([]*PriceData, error) {
priceData := make([]*PriceData, 0)
var rows *sql.Rows
var err error
rows, err = p.db.Query("SELECT * FROM stockprices where timestamp::date = $1 ORDER BY timestamp DESC", date.Format(dateFormat))
if err != nil {
return priceData, fmt.Errorf("unable to prepare SELECT statement. Error %s", err.Error())
}
var timestamp time.Time
var price float64
for rows.Next() {
err = rows.Scan(×tamp, &price)
if err != nil {
return priceData, fmt.Errorf("unable to query table. Error %s", err.Error())
}
priceData = append(priceData, &PriceData{
Timestamp: timestamp,
Price: price,
})
}
return priceData, nil
}