-
-
Notifications
You must be signed in to change notification settings - Fork 222
/
stmt.go
62 lines (49 loc) · 1.48 KB
/
stmt.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
//go:build linux && cgo && !agent
package cluster
import (
"database/sql"
"fmt"
)
// RegisterStmt register a SQL statement.
//
// Registered statements will be prepared upfront and re-used, to speed up
// execution.
//
// Return a unique registration code.
func RegisterStmt(sql string) int {
code := len(stmts)
stmts[code] = sql
return code
}
// PrepareStmts prepares all registered statements and returns an index from
// statement code to prepared statement object.
func PrepareStmts(db *sql.DB, skipErrors bool) (map[int]*sql.Stmt, error) {
index := map[int]*sql.Stmt{}
for code, sql := range stmts {
stmt, err := db.Prepare(sql)
if err != nil && !skipErrors {
return nil, fmt.Errorf("%q: %w", sql, err)
}
index[code] = stmt
}
return index, nil
}
var stmts = map[int]string{} // Statement code to statement SQL text.
// PreparedStmts is a placeholder for transitioning to package-scoped transaction functions.
var PreparedStmts = map[int]*sql.Stmt{}
// Stmt prepares the in-memory prepared statement for the transaction.
func Stmt(tx *sql.Tx, code int) (*sql.Stmt, error) {
stmt, ok := PreparedStmts[code]
if !ok {
return nil, fmt.Errorf("No prepared statement registered with code %d", code)
}
return tx.Stmt(stmt), nil
}
// StmtString returns the in-memory query string with the given code.
func StmtString(code int) (string, error) {
stmt, ok := stmts[code]
if !ok {
return "", fmt.Errorf("No prepared statement registered with code %d", code)
}
return stmt, nil
}