-
Notifications
You must be signed in to change notification settings - Fork 0
/
rename.go
67 lines (53 loc) · 1.52 KB
/
rename.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
package sdk
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/georgysavva/scany/v2/sqlscan"
"github.com/jtarchie/sqlettuce/executers"
)
func (c *Client) Rename(ctx context.Context, current string, next string) error {
err := c.db.WithTX(ctx, func(tx executers.Executer) error {
_, _ = tx.ExecContext(ctx, `DELETE FROM keys WHERE name = :new`, sql.Named("new", next))
result, err := tx.ExecContext(ctx, `UPDATE keys SET name = :new WHERE name = :old`, sql.Named("new", next), sql.Named("old", current))
if err != nil {
return fmt.Errorf("could not rename key: %w", err)
}
count, _ := result.RowsAffected()
if count == 0 {
return ErrKeyDoesNotExist
}
return nil
})
if err != nil {
return fmt.Errorf("could not rename: %w", err)
}
return nil
}
func (c *Client) RenameIfNotExists(ctx context.Context, current string, next string) error {
err := c.db.WithTX(ctx, func(tx executers.Executer) error {
var value int
err := sqlscan.Get(ctx, tx, &value,
`SELECT 1 FROM keys WHERE name = :new`,
sql.Named("new", next),
)
if errors.Is(err, sql.ErrNoRows) {
_, err = tx.ExecContext(ctx, `UPDATE keys SET name = :new WHERE name = :old`, sql.Named("new", next), sql.Named("old", current))
if err != nil {
return fmt.Errorf("could not rename key: %w", err)
}
}
if err != nil {
return fmt.Errorf("could not find new: %w", err)
}
if value == 1 {
return ErrKeyAlreadyExists
}
return nil
})
if err != nil {
return fmt.Errorf("could not rename: %w", err)
}
return nil
}