-
Notifications
You must be signed in to change notification settings - Fork 1
/
conn_getters.go
64 lines (49 loc) · 1.57 KB
/
conn_getters.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
package dbpool
import (
"context"
"errors"
"time"
"github.com/jmoiron/sqlx"
"github.com/jmoiron/sqlx/reflectx"
)
///////////////////////////////////////////////////////// Mapper functions
func JsonMapperFunc() *reflectx.Mapper {
return reflectx.NewMapperFunc("json", func(s string) string { return s })
}
/////////////////////////////////////////////////////////
// GetConnectionByParams - get *sqlx.DB from cache (if exists, with default-json-mapperFunc) or create new and put into cache
func GetConnectionByParams(Ctx context.Context, connCache *SafeDbMapCache,
duration time.Duration, driver, connString string) (*sqlx.DB, error) {
return GetConnectionWithMapper(Ctx, connCache, duration, driver, connString, JsonMapperFunc())
}
// GetConnectionWithMapper - get *sqlx.DB from cache (if exists, with set mapperFunc) or create new and put into cache
func GetConnectionWithMapper(
Ctx context.Context,
connCache *SafeDbMapCache,
duration time.Duration,
driver, connString string,
mapperFunc *reflectx.Mapper) (*sqlx.DB, error) {
conn, ok := connCache.Get(connString)
if ok && conn != nil {
// ping to check
err := conn.PingContext(Ctx)
if err != nil {
return nil, err
}
return conn, nil
}
// create conn
db, err := sqlx.ConnectContext(Ctx, driver, connString)
if err != nil {
return nil, err
}
db.SetConnMaxLifetime(duration)
db.Mapper = mapperFunc
// add conn to connCache
connCache.Set(connString, db, duration)
conn, ok = connCache.Get(connString)
if !ok && conn == nil {
return nil, errors.New("no conn in connCache")
}
return conn, nil
}