-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.go
376 lines (337 loc) · 9.16 KB
/
db.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package cove
import (
"database/sql"
"errors"
"fmt"
"iter"
"log/slog"
"os"
"strings"
"time"
)
type query interface {
Query(query string, args ...any) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
Exec(query string, args ...any) (sql.Result, error)
}
func exec(db query, qs ...string) error {
for _, q := range qs {
_, err := db.Exec(q)
if err != nil {
return fmt.Errorf("could not exec, %s, err, %w", q, err)
}
}
return nil
}
func getRange(db query, from string, to string, tbl string) (kv []KV[[]byte], err error) {
r, err := db.Query(fmt.Sprintf(`SELECT key, value FROM %s WHERE $1 <= key AND key <= $2`, tbl), from, to)
if err != nil {
return nil, fmt.Errorf("could not query in range, %w", err)
}
defer r.Close()
for r.Next() {
var k string
var v []byte
err := r.Scan(&k, &v)
if err != nil {
return nil, fmt.Errorf("could not scan in range, %w", err)
}
kv = append(kv, KV[[]byte]{K: k, V: v})
}
return kv, nil
}
func getKeys(db query, from string, to string, tbl string) (keys []string, err error) {
r, err := db.Query(fmt.Sprintf(`SELECT key FROM %s WHERE $1 <= key AND key <= $2`, tbl), from, to)
if err != nil {
return nil, fmt.Errorf("could not query in range, %w", err)
}
defer r.Close()
for r.Next() {
var k string
err := r.Scan(&k)
if err != nil {
return nil, fmt.Errorf("could not scan in range, %w", err)
}
keys = append(keys, k)
}
return keys, nil
}
func getValues(db query, from string, to string, tbl string) (vals [][]byte, err error) {
r, err := db.Query(fmt.Sprintf(`SELECT value FROM %s WHERE $1 <= key AND key <= $2`, tbl), from, to)
if err != nil {
return nil, fmt.Errorf("could not query in range, %w", err)
}
defer r.Close()
for r.Next() {
var v []byte
err := r.Scan(&v)
if err != nil {
return nil, fmt.Errorf("could not scan in range, %w", err)
}
vals = append(vals, v)
}
return vals, nil
}
func iterKV(db query, from string, to string, tbl string, log *slog.Logger) iter.Seq2[string, []byte] {
r, err := db.Query(fmt.Sprintf(`SELECT key, value FROM %s WHERE $1 <= key AND key <= $2`, tbl), from, to)
if err != nil {
if log != nil {
log.Error("[cove] iterKV, could not query in iter", "err", err)
return func(yield func(string, []byte) bool) {}
}
_, _ = fmt.Fprintf(os.Stderr, "[cove] iterKV, could not query in iter, %v", err)
return func(yield func(string, []byte) bool) {}
}
return func(yield func(string, []byte) bool) {
defer r.Close()
for r.Next() {
var k string
var v []byte
err := r.Scan(&k, &v)
if err != nil {
if log != nil {
log.Error("[cove] iterKV, could not scan in iter,", "err", err)
return
}
_, _ = fmt.Fprintf(os.Stderr, "cove: iterKV, could not scan in iter, %v", err)
return
}
if !yield(k, v) {
return
}
}
}
}
func iterKeys(db query, from string, to string, tbl string, log *slog.Logger) iter.Seq[string] {
r, err := db.Query(fmt.Sprintf(`SELECT key FROM %s WHERE $1 <= key AND key <= $2`, tbl), from, to)
if err != nil {
if log != nil {
log.Error("[cove] could not query in iter,", "err", err)
return func(yield func(string) bool) {}
}
_, _ = fmt.Fprintf(os.Stderr, "cove: could not query in iter, %v", err)
return func(yield func(string) bool) {}
}
return func(yield func(string) bool) {
defer r.Close()
for r.Next() {
var k string
err := r.Scan(&k)
if err != nil {
if log != nil {
log.Error("[cove] iterKeys, could not scan in iter,", "err", err)
return
}
_, _ = fmt.Fprintf(os.Stderr, "cove: iterKeys, could not scan in iter, %v", err)
return
}
if !yield(k) {
return
}
}
}
}
func iterValues(db query, from string, to string, tbl string, log *slog.Logger) iter.Seq[[]byte] {
r, err := db.Query(fmt.Sprintf(`SELECT value FROM %s WHERE $1 <= key AND key <= $2`, tbl), from, to)
if err != nil {
if log != nil {
log.Error("[cove] iterValues, could not query in iter,", "err", err)
return func(yield func([]byte) bool) {}
}
_, _ = fmt.Fprintf(os.Stderr, "cove: iterValues, could not query in iter, %v", err)
return func(yield func([]byte) bool) {}
}
return func(yield func([]byte) bool) {
defer r.Close()
for r.Next() {
var v string
err := r.Scan(&v)
if err != nil {
if log != nil {
log.Error("[cove] iterValues, could not scan in iter,", "err", err)
return
}
_, _ = fmt.Fprintf(os.Stderr, "cove: iterValues, could not scan in iter, %v", err)
return
}
if !yield([]byte(v)) {
return
}
}
}
}
func evictAll(r query, tbl string) (int, error) {
res, err := r.Exec(fmt.Sprintf(`
DELETE FROM %s
`, tbl))
if err != nil {
return 0, fmt.Errorf("could not delete all in %s, err; %w", tbl, err)
}
i, err := res.RowsAffected()
return int(i), err
}
func evict(r query, key string, tbl string) (KV[[]byte], error) {
var value []byte
err := r.QueryRow(fmt.Sprintf(`
DELETE FROM %s
WHERE key = $1
RETURNING value
`, tbl), key).Scan(&value)
if errors.Is(err, sql.ErrNoRows) {
return KV[[]byte]{}, NotFound
}
if err != nil {
return KV[[]byte]{}, fmt.Errorf("could not delete key %s, err; %w", key, err)
}
return KV[[]byte]{K: key, V: value}, err
}
func get(r query, key string, tbl string) ([]byte, error) {
var value []byte
err := r.QueryRow(fmt.Sprintf(`
SELECT value FROM %s
WHERE key = $1 AND strftime('%%s', 'now') < expire_at
`, tbl), key).Scan(&value)
if errors.Is(err, sql.ErrNoRows) {
return nil, NotFound
}
if err != nil {
return nil, fmt.Errorf("could not get key %s, err; %w", key, err)
}
return value, nil
}
func setTTL(r query, key string, value []byte, ttl time.Duration, tbl string) error {
if value == nil {
value = []byte{}
}
_, err := r.Exec(fmt.Sprintf(`
INSERT INTO %s (key, value, expire_at, ttl)
VALUES ($1, $2, strftime('%%s', 'now')+$3, $3)
ON CONFLICT (key)
DO UPDATE
SET
value = excluded.value,
create_at = excluded.create_at,
expire_at = excluded.expire_at,
ttl = excluded.ttl
`, tbl), key, value, int(ttl.Seconds()))
if err != nil {
return fmt.Errorf("could not exec, %w", err)
}
return nil
}
func batchGet(db query, keys []string, tbl string) ([]KV[[]byte], error) {
var values []string
var params []any
for i, key := range keys {
values = append(values, fmt.Sprintf("$%d", i+1))
params = append(params, key)
}
q := fmt.Sprintf(`
SELECT key, value FROM %s
WHERE key IN (%s)
AND strftime('%%s', 'now') < expire_at
`, tbl, strings.Join(values, ", "))
rows, err := db.Query(q, params...)
if err != nil {
return nil, fmt.Errorf("could not query, %w", err)
}
defer rows.Close()
var kvs []KV[[]byte]
for rows.Next() {
var k string
var v []byte
err := rows.Scan(&k, &v)
if err != nil {
return nil, fmt.Errorf("could not scan, %w", err)
}
kvs = append(kvs, KV[[]byte]{K: k, V: v})
}
return kvs, nil
}
func batchSet(db query, rows []KV[[]byte], ttl time.Duration, tbl string) error {
var values []string
var params []any
for i, kv := range rows {
values = append(values, fmt.Sprintf("($%d, $%d, strftime('%%s', 'now')+$%d, $%d)", i*3+1, i*3+2, i*3+3, i*3+3))
params = append(params, kv.K, kv.V, int(ttl.Seconds()))
}
q := fmt.Sprintf(`
INSERT INTO %s (key, value, expire_at, ttl)
VALUES %s
ON CONFLICT (key)
DO UPDATE
SET
value = excluded.value,
create_at = excluded.create_at,
expire_at = excluded.expire_at,
ttl = excluded.ttl
`, tbl, strings.Join(values, ","))
_, err := db.Exec(q, params...)
return err
}
func batchEvict(r query, keys []string, tbl string) ([]KV[[]byte], error) {
var values []string
var params []any
for i, key := range keys {
values = append(values, fmt.Sprintf("$%d", i+1))
params = append(params, key)
}
q := fmt.Sprintf(`
DELETE FROM %s
WHERE key IN (%s)
RETURNING key, value
`, tbl, strings.Join(values, ", "))
rows, err := r.Query(q, params...)
if err != nil {
return nil, fmt.Errorf("could not query, %w", err)
}
defer rows.Close()
var kvs []KV[[]byte]
for rows.Next() {
var k string
var v []byte
err := rows.Scan(&k, &v)
if err != nil {
return nil, fmt.Errorf("could not scan, %w", err)
}
kvs = append(kvs, KV[[]byte]{K: k, V: v})
}
return kvs, nil
}
func vacuumNoResult(r query, max int, tbl string) (int, error) {
q := fmt.Sprintf(`
DELETE FROM %s
WHERE expire_at < strftime('%%s', 'now')
AND key in (SELECT key FROM %s WHERE expire_at < strftime('%%s', 'now') LIMIT $1)
`, tbl, tbl)
res, err := r.Exec(q, max)
if err != nil {
return 0, fmt.Errorf("could not query, %w", err)
}
i, err := res.RowsAffected()
return int(i), err
}
func vacuum(r query, max int, tbl string) ([]KV[[]byte], error) {
q := fmt.Sprintf(`
DELETE FROM %s
WHERE expire_at < strftime('%%s', 'now')
AND key in (SELECT key FROM %s WHERE expire_at < strftime('%%s', 'now') LIMIT $1)
RETURNING key, value
`, tbl, tbl)
rows, err := r.Query(q, max)
if err != nil {
return nil, fmt.Errorf("could not query, %w", err)
}
defer rows.Close()
var kvs []KV[[]byte]
for rows.Next() {
var k string
var v []byte
err := rows.Scan(&k, &v)
if err != nil {
return nil, fmt.Errorf("could not scan, %w", err)
}
kvs = append(kvs, KV[[]byte]{K: k, V: v})
}
return kvs, nil
}