-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdb.go
353 lines (301 loc) · 10.4 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
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Copyright 2018-19 PJ Engineering and Business Solutions Pty. Ltd. All rights reserved.
package sql
import (
"context"
stdSql "database/sql"
"database/sql/driver"
"sync"
"time"
"golang.org/x/sync/errgroup"
)
// Open opens a database specified by its connection information.
//
// You will need to import "github.com/go-sql-driver/mysql".
//
// Open will just validate its arguments without creating a connection
// to the database. To verify that the data source name is valid, call
// Ping.
//
// The returned DB contains 2 pools. The KillerPool is configured to have only
// 1 max open connection. It is for internal use only.
//
// The returned DB is safe for concurrent use by multiple goroutines
// and maintains its own pool of idle connections. Thus, the Open
// function should be called just once. It is rarely necessary to
// close a DB. For the cancelation feature, a Conn needs to be created.
func Open(driverName string, dataSourceName ...string) (*DB, error) {
var (
dn string
dsn string
)
if len(dataSourceName) == 0 {
dn = "mysql"
dsn = driverName
} else {
dn = driverName
dsn = dataSourceName[0]
}
var (
mp *stdSql.DB
kp *stdSql.DB
)
var g errgroup.Group
g.Go(func() error {
pool, err := stdSql.Open(dn, dsn)
if err != nil {
return err
}
mp = pool
return nil
})
g.Go(func() error {
pool, err := stdSql.Open(dn, dsn)
if err != nil {
return err
}
kp = pool
kp.SetMaxOpenConns(1)
return nil
})
err := g.Wait()
if err != nil {
if mp != nil {
mp.Close()
}
if kp != nil {
kp.Close()
}
return nil, err
}
return &DB{
DB: mp,
KillerPool: kp,
}, nil
}
// OpenDB opens a database using a Connector, allowing drivers to
// bypass a string based data source name.
//
// You will need to import "github.com/go-sql-driver/mysql".
//
// OpenDB will just validate its arguments without creating a connection
// to the database. To verify that the data source name is valid, call
// Ping.
//
// The returned DB contains 2 pools. The KillerPool is configured to have only
// 1 max open connection. It is for internal use only.
//
// The returned DB is safe for concurrent use by multiple goroutines
// and maintains its own pool of idle connections. Thus, the OpenDB
// function should be called just once. It is rarely necessary to
// close a DB. For the cancelation feature, a Conn needs to be created.
func OpenDB(c driver.Connector) *DB {
var (
mp *stdSql.DB
kp *stdSql.DB
)
var wg sync.WaitGroup
go func() {
wg.Add(1)
defer wg.Done()
mp = stdSql.OpenDB(c)
}()
go func() {
wg.Add(1)
defer wg.Done()
kp = stdSql.OpenDB(c)
kp.SetMaxOpenConns(1)
}()
wg.Wait()
return &DB{
DB: mp,
KillerPool: kp,
}
}
// DB is a database handle representing a pool of zero or more
// underlying connections. It's safe for concurrent use by multiple
// goroutines.
//
// The sql package creates and frees connections automatically; it
// also maintains a free pool of idle connections. If the database has
// a concept of per-connection state, such state can be reliably observed
// within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the
// returned Tx is bound to a single connection. Once Commit or
// Rollback is called on the transaction, that transaction's
// connection is returned to DB's idle connection pool. The pool size
// can be controlled with SetMaxIdleConns.
type DB struct {
// DB is the primary connection pool (i.e. *stdSql.DB).
DB StdSQLDBExtra
// KillerPool is an optional (but recommended) secondary connection pool (i.e. *stdSql.DB).
// If provided, it is used to fire KILL signals.
KillerPool StdSQLDBExtra
// KillTimeout sets how long to attempt sending the KILL signal.
// A value of zero is equivalent to no time limit (not recommended).
KillTimeout time.Duration
}
// Begin starts a transaction. The default isolation level is dependent on
// the driver.
func (db *DB) Begin() (*stdSql.Tx, error) {
return db.DB.Begin()
}
// BeginTx starts a transaction.
//
// The provided context is used until the transaction is committed or rolled back.
// If the context is canceled, the sql package will roll back
// the transaction. Tx.Commit will return an error if the context provided to
// BeginTx is canceled.
//
// The provided TxOptions is optional and may be nil if defaults should be used.
// If a non-default isolation level is used that the driver doesn't support,
// an error will be returned.
func (db *DB) BeginTx(ctx context.Context, opts *stdSql.TxOptions) (*stdSql.Tx, error) {
return db.DB.BeginTx(ctx, opts)
}
// Close closes the database and prevents new queries from starting.
// Close then waits for all queries that have started processing on the server
// to finish.
//
// It is rare to Close a DB, as the DB handle is meant to be
// long-lived and shared between many goroutines.
func (db *DB) Close() error {
if db.KillerPool == db.DB {
return db.DB.Close()
}
if db.KillerPool != nil {
db.KillerPool.Close()
}
return db.DB.Close()
}
// Conn returns a single connection by either opening a new connection
// or returning an existing connection from the connection pool. Conn will
// block until either a connection is returned or ctx is canceled.
// Queries run on the same Conn will be run in the same database session.
//
// Every Conn must be returned to the database pool after use by
// calling Conn.Close.
func (db *DB) Conn(ctx context.Context) (*Conn, error) {
// Obtain an exclusive connection
conn, err := db.DB.Conn(ctx)
if err != nil {
return nil, err
}
// Determine the connection's connection_id
var connectionID string
err = conn.QueryRowContext(ctx, "SELECT CONNECTION_ID()").Scan(&connectionID)
if err != nil {
// Return the connection back to the pool
conn.Close()
return nil, err
}
if db.KillerPool == nil {
return &Conn{conn, db.DB, connectionID, db.KillTimeout}, nil
}
return &Conn{conn, db.KillerPool, connectionID, db.KillTimeout}, nil
}
// Driver returns the database's underlying driver.
func (db *DB) Driver() driver.Driver {
return db.DB.Driver()
}
// Exec executes a query without returning any rows.
// The args are for any placeholder parameters in the query.
func (db *DB) Exec(query string, args ...interface{}) (stdSql.Result, error) {
return db.DB.Exec(query, args...)
}
// ExecContext executes a query without returning any rows.
// The args are for any placeholder parameters in the query.
func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (stdSql.Result, error) {
return db.DB.ExecContext(ctx, query, args...)
}
// Ping verifies a connection to the database is still alive,
// establishing a connection if necessary.
func (db *DB) Ping() error {
return db.DB.Ping()
}
// PingContext verifies a connection to the database is still alive,
// establishing a connection if necessary.
func (db *DB) PingContext(ctx context.Context) error {
return db.DB.PingContext(ctx)
}
// Prepare creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the
// returned statement.
// The caller must call the statement's Close method
// when the statement is no longer needed.
func (db *DB) Prepare(query string) (*stdSql.Stmt, error) {
return db.DB.Prepare(query)
}
// PrepareContext creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the
// returned statement.
// The caller must call the statement's Close method
// when the statement is no longer needed.
//
// The provided context is used for the preparation of the statement, not for the
// execution of the statement.
func (db *DB) PrepareContext(ctx context.Context, query string) (*stdSql.Stmt, error) {
return db.DB.PrepareContext(ctx, query)
}
// Query executes a query that returns rows, typically a SELECT.
// The args are for any placeholder parameters in the query.
func (db *DB) Query(query string, args ...interface{}) (*stdSql.Rows, error) {
return db.DB.Query(query, args...)
}
// QueryContext executes a query that returns rows, typically a SELECT.
// The args are for any placeholder parameters in the query.
func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*stdSql.Rows, error) {
return db.DB.QueryContext(ctx, query, args...)
}
// QueryRow executes a query that is expected to return at most one row.
// QueryRow always returns a non-nil value. Errors are deferred until
// Row's Scan method is called.
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
// Otherwise, the *Row's Scan scans the first selected row and discards
// the rest.
func (db *DB) QueryRow(query string, args ...interface{}) *stdSql.Row {
return db.DB.QueryRow(query, args...)
}
// QueryRowContext executes a query that is expected to return at most one row.
// QueryRowContext always returns a non-nil value. Errors are deferred until
// Row's Scan method is called.
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
// Otherwise, the *Row's Scan scans the first selected row and discards
// the rest.
func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *stdSql.Row {
return db.DB.QueryRowContext(ctx, query, args...)
}
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
//
// Expired connections may be closed lazily before reuse.
//
// If d <= 0, connections are reused forever.
func (db *DB) SetConnMaxLifetime(d time.Duration) {
db.DB.SetConnMaxLifetime(d)
}
// SetMaxIdleConns sets the maximum number of connections in the idle
// connection pool.
//
// If MaxOpenConns is greater than 0 but less than the new MaxIdleConns,
// then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.
//
// If n <= 0, no idle connections are retained.
//
// The default max idle connections is currently 2. This may change in
// a future release.
func (db *DB) SetMaxIdleConns(n int) {
db.DB.SetMaxIdleConns(n)
}
// SetMaxOpenConns sets the maximum number of open connections to the database.
//
// If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
// MaxIdleConns, then MaxIdleConns will be reduced to match the new
// MaxOpenConns limit.
//
// If n <= 0, then there is no limit on the number of open connections.
// The default is 0 (unlimited).
func (db *DB) SetMaxOpenConns(n int) {
db.DB.SetMaxOpenConns(n)
}
// Stats returns database statistics.
func (db *DB) Stats() stdSql.DBStats {
return db.DB.Stats()
}