forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbtxn.go
63 lines (50 loc) · 1.33 KB
/
dbtxn.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 dbtxn
import (
"context"
"database/sql"
"fmt"
"strings"
)
// ExecuteDBQuery handles executing one single statement, while properly releasing its resources.
// - ctx: Required
// - db: Required
// - config: Optional, may be nil
// - query: Required
func ExecuteDBQuery(ctx context.Context, db *sql.DB, params map[string]string, query string) error {
parsedQuery := parseQuery(params, query)
stmt, err := db.PrepareContext(ctx, parsedQuery)
if err != nil {
return err
}
defer stmt.Close()
return execute(ctx, stmt)
}
// ExecuteTxQuery handles executing one single statement, while properly releasing its resources.
// - ctx: Required
// - tx: Required
// - config: Optional, may be nil
// - query: Required
func ExecuteTxQuery(ctx context.Context, tx *sql.Tx, params map[string]string, query string) error {
parsedQuery := parseQuery(params, query)
stmt, err := tx.PrepareContext(ctx, parsedQuery)
if err != nil {
return err
}
defer stmt.Close()
return execute(ctx, stmt)
}
func execute(ctx context.Context, stmt *sql.Stmt) error {
if _, err := stmt.ExecContext(ctx); err != nil {
return err
}
return nil
}
func parseQuery(m map[string]string, tpl string) string {
if m == nil || len(m) <= 0 {
return tpl
}
for k, v := range m {
tpl = strings.Replace(tpl, fmt.Sprintf("{{%s}}", k), v, -1)
}
return tpl
}