-
Notifications
You must be signed in to change notification settings - Fork 0
/
dblink.go
189 lines (143 loc) · 3.9 KB
/
dblink.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package mysqlkebab
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"time"
)
// DBLink is the basic interface between developer and database instance
type DBLink struct {
db *sql.DB // db DBLink Connection Handler
DBLinkOptions // connection options
supposedReady bool
}
// log prints log messages in case of l.debugPrint is true
func (l *DBLink) log(format string, args ...interface{}) {
if l.debugPrint {
s := fmt.Sprintf(format, args...)
log.Println(s)
}
}
// SetEmergencyCallback defines a routine to log emergency "no-connection" messages
func (l *DBLink) SetEmergencyCallback(ec func(error)) {
l.emergencyCallback = ec
}
func (l *DBLink) connectSimple() error {
l.supposedReady = false
l.db = nil
db, err := sql.Open("mysql", l.connectionString.get())
if err != nil {
if l.debugPrint {
log.Printf("couldn't connect database. %v\n", err)
}
return err
}
l.db = db
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(l.connectionTimeoutSeconds)*time.Second)
defer cancel()
if er2 := l.db.PingContext(ctx); er2 != nil {
if l.debugPrint {
log.Printf("couldn't ping database. %v\n", er2)
}
return er2
}
l.supposedReady = true
return nil
}
func (l *DBLink) connectLoop() error {
// If the first attempt failed, a more sophisticated approach is executed, addressing a controlled flow of sequential attempts
var (
connectionAttempt uint
connectionTimerStart = time.Now()
)
waitNextAttempt := func() {
if l.debugPrint {
log.Printf("wating %d seconds before retry to connect database.", l.secondsBetweenConnectionAttempts)
}
time.Sleep(time.Duration(l.secondsBetweenConnectionAttempts) * time.Second)
}
for {
err := l.connectSimple()
if err == nil {
return nil
}
if time.Now().Before(connectionTimerStart.Add(time.Duration(l.connectionAttemptsMaxMinutes) * time.Minute)) {
if l.debugPrint {
log.Printf("database connection time limit reached without success. %v\n", err)
}
return fmt.Errorf("database connection time limit reached without success. %v", err)
}
connectionAttempt++
if connectionAttempt >= l.connectionAttemptsMax {
if l.debugPrint {
log.Printf("database connection attempts limit reached without success. %v\n", err)
}
return fmt.Errorf("database connection attempts limit reached without success. %v", err)
}
waitNextAttempt()
continue
}
}
// Connect assures that database could be reached and used.
func (l *DBLink) Connect() error {
if l.debugPrint {
log.Println("opening database connection")
}
l.DBLinkOptions.print()
if l.connectionAttemptsMax == 1 {
return l.connectSimple()
}
return l.connectLoop()
}
// NewConnected return an already connected link
func NewConnected(opts *DBLinkOptions) (*DBLink, error) {
dbl, err := New(opts)
if err != nil {
return nil, err
}
if er0 := dbl.Connect(); er0 != nil {
return nil, er0
}
return dbl, nil
}
// Disconnect closes the link with database or database pool
func (l *DBLink) Disconnect() {
if l.debugPrint {
log.Println("disconnecting from database")
}
if l == nil || l.db == nil || !l.supposedReady {
return
}
if err := l.db.Close(); err != nil {
if l.debugPrint {
log.Println(err)
}
}
}
// Database returns the raw sql driver database connection, aimed to let the programmer execute transactions and advanced operations
func (l *DBLink) Database() *sql.DB {
return l.db
}
// IsEmptyErr returns true if the given error is sql.ErrNoRows
func (l *DBLink) IsEmptyErr(err error) bool {
if err == nil {
return false
}
return errors.Is(err, sql.ErrNoRows)
}
// New return an instance of database, configured with options.
func New(opts *DBLinkOptions) (*DBLink, error) {
if opts == nil {
return nil, fmt.Errorf("undefined options")
}
if erv := opts.validate(); erv != nil {
return nil, erv
}
dbl := DBLink{
db: nil,
DBLinkOptions: *opts,
}
return &dbl, nil
}