forked from Masterminds/squirrel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstmtcacher.go
90 lines (77 loc) · 1.85 KB
/
stmtcacher.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
package squirrel
import (
"database/sql"
"sync"
)
// Prepareer is the interface that wraps the Prepare method.
//
// Prepare executes the given query as implemented by database/sql.Prepare.
type Preparer interface {
Prepare(query string) (*sql.Stmt, error)
}
// DBProxy groups the Execer, Queryer, QueryRower, and Preparer interfaces.
type DBProxy interface {
Execer
Queryer
QueryRower
Preparer
}
type stmtCacher struct {
prep Preparer
cache map[string]*sql.Stmt
mu sync.Mutex
}
// NewStmtCacher returns a DBProxy wrapping prep that caches Prepared Stmts.
//
// Stmts are cached based on the string value of their queries.
func NewStmtCacher(prep Preparer) DBProxy {
return &stmtCacher{prep: prep, cache: make(map[string]*sql.Stmt)}
}
func (sc *stmtCacher) Prepare(query string) (*sql.Stmt, error) {
sc.mu.Lock()
defer sc.mu.Unlock()
stmt, ok := sc.cache[query]
if ok {
return stmt, nil
}
stmt, err := sc.prep.Prepare(query)
if err == nil {
sc.cache[query] = stmt
}
return stmt, err
}
func (sc *stmtCacher) Exec(query string, args ...interface{}) (res sql.Result, err error) {
stmt, err := sc.Prepare(query)
if err != nil {
return
}
return stmt.Exec(args...)
}
func (sc *stmtCacher) Query(query string, args ...interface{}) (rows *sql.Rows, err error) {
stmt, err := sc.Prepare(query)
if err != nil {
return
}
return stmt.Query(args...)
}
func (sc *stmtCacher) QueryRow(query string, args ...interface{}) RowScanner {
stmt, err := sc.Prepare(query)
if err != nil {
return &Row{err: err}
}
return stmt.QueryRow(args...)
}
type DBProxyBeginner interface {
DBProxy
Begin() (*sql.Tx, error)
}
type stmtCacheProxy struct {
DBProxy
db *sql.DB
}
func NewStmtCacheProxy(db *sql.DB) DBProxyBeginner {
return &stmtCacheProxy{DBProxy: NewStmtCacher(db), db: db}
}
func (sp *stmtCacheProxy) Begin() (*sql.Tx, error) {
return sp.db.Begin()
}