-
Notifications
You must be signed in to change notification settings - Fork 342
/
store.go
235 lines (211 loc) · 5.62 KB
/
store.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
package postgres
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/treeverse/lakefs/pkg/kv"
)
type Driver struct{}
type Store struct {
Pool *pgxpool.Pool
Params *Params
TableSanitized string
}
type EntriesIterator struct {
rows pgx.Rows
entry *kv.Entry
err error
}
const (
DriverName = "postgres"
defaultTableName = "kv"
paramTableName = "lakefskv_table"
)
//nolint:gochecknoinits
func init() {
kv.Register(DriverName, &Driver{})
}
func (d *Driver) Open(ctx context.Context, name string) (kv.Store, error) {
// TODO(barak): should we handle Open reuse the same store based on name
config, err := pgxpool.ParseConfig(name)
if err != nil {
return nil, fmt.Errorf("%w: %s", kv.ErrDriverConfiguration, err)
}
pool, err := pgxpool.ConnectConfig(ctx, config)
if err != nil {
return nil, fmt.Errorf("%w: %s", kv.ErrConnectFailed, err)
}
defer func() {
// if we return before store uses the pool, free it
if pool != nil {
pool.Close()
}
}()
// acquire connection and make sure we reach the database
conn, err := pool.Acquire(ctx)
if err != nil {
return nil, fmt.Errorf("%w: %s", kv.ErrConnectFailed, err)
}
defer conn.Release()
err = conn.Conn().Ping(ctx)
if err != nil {
return nil, fmt.Errorf("%w: %s", kv.ErrConnectFailed, err)
}
params := parseStoreConfig(config.ConnConfig.RuntimeParams)
err = setupKeyValueDatabase(ctx, conn, params)
if err != nil {
return nil, fmt.Errorf("%w: %s", kv.ErrSetupFailed, err)
}
store := &Store{
Pool: pool,
Params: params,
TableSanitized: pgx.Identifier{params.TableName}.Sanitize(),
}
pool = nil
return store, nil
}
type Params struct {
TableName string
SanitizedTableName string
}
func parseStoreConfig(runtimeParams map[string]string) *Params {
p := &Params{
TableName: defaultTableName,
}
if tableName, ok := runtimeParams[paramTableName]; ok {
p.TableName = tableName
}
p.SanitizedTableName = pgx.Identifier{p.TableName}.Sanitize()
return p
}
// setupKeyValueDatabase setup everything required to enable kv over postgres
func setupKeyValueDatabase(ctx context.Context, conn *pgxpool.Conn, params *Params) error {
_, err := conn.Exec(ctx, `CREATE TABLE IF NOT EXISTS `+params.SanitizedTableName+` (
key BYTEA NOT NULL PRIMARY KEY,
value BYTEA NOT NULL);`)
return err
}
func (s *Store) Get(ctx context.Context, key []byte) ([]byte, error) {
if key == nil {
return nil, kv.ErrMissingKey
}
row := s.Pool.QueryRow(ctx, `SELECT value FROM `+s.Params.SanitizedTableName+` WHERE key = $1`, key)
var val []byte
err := row.Scan(&val)
if errors.Is(err, pgx.ErrNoRows) {
return nil, kv.ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("%s: %w", err, kv.ErrOperationFailed)
}
return val, nil
}
func (s *Store) Set(ctx context.Context, key, value []byte) error {
if key == nil {
return kv.ErrMissingKey
}
if value == nil {
return kv.ErrMissingValue
}
_, err := s.Pool.Exec(ctx, `INSERT INTO `+s.Params.SanitizedTableName+`(key,value) VALUES($1,$2)
ON CONFLICT (key) DO UPDATE SET value = $2`, key, value)
if err != nil {
return fmt.Errorf("%s: %w", err, kv.ErrOperationFailed)
}
return nil
}
func (s *Store) SetIf(ctx context.Context, key, value, valuePredicate []byte) error {
if key == nil {
return kv.ErrMissingKey
}
if value == nil {
return kv.ErrMissingValue
}
var (
res pgconn.CommandTag
err error
)
if valuePredicate == nil {
// use insert to make sure there was no previous value before
res, err = s.Pool.Exec(ctx, `INSERT INTO `+s.Params.SanitizedTableName+`(key,value) VALUES($1,$2) ON CONFLICT DO NOTHING`, key, value)
} else {
// update just in case the previous value was same as predicate value
res, err = s.Pool.Exec(ctx, `UPDATE `+s.Params.SanitizedTableName+` SET value=$2 WHERE key=$1 AND value=$3`, key, value, valuePredicate)
}
if err != nil {
return fmt.Errorf("%s: %w", err, kv.ErrOperationFailed)
}
if res.RowsAffected() != 1 {
return kv.ErrPredicateFailed
}
return nil
}
func (s *Store) Delete(ctx context.Context, key []byte) error {
if key == nil {
return kv.ErrMissingKey
}
_, err := s.Pool.Exec(ctx, `DELETE FROM `+s.Params.SanitizedTableName+` WHERE key=$1`, key)
if err != nil {
return fmt.Errorf("%s: %w", err, kv.ErrOperationFailed)
}
return nil
}
func (s *Store) Scan(ctx context.Context, start []byte) (kv.EntriesIterator, error) {
var (
rows pgx.Rows
err error
)
if start == nil {
rows, err = s.Pool.Query(ctx, `SELECT key,value FROM `+s.Params.SanitizedTableName+` ORDER BY key`)
} else {
rows, err = s.Pool.Query(ctx, `SELECT key,value FROM `+s.Params.SanitizedTableName+` WHERE key >= $1 ORDER BY key`, start)
}
if err != nil {
return nil, fmt.Errorf("%s: %w", err, kv.ErrOperationFailed)
}
return &EntriesIterator{
rows: rows,
}, nil
}
func (s *Store) Close() {
s.Pool.Close()
}
// Next reads the next key/value.
func (e *EntriesIterator) Next() bool {
if e.err != nil {
return false
}
e.entry = nil
if !e.rows.Next() {
return false
}
var ent kv.Entry
if err := e.rows.Scan(&ent.Key, &ent.Value); err != nil {
e.err = fmt.Errorf("%s: %w", err, kv.ErrOperationFailed)
return false
}
e.entry = &ent
return true
}
func (e *EntriesIterator) Entry() *kv.Entry {
return e.entry
}
// Err return the last scan error or the cursor error
func (e *EntriesIterator) Err() error {
if e.err != nil {
return e.err
}
if err := e.rows.Err(); err != nil {
e.err = fmt.Errorf("%s: %w", err, kv.ErrOperationFailed)
return err
}
return nil
}
func (e *EntriesIterator) Close() {
e.rows.Close()
e.entry = nil
e.err = kv.ErrClosedEntries
}