-
Notifications
You must be signed in to change notification settings - Fork 2
/
wrapper.go
101 lines (89 loc) · 2.12 KB
/
wrapper.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
99
100
101
package db
import (
"context"
"database/sql"
"sync"
"time"
"github.com/dyweb/gommon/errors"
dlog "github.com/dyweb/gommon/log"
"github.com/dyweb/go.ice/ice/config"
)
type Wrapper struct {
db *sql.DB
a Adapter
c config.DatabaseConfig
mu sync.RWMutex
log *dlog.Logger
}
func NewWrapper(a Adapter) *Wrapper {
w := &Wrapper{a: a}
w.log = dlog.NewStructLogger(log, w)
return w
}
func (w *Wrapper) Adapter() Adapter {
return w.a
}
func (w *Wrapper) SetDB(db *sql.DB) {
w.mu.Lock()
defer w.mu.Unlock()
if db == nil {
w.log.Warn("sql.DB pointer is nil")
}
w.db = db
}
// TODO: add error in return value? now we just warn if its nil ...
func (w *Wrapper) GetDB() *sql.DB {
w.mu.RLock()
defer w.mu.RUnlock()
if w.db == nil {
w.log.Warn("sql.DB pointer is nil")
}
return w.db
}
func (w *Wrapper) Transaction() (*sql.Tx, error) {
w.mu.RLock()
defer w.mu.RUnlock()
if w.db == nil {
return nil, errors.New("sql.DB pointer is nil")
}
if tx, err := w.db.BeginTx(context.Background(), nil); err != nil {
return tx, errors.Wrap(err, "can't begin transaction")
} else {
return tx, nil
}
}
func (w *Wrapper) Ping(timeout time.Duration) (time.Duration, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
start := time.Now()
err := w.db.PingContext(ctx)
duration := time.Now().Sub(start)
if err != nil {
return duration, errors.Wrap(err, "fail to ping")
}
return duration, nil
}
func (w *Wrapper) CreateDatabase(name string) error {
if !w.a.CanCreateDatabase() {
log.Warnf("%s does not support create database", w.a.DriverName())
return nil
}
db := w.db
// NOTE: you can't use transaction for create database ...
// pg: ERROR: CREATE DATABASE cannot run inside a transaction block
if _, err := db.Exec("CREATE DATABASE " + name + ";"); err != nil {
return errors.Wrapf(err, "can't create database %s", name)
}
log.Debugf("database %s created", name)
return nil
}
func (w *Wrapper) Close() error {
if w.db == nil {
w.log.Warn("closing nil db")
return nil
}
if err := w.db.Close(); err != nil {
return errors.Wrap(err, "error when closing db")
}
return nil
}