forked from brocaar/chirpstack-application-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
86 lines (78 loc) · 2.1 KB
/
db.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
package storage
import (
"fmt"
"time"
"github.com/brocaar/lora-app-server/internal/common"
"github.com/garyburd/redigo/redis"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
// register postgresql driver
_ "github.com/lib/pq"
)
const (
redisMaxIdle = 3
redisIdleTimeoutSec = 240
redisDialReadTimeout = 60 * time.Second
redisDialWriteTimeout = 10 * time.Second
)
// NewRedisPool returns a new Redis connection pool.
func NewRedisPool(redisURL string) *redis.Pool {
return &redis.Pool{
MaxIdle: redisMaxIdle,
IdleTimeout: redisIdleTimeoutSec * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.DialURL(redisURL,
redis.DialReadTimeout(redisDialReadTimeout),
redis.DialWriteTimeout(redisDialWriteTimeout),
)
if err != nil {
return nil, fmt.Errorf("redis connection error: %s", err)
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
if err != nil {
return fmt.Errorf("ping redis error: %s", err)
}
return nil
},
}
}
// OpenDatabase opens the database and performs a ping to make sure the
// database is up.
func OpenDatabase(dsn string) (*common.DBLogger, error) {
db, err := sqlx.Open("postgres", dsn)
if err != nil {
return nil, fmt.Errorf("database connection error: %s", err)
}
for {
if err := db.Ping(); err != nil {
log.Errorf("ping database error, will retry in 2s: %s", err)
time.Sleep(2 * time.Second)
} else {
break
}
}
return &common.DBLogger{DB: db}, nil
}
// Transaction wraps the given function in a transaction. In case the given
// functions returns an error, the transaction will be rolled back.
func Transaction(db *common.DBLogger, f func(tx sqlx.Ext) error) error {
tx, err := db.Beginx()
if err != nil {
return errors.Wrap(err, "begin transaction error")
}
err = f(tx)
if err != nil {
if rbErr := tx.Rollback(); rbErr != nil {
return errors.Wrap(rbErr, "transaction rollback error")
}
return err
}
if err := tx.Commit(); err != nil {
return errors.Wrap(err, "transaction commit error")
}
return nil
}