This repository has been archived by the owner on Jan 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
cache.go
98 lines (81 loc) · 2.12 KB
/
cache.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
91
92
93
94
95
96
97
98
package gomodel
import "database/sql"
type (
// cacheItem keeps the sql and prepared statement of it
cacheItem struct {
sql string
stmt *sql.Stmt
}
cache map[uint64]cacheItem // map[id]{sql, stmt}
)
func newCache() cache {
return make(cache)
}
// StmtById search a prepared statement for given sql type by id, if not found,
// create with the creator, and prepared the sql to a statement, cache it, then
// return
func (c cache) StmtById(exec Executor, sqlid uint64) (*sql.Stmt, error) {
if item, has := c[sqlid]; has {
sqlPrinter.Print(true, item.sql)
return item.stmt, nil
}
sql_ := SqlById(exec, sqlid)
sql_ = exec.Driver().Prepare(sql_)
sqlPrinter.Print(false, sql_)
stmt, err := exec.Prepare(sql_)
if err != nil {
return nil, err
}
c[sqlid] = cacheItem{sql: sql_, stmt: stmt}
return stmt, nil
}
// GetStmt get sql and statement from cacher, if not found, "" and nil was returned
func (c cache) GetStmt(exec Executor, sqlid uint64) (string, *sql.Stmt, error) {
item, has := c[sqlid]
if !has {
return "", nil, nil
}
var err error
if item.stmt == nil {
item.sql = exec.Driver().Prepare(item.sql)
item.stmt, err = exec.Prepare(item.sql)
}
return item.sql, item.stmt, err
}
// SetStmt exec a sql to statement, cache then return it
func (c cache) SetStmt(exec Executor, sqlid uint64, sql string) (*sql.Stmt, error) {
sql = exec.Driver().Prepare(sql)
stmt, err := exec.Prepare(sql)
if err != nil {
return nil, err
}
c[sqlid] = cacheItem{
sql: sql,
stmt: stmt,
}
return stmt, nil
}
func (c cache) PrepareById(exec Executor, sqlid uint64) (*sql.Stmt, error) {
item, has := c[sqlid]
if !has {
item.sql = exec.Driver().Prepare(SqlById(exec, sqlid))
c[sqlid] = item
}
sqlPrinter.Print(has, item.sql)
stmt, err := exec.Prepare(item.sql)
return stmt, err
}
func (c cache) PrepareSQL(exec Executor, sqlid uint64) (string, *sql.Stmt, error) {
item, has := c[sqlid]
if !has {
return "", nil, nil
}
item.sql = exec.Driver().Prepare(item.sql)
stmt, err := exec.Prepare(item.sql)
return item.sql, stmt, err
}
func (c cache) SetSQL(sqlid uint64, sql string) {
c[sqlid] = cacheItem{
sql: sql,
}
}