-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
65 lines (52 loc) · 1.06 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
package qp
import (
"errors"
"fmt"
"io"
"log/slog"
"sync"
"github.com/jmoiron/sqlx"
)
type stmt interface {
sqlx.Stmt | sqlx.NamedStmt
}
type cache[T stmt] struct {
ctor func(*sqlx.DB, string) (*T, error)
build func(*query) (string, error)
m sync.Map
}
func (c *cache[T]) prepare(db *sqlx.DB, q *query) (*T, error) {
v, ok := c.m.Load(q.key)
if ok {
return v.(*T), nil
}
raw, err := c.build(q)
if err != nil {
return nil, fmt.Errorf("error building query: %w", err)
}
slog.Debug("preparing statement",
"driver", db.DriverName(),
"type", q.name,
"sql", raw,
)
stmt, err := c.ctor(db, raw)
if err != nil {
return nil, fmt.Errorf("error preparing statement: %w", err)
}
v, dup := c.m.LoadOrStore(q.key, stmt)
if dup {
_ = interface{}(stmt).(io.Closer).Close() // discard the duplicate
stmt = v.(*T)
}
return stmt, nil
}
func (c *cache[T]) Close() error {
var err error
c.m.Range(func(_, v interface{}) bool {
if e := interface{}(v).(io.Closer).Close(); e != nil {
err = errors.Join(err, e)
}
return true
})
return err
}