-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatement_cache.go
More file actions
70 lines (63 loc) · 1.21 KB
/
statement_cache.go
File metadata and controls
70 lines (63 loc) · 1.21 KB
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
package dbx
import (
"context"
"database/sql"
"sync"
)
type statementCache struct {
mu sync.Mutex
max int
order []string
items map[string]*sql.Stmt
}
func newStatementCache(max int) *statementCache {
if max < 1 {
max = 1
}
return &statementCache{
max: max,
order: make([]string, 0, max),
items: make(map[string]*sql.Stmt, max),
}
}
func (c *statementCache) GetOrPrepare(ctx context.Context, db *sql.DB, query string) (*sql.Stmt, error) {
c.mu.Lock()
if stmt, ok := c.items[query]; ok {
c.mu.Unlock()
return stmt, nil
}
c.mu.Unlock()
if ctx == nil {
ctx = context.Background()
}
stmt, err := db.PrepareContext(ctx, query)
if err != nil {
return nil, err
}
c.mu.Lock()
defer c.mu.Unlock()
if existing, ok := c.items[query]; ok {
_ = stmt.Close()
return existing, nil
}
c.items[query] = stmt
c.order = append(c.order, query)
if len(c.order) > c.max {
old := c.order[0]
c.order = c.order[1:]
if s, ok := c.items[old]; ok {
delete(c.items, old)
_ = s.Close()
}
}
return stmt, nil
}
func (c *statementCache) Close() {
c.mu.Lock()
defer c.mu.Unlock()
for _, stmt := range c.items {
_ = stmt.Close()
}
c.items = map[string]*sql.Stmt{}
c.order = c.order[:0]
}