-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostgres_provider.go
63 lines (57 loc) · 1.49 KB
/
postgres_provider.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
package openapi
import (
"database/sql"
"errors"
"fmt"
)
const (
queryTemplate4PG = "SELECT %s FROM %s WHERE %s = $1 LIMIT 1"
insertTemplate4PG = "INSERT INTO %s (%s, %s)VALUES($1, $2)"
)
// default provided sql
type PgSqlSecretKeeper struct {
Db *sql.DB // the client to access database
TableName string // the table where the secret stores
KeyCol string // the column name of the key
SecretCol string // the column name of the secret
}
// get secret from a sql data source
func (s PgSqlSecretKeeper) GetSecret(key string) (string, error) {
if s.Db == nil {
return EmptyString, errors.New("db client should not be nil")
}
row := s.Db.QueryRow(s.constructQuery(), key)
var secret string
err := row.Scan(&secret)
if err != nil {
return EmptyString, err
}
return secret, nil
}
// construct query for getting secret
func (s PgSqlSecretKeeper) constructQuery() string {
return fmt.Sprintf(queryTemplate4PG, s.SecretCol, s.TableName, s.KeyCol)
}
func (s PgSqlSecretKeeper) GeneratePair() *KvPair {
p := KvPair{
Key: string(randomStr(keyLen, kindAll)),
Value: string(randomStr(secretLen, kindAll)),
}
// do the insert work
insertSql := fmt.Sprintf(insertTemplate4PG, s.TableName, s.KeyCol, s.SecretCol)
stmt, err := s.Db.Prepare(insertSql)
if err != nil {
return nil
}
r, err := stmt.Exec(p.Key, p.Value)
if err != nil || r == nil {
return nil
}
defer stmt.Close()
a, err := r.RowsAffected()
// check result
if err != nil || a < 1 {
return nil
}
return &p
}