-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgres_batch.go
109 lines (91 loc) · 2.03 KB
/
postgres_batch.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
package postgreskvdb
import (
"context"
"fmt"
"sync"
"github.com/jackc/pgx/v5"
)
type PostgresDBBatch struct {
conn *pgx.Conn
queries []queryBatch
mtx sync.Mutex
}
type queryBatch struct {
key, value []byte
operator opType
}
var _ Batch = (*PostgresDBBatch)(nil)
func NewPostgresDBBatch(conn *pgx.Conn) *PostgresDBBatch {
return &PostgresDBBatch{
conn: conn,
queries: make([]queryBatch, 0),
}
}
func (b *PostgresDBBatch) Set(key, value []byte) error {
b.mtx.Lock()
defer b.mtx.Unlock()
if len(key) == 0 {
return errKeyEmpty
}
if value == nil {
return errValueNil
}
if b.queries == nil {
return errBatchClosed
}
b.queries = append(b.queries, queryBatch{key: key, value: value, operator: opTypeSet})
return nil
}
func (b *PostgresDBBatch) Delete(key []byte) error {
b.mtx.Lock()
defer b.mtx.Unlock()
if len(key) == 0 {
return errKeyEmpty
}
if b.queries == nil {
return errBatchClosed
}
b.queries = append(b.queries, queryBatch{key: key, operator: opTypeDelete})
return nil
}
func (b *PostgresDBBatch) Write() error {
b.mtx.Lock()
defer b.mtx.Unlock()
if b.queries == nil {
return errBatchClosed
}
batch := &pgx.Batch{}
for _, value := range b.queries {
switch value.operator {
case opTypeSet:
id, err := generateUUIDv5FromBytes(value.key)
if err != nil {
return err
}
query := "INSERT INTO kv_store (id,key, value) VALUES ($1, $2,$3) ON CONFLICT (key) DO UPDATE SET value = $3;"
batch.Queue(query, id, value.key, value.value)
case opTypeDelete:
query := "DELETE FROM kv_store WHERE key = $1;"
batch.Queue(query, value.key)
default:
return fmt.Errorf("unknown operation type %v (%v)", value.operator, value)
}
}
br := b.conn.SendBatch(context.Background(), batch)
defer br.Close()
_, err := br.Exec()
if err != nil {
return err
}
return nil
}
func (b *PostgresDBBatch) WriteSync() error {
return b.Write()
}
func (b *PostgresDBBatch) Close() error {
b.mtx.Lock()
defer b.mtx.Unlock()
// Clear queries for reusability
b.queries = nil
return nil
}