This repository has been archived by the owner on Mar 24, 2024. It is now read-only.
generated from yandex-praktikum/go-musthave-devops-tpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
181 lines (148 loc) · 4.77 KB
/
database.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package storage
import (
"context"
"errors"
"fmt"
"github.com/alkurbatov/metrics-collector/internal/entity"
"github.com/alkurbatov/metrics-collector/pkg/metrics"
"github.com/jackc/pgx/v5"
"github.com/rs/zerolog/log"
)
var _ Storage = DatabaseStorage{}
func rollback(ctx context.Context, tx pgx.Tx) {
if err := tx.Rollback(ctx); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
log.Ctx(ctx).Error().Err(err).Msg("DatabaseStorage - rollback - tx.Rollback")
}
}
// DatabaseStorage implements database metrics storage.
type DatabaseStorage struct {
pool DBConnPool
}
// NewDatabaseStorage creates new instance of DatabaseStorage.
func NewDatabaseStorage(pool DBConnPool) DatabaseStorage {
return DatabaseStorage{pool: pool}
}
// Push records metric data.
func (d DatabaseStorage) Push(ctx context.Context, key string, record Record) error {
conn, err := d.pool.Acquire(ctx)
if err != nil {
return fmt.Errorf("DatabaseStorage - Push - d.pool.Acquire: %w", err)
}
tx, err := conn.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted})
if err != nil {
conn.Release()
return fmt.Errorf("DatabaseStorage - Push - conn.BeginTx: %w", err)
}
defer conn.Release()
defer rollback(ctx, tx)
if _, err = tx.Exec(
ctx,
"INSERT INTO metrics(id, name, kind, value) values ($1, $2, $3, $4) ON CONFLICT (id) DO UPDATE SET value = $4",
key,
record.Name,
record.Value.Kind(),
record.Value.String(),
); err != nil {
return fmt.Errorf("DatabaseStorage - Push - tx.Exec: %w", err)
}
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("DatabaseStorage - Push - tx.Commit: %w", err)
}
return nil
}
// PushBatch records list of metrics data in single request to the database.
func (d DatabaseStorage) PushBatch(ctx context.Context, data map[string]Record) error {
// NB (alkurbatov): Since batch queries are run in an implicit transaction
// (unless explicit transaction control statements are executed)
// we don't need to handle transactions manually.
// See: https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY
batch := new(pgx.Batch)
for id, record := range data {
batch.Queue(
"INSERT INTO metrics(id, name, kind, value) values ($1, $2, $3, $4) ON CONFLICT (id) DO UPDATE SET value = $4",
id,
record.Name,
record.Value.Kind(),
record.Value.String(),
)
}
batchResp := d.pool.SendBatch(ctx, batch)
defer func() {
if err := batchResp.Close(); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("DatabaseStorage - PushBatch - batchResp.Close")
}
}()
for i := 0; i < len(data); i++ {
if _, err := batchResp.Exec(); err != nil {
return fmt.Errorf("DatabaseStorage - PushBatch - batchResp.Exec: %w", err)
}
}
return nil
}
// Get returns stored metrics record.
func (d DatabaseStorage) Get(ctx context.Context, key string) (Record, error) {
var (
name string
kind string
value float64
)
err := d.pool.
QueryRow(ctx, "SELECT name, kind, value FROM metrics WHERE id=$1", key).
Scan(&name, &kind, &value)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return Record{}, fmt.Errorf("DatabaseStorage - Get - d.pool.QueryRow: %w", entity.ErrMetricNotFound)
}
return Record{}, fmt.Errorf("DatabaseStorage - Get - d.pool.QueryRow: %w", err)
}
switch kind {
case metrics.KindCounter:
return Record{Name: name, Value: metrics.Counter(value)}, nil
case metrics.KindGauge:
return Record{Name: name, Value: metrics.Gauge(value)}, nil
default:
return Record{}, fmt.Errorf("DatabaseStorage - Get - kind: %w", entity.MetricNotImplementedError(kind))
}
}
// GetAll returns all stored metrics.
func (d DatabaseStorage) GetAll(ctx context.Context) ([]Record, error) {
rows, err := d.pool.Query(ctx, "SELECT name, kind, value FROM metrics")
if err != nil {
return nil, fmt.Errorf("DatabaseStorage - GetAll - d.pool.Query: %w", err)
}
defer rows.Close()
var (
name string
kind string
value float64
)
rv := make([]Record, 0)
_, err = pgx.ForEachRow(rows, []any{&name, &kind, &value}, func() error {
switch kind {
case metrics.KindCounter:
rv = append(rv, Record{Name: name, Value: metrics.Counter(value)})
return nil
case metrics.KindGauge:
rv = append(rv, Record{Name: name, Value: metrics.Gauge(value)})
return nil
default:
return entity.MetricNotImplementedError(kind)
}
})
if err != nil {
return nil, fmt.Errorf("DatabaseStorage - GetAll - pgx.ForEachRow: %w", err)
}
return rv, nil
}
// Ping verifies that connection to the database can be established.
func (d DatabaseStorage) Ping(ctx context.Context) error {
if err := d.pool.Ping(ctx); err != nil {
return fmt.Errorf("DatabaseSrorage - Ping - d.pool.Ping: %w", err)
}
return nil
}
// Close closes all open connection to the database.
func (d DatabaseStorage) Close(_ context.Context) error {
d.pool.Close()
return nil
}