-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
stats.go
89 lines (78 loc) · 1.62 KB
/
stats.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
package graphql
import (
"context"
"fmt"
"time"
)
// Save upserts a stat.
func (s *Stat) Save(ctx context.Context) error {
if s.Key == "" {
return fmt.Errorf("Empty key not allowed")
}
s.When = time.Now()
if _, err := db.ExecContext(
ctx,
`INSERT INTO stats(key, value, inserted_at) VALUES ($1, $2, $3)`,
s.Key,
s.Value,
s.When,
); err != nil {
return err
}
return nil
}
// GetStats returns the limit of the most recently updated stats.
func GetStats(ctx context.Context, limit int) ([]*Stat, error) {
rows, err := db.QueryContext(
ctx,
`SELECT DISTINCT ON (key) key, value, inserted_at
FROM stats
ORDER by key, inserted_at DESC
LIMIT $1`,
limit)
if err != nil {
return nil, err
}
defer rows.Close()
var stats []*Stat
for rows.Next() {
stat := new(Stat)
if err := rows.Scan(&stat.Key, &stat.Value, &stat.When); err != nil {
return nil, err
}
stats = append(stats, stat)
}
if err = rows.Err(); err != nil {
return nil, err
}
return stats, nil
}
// GetStat returns the history of a stat
func GetStat(ctx context.Context, key string, limit int, offset int) ([]*Stat, error) {
rows, err := db.QueryContext(
ctx,
`SELECT key, value, inserted_at
FROM stats
WHERE key = $1
ORDER by inserted_at DESC
LIMIT $2 OFFSET $3`,
key,
limit,
offset)
if err != nil {
return nil, err
}
defer rows.Close()
var stats []*Stat
for rows.Next() {
stat := new(Stat)
if err := rows.Scan(&stat.Key, &stat.Value, &stat.When); err != nil {
return nil, err
}
stats = append(stats, stat)
}
if err = rows.Err(); err != nil {
return nil, err
}
return stats, nil
}