-
Notifications
You must be signed in to change notification settings - Fork 42
/
sql.go
281 lines (260 loc) · 8.05 KB
/
sql.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
package ipam
import (
"context"
dbsql "database/sql"
"errors"
"fmt"
"strings"
"sync"
"github.com/jmoiron/sqlx"
)
type sql struct {
db *sqlx.DB
maxIdLength int
tables sync.Map
}
func createTableSQL(namespace string) string {
return fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
cidr text PRIMARY KEY NOT NULL,
prefix JSONB
);
CREATE INDEX IF NOT EXISTS prefix_idx ON %s USING GIN(prefix);
`, getTableName(namespace), getTableName(namespace))
}
func getTableName(namespace string) string {
if namespace == defaultNamespace {
return "prefixes"
}
return fmt.Sprintf("\"prefixes_%s\"", namespace)
}
func (s *sql) prefixExists(ctx context.Context, prefix Prefix, namespace string) (*Prefix, bool) {
p, err := s.ReadPrefix(ctx, prefix.Cidr, namespace)
if err != nil {
return nil, false
}
return &p, true
}
func (s *sql) checkNamespaceExists(ctx context.Context, namespace string) error {
if _, ok := s.tables.Load(namespace); ok {
return nil
}
// populate namespaces from sql
if _, err := s.ListNamespaces(ctx); err != nil {
return err
}
if _, ok := s.tables.Load(namespace); !ok {
return ErrNamespaceDoesNotExist
}
return nil
}
func (s *sql) CreatePrefix(ctx context.Context, prefix Prefix, namespace string) (Prefix, error) {
if err := s.checkNamespaceExists(ctx, namespace); err != nil {
return Prefix{}, err
}
existingPrefix, exists := s.prefixExists(ctx, prefix, namespace)
if exists {
return *existingPrefix, nil
}
prefix.version = int64(0)
pj, err := prefix.toJSON()
if err != nil {
return Prefix{}, err
}
tx, err := s.db.Beginx()
if err != nil {
return Prefix{}, fmt.Errorf("unable to start transaction:%w", err)
}
// Defer a rollback in case anything fails.
defer func() {
_ = tx.Rollback()
}()
_, err = tx.ExecContext(ctx, "INSERT INTO "+getTableName(namespace)+"(cidr, prefix) VALUES ($1, $2)", prefix.Cidr, pj)
if err != nil {
return Prefix{}, fmt.Errorf("unable to insert prefix:%w", err)
}
if err := tx.Commit(); err != nil {
return Prefix{}, err
}
return prefix, nil
}
func (s *sql) ReadPrefix(ctx context.Context, prefix, namespace string) (Prefix, error) {
if err := s.checkNamespaceExists(ctx, namespace); err != nil {
return Prefix{}, err
}
var result []byte
err := s.db.GetContext(ctx, &result, "SELECT prefix FROM "+getTableName(namespace)+" WHERE cidr=$1", prefix)
if err != nil {
if errors.Is(err, dbsql.ErrNoRows) {
return Prefix{}, fmt.Errorf("%w prefix:%s not found:%s", ErrNotFound, prefix, err.Error())
}
return Prefix{}, fmt.Errorf("unable to read prefix:%w", err)
}
return fromJSON(result)
}
func (s *sql) DeleteAllPrefixes(ctx context.Context, namespace string) error {
if err := s.checkNamespaceExists(ctx, namespace); err != nil {
return err
}
_, err := s.db.ExecContext(ctx, "DELETE FROM "+getTableName(namespace))
return err
}
// ReadAllPrefixes returns all known prefixes.
func (s *sql) ReadAllPrefixes(ctx context.Context, namespace string) (Prefixes, error) {
if err := s.checkNamespaceExists(ctx, namespace); err != nil {
return nil, err
}
var prefixes [][]byte
err := s.db.SelectContext(ctx, &prefixes, "SELECT prefix FROM "+getTableName(namespace))
if err != nil {
return nil, fmt.Errorf("unable to read prefixes:%w", err)
}
return toPrefixes(prefixes)
}
func toPrefixes(prefixes [][]byte) ([]Prefix, error) {
result := Prefixes{}
for _, v := range prefixes {
pfx, err := fromJSON(v)
if err != nil {
return nil, err
}
result = append(result, pfx)
}
return result, nil
}
// ReadAllPrefixCidrs is cheaper that ReadAllPrefixes because it only returns the Cidrs.
func (s *sql) ReadAllPrefixCidrs(ctx context.Context, namespace string) ([]string, error) {
if err := s.checkNamespaceExists(ctx, namespace); err != nil {
return nil, err
}
cidrs := []string{}
err := s.db.SelectContext(ctx, &cidrs, "SELECT cidr FROM "+getTableName(namespace))
if err != nil {
return nil, fmt.Errorf("unable to read prefixes in namespace:%s :%w", namespace, err)
}
return cidrs, nil
}
// UpdatePrefix tries to update the prefix.
// Returns OptimisticLockError if it does not succeed due to a concurrent update.
func (s *sql) UpdatePrefix(ctx context.Context, prefix Prefix, namespace string) (Prefix, error) {
if err := s.checkNamespaceExists(ctx, namespace); err != nil {
return Prefix{}, err
}
oldVersion := prefix.version
prefix.version = oldVersion + 1
pn, err := prefix.toJSON()
if err != nil {
return Prefix{}, err
}
tx, err := s.db.Beginx()
if err != nil {
return Prefix{}, fmt.Errorf("unable to start transaction:%w", err)
}
// Defer a rollback in case anything fails.
defer func() {
_ = tx.Rollback()
}()
result, err := tx.ExecContext(ctx, "SELECT prefix FROM "+getTableName(namespace)+" WHERE cidr=$1 AND prefix->>'Version'=$2 FOR UPDATE", prefix.Cidr, oldVersion)
if err != nil {
return Prefix{}, fmt.Errorf("%w: unable to select for update prefix:%s", ErrOptimisticLockError, prefix.Cidr)
}
rows, err := result.RowsAffected()
if err != nil {
return Prefix{}, err
}
if rows == 0 {
// Rollback, but ignore error, if rollback is omitted, the row lock created by SELECT FOR UPDATE will not get released.
_ = tx.Rollback()
return Prefix{}, fmt.Errorf("%w: select for update did not effect any row", ErrOptimisticLockError)
}
result, err = tx.ExecContext(ctx, "UPDATE "+getTableName(namespace)+" SET prefix=$1 WHERE cidr=$2 AND prefix->>'Version'=$3", pn, prefix.Cidr, oldVersion)
if err != nil {
return Prefix{}, fmt.Errorf("%w: unable to update prefix:%s", ErrOptimisticLockError, prefix.Cidr)
}
rows, err = result.RowsAffected()
if err != nil {
return Prefix{}, err
}
if rows == 0 {
// Rollback, but ignore error, if rollback is omitted, the row lock created by SELECT FOR UPDATE will not get released.
_ = tx.Rollback()
return Prefix{}, fmt.Errorf("%w: updatePrefix did not effect any row", ErrOptimisticLockError)
}
if err := tx.Commit(); err != nil {
return Prefix{}, err
}
return prefix, nil
}
func (s *sql) DeletePrefix(ctx context.Context, prefix Prefix, namespace string) (Prefix, error) {
if err := s.checkNamespaceExists(ctx, namespace); err != nil {
return Prefix{}, err
}
tx, err := s.db.Beginx()
if err != nil {
return Prefix{}, fmt.Errorf("unable to start transaction: %w", err)
}
// Defer a rollback in case anything fails.
defer func() {
_ = tx.Rollback()
}()
_, err = tx.ExecContext(ctx, "DELETE from "+getTableName(namespace)+" WHERE cidr=$1", prefix.Cidr)
if err != nil {
return Prefix{}, fmt.Errorf("unable delete prefix: %w", err)
}
if err := tx.Commit(); err != nil {
return Prefix{}, err
}
return prefix, nil
}
func (s *sql) Name() string {
return "postgres"
}
func (s *sql) CreateNamespace(ctx context.Context, namespace string) error {
if len(namespace) > s.maxIdLength {
return ErrNameTooLong
}
if _, ok := s.tables.Load(namespace); !ok {
if _, err := s.db.ExecContext(ctx, createTableSQL(namespace)); err != nil {
return fmt.Errorf("unable to create table: %w", err)
}
s.tables.Store(namespace, struct{}{})
}
return nil
}
func (s *sql) ListNamespaces(ctx context.Context) ([]string, error) {
var result []string
if err := s.db.SelectContext(ctx, &result, "SELECT table_name FROM information_schema.tables WHERE table_name LIKE 'prefix%'"); err != nil {
return nil, fmt.Errorf("unable to get tables: %w", err)
}
for i := range result {
if result[i] == "prefixes" {
result[i] = defaultNamespace
} else {
result[i] = strings.TrimPrefix(result[i], "prefixes_")
}
s.tables.Store(result[i], struct{}{})
}
return result, nil
}
func (s *sql) DeleteNamespace(ctx context.Context, namespace string) error {
if err := s.checkNamespaceExists(ctx, namespace); err != nil {
return err
}
tx, err := s.db.Beginx()
if err != nil {
return fmt.Errorf("unable to start transaction: %w", err)
}
// Defer a rollback in case anything fails.
defer func() {
_ = tx.Rollback()
}()
_, err = tx.ExecContext(ctx, "DROP TABLE "+getTableName(namespace))
if err != nil {
return fmt.Errorf("unable delete prefix:%w", err)
}
if err := tx.Commit(); err != nil {
return err
}
s.tables.Delete(namespace)
return nil
}