forked from asynkron/CallMeLater
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg_storage.go
118 lines (98 loc) · 2.14 KB
/
pg_storage.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
114
115
116
117
118
package main
import (
"database/sql"
"database/sql/driver"
"encoding/json"
_ "github.com/lib/pq"
"github.com/rs/zerolog/log"
"time"
)
type PgStorage struct {
db *sql.DB
}
type PgRow struct {
RequestId string
Timestamp time.Time
Data requestData
}
func newPgStorage(connectionString string) *PgStorage {
log.
Info().
Str("connectionString", connectionString).
Msg("Connecting to PostgreSQL")
db, err := sql.Open("postgres", connectionString)
if err != nil {
log.
Err(err).
Msg("Failed to connect to Postgres")
panic(err)
}
log.
Info().
Str("connectionString", connectionString).
Msg("Connected to PostgreSQL")
return &PgStorage{db: db}
}
func (p *PgStorage) Get() ([]*requestData, error) {
//gets the top 1000 requests
rows, err := p.db.Query(`SELECT * FROM "Requests" ORDER BY "Timestamp" DESC LIMIT 100`)
if err != nil {
log.
Err(err).
Msg("Failed to get requests")
return nil, err
}
var r []*requestData
//loop over rows and add to slice
for rows.Next() {
pgRow := &PgRow{}
err := rows.Scan(&pgRow.RequestId, &pgRow.Timestamp, &pgRow.Data)
if err != nil {
log.
Err(err).
Msg("Failed to scan row")
return nil, err
}
r = append(r, &pgRow.Data)
}
return r, nil
}
// Make the Attrs struct implement the driver.Valuer interface. This method
// simply returns the JSON-encoded representation of the struct.
func (a *requestData) Value() (driver.Value, error) {
return json.Marshal(a)
}
func (p *requestData) Scan(src interface{}) error {
source, ok := src.([]byte)
if !ok {
return nil
}
err := json.Unmarshal(source, p)
if err != nil {
return err
}
return nil
}
func (p *PgStorage) Set(data *requestData) error {
var _, err = p.db.Exec(
`INSERT INTO "Requests" VALUES ($1, $2, $3)`,
data.RequestId,
data.When,
data,
)
log.Info().
Str("id", data.RequestId).
Str("Url", data.RequestUrl).
Msg("Inserted new request")
return err
}
func (p *PgStorage) Delete(requestId string) error {
var _, err = p.db.Exec(
`DELETE FROM "Requests" WHERE "RequestId" = $1`,
requestId,
)
log.Info().
Str("requestId", requestId).
Msg("Deleted request")
return err
}