forked from go-pg/pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
398 lines (334 loc) · 8.54 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package pg // import "gopkg.in/pg.v4"
import (
"io"
"time"
"gopkg.in/pg.v4/internal"
"gopkg.in/pg.v4/internal/pool"
"gopkg.in/pg.v4/orm"
"gopkg.in/pg.v4/types"
)
// Connect connects to a database using provided options.
//
// The returned DB is safe for concurrent use by multiple goroutines
// and maintains its own connection pool.
func Connect(opt *Options) *DB {
opt.init()
return &DB{
opt: opt,
pool: newConnPool(opt),
}
}
// DB is a database handle representing a pool of zero or more
// underlying connections. It's safe for concurrent use by multiple
// goroutines.
type DB struct {
opt *Options
pool *pool.ConnPool
}
// Options returns read-only Options that were used to connect to the DB.
func (db *DB) Options() *Options {
return db.opt
}
// WithTimeout returns a DB that uses d as the read/write timeout.
func (db *DB) WithTimeout(d time.Duration) *DB {
newopt := *db.opt
newopt.ReadTimeout = d
newopt.WriteTimeout = d
return &DB{
opt: &newopt,
pool: db.pool,
}
}
func (db *DB) conn() (*pool.Conn, error) {
cn, err := db.pool.Get()
if err != nil {
return nil, err
}
if !cn.Inited {
if err := db.initConn(cn); err != nil {
_ = db.pool.Remove(cn, err)
return nil, err
}
}
cn.SetReadTimeout(db.opt.ReadTimeout)
cn.SetWriteTimeout(db.opt.WriteTimeout)
return cn, nil
}
func (db *DB) initConn(cn *pool.Conn) error {
if db.opt.SSL || db.opt.TLSConfig != nil {
if err := enableSSL(cn, db.opt.TLSConfig); err != nil {
return err
}
}
err := startup(cn, db.opt.User, db.opt.Password, db.opt.Database)
if err != nil {
return err
}
if err := setParams(cn, db.opt.Params); err != nil {
return err
}
cn.Inited = true
return nil
}
func (db *DB) freeConn(cn *pool.Conn, err error) error {
if !isBadConn(err, false) {
return db.pool.Put(cn)
}
return db.pool.Remove(cn, err)
}
// Close closes the database client, releasing any open resources.
//
// 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 {
st := db.pool.Stats()
if st.TotalConns != st.FreeConns {
internal.Logf(
"connection leaking detected: total_conns=%d free_conns=%d",
st.TotalConns, st.FreeConns,
)
}
return db.pool.Close()
}
// Exec executes a query ignoring returned rows. The params are for any
// placeholder parameters in the query.
func (db *DB) Exec(query interface{}, params ...interface{}) (res *types.Result, err error) {
for i := 0; ; i++ {
var cn *pool.Conn
cn, err = db.conn()
if err != nil {
return nil, err
}
res, err = simpleQuery(cn, query, params...)
db.freeConn(cn, err)
if i >= db.opt.MaxRetries {
return res, err
}
if !shouldRetry(err) {
return res, err
}
time.Sleep(internal.RetryBackoff << uint(i))
}
return
}
// ExecOne acts like Exec, but query must affect only one row. It
// returns ErrNoRows error when query returns zero rows or
// ErrMultiRows when query returns multiple rows.
func (db *DB) ExecOne(query interface{}, params ...interface{}) (*types.Result, error) {
res, err := db.Exec(query, params...)
if err != nil {
return nil, err
}
return assertOneAffected(res)
}
// Query executes a query that returns rows, typically a SELECT.
// The params are for any placeholder parameters in the query.
func (db *DB) Query(model, query interface{}, params ...interface{}) (res *types.Result, err error) {
for i := 0; i < 3; i++ {
var cn *pool.Conn
cn, err = db.conn()
if err != nil {
return nil, err
}
res, err = simpleQueryData(db, cn, model, query, params...)
db.freeConn(cn, err)
if i >= db.opt.MaxRetries {
return res, err
}
if !shouldRetry(err) {
return res, err
}
time.Sleep(internal.RetryBackoff << uint(i))
}
return
}
// QueryOne acts like Query, but query must return only one row. It
// returns ErrNoRows error when query returns zero rows or
// ErrMultiRows when query returns multiple rows.
func (db *DB) QueryOne(model, query interface{}, params ...interface{}) (*types.Result, error) {
mod, err := newSingleModel(model)
if err != nil {
return nil, err
}
res, err := db.Query(mod, query, params...)
if err != nil {
return nil, err
}
return assertOneAffected(res)
}
// Listen listens for notifications sent by NOTIFY statement.
func (db *DB) Listen(channels ...string) (*Listener, error) {
l := &Listener{
db: db,
}
if err := l.Listen(channels...); err != nil {
l.Close()
return nil, err
}
return l, nil
}
// CopyFrom copies data from reader to a table.
func (db *DB) CopyFrom(reader io.Reader, query interface{}, params ...interface{}) (*types.Result, error) {
cn, err := db.conn()
if err != nil {
return nil, err
}
res, err := copyFrom(cn, reader, query, params...)
if err != nil {
db.freeConn(cn, err)
return nil, err
}
db.pool.Put(cn)
return res, nil
}
// CopyTo copies data from a table to writer.
func (db *DB) CopyTo(writer io.Writer, query interface{}, params ...interface{}) (*types.Result, error) {
cn, err := db.conn()
if err != nil {
return nil, err
}
if err := writeQueryMsg(cn.Wr, query, params...); err != nil {
db.pool.Put(cn)
return nil, err
}
if err := cn.Wr.Flush(); err != nil {
db.freeConn(cn, err)
return nil, err
}
if err := readCopyOutResponse(cn); err != nil {
db.freeConn(cn, err)
return nil, err
}
res, err := readCopyData(cn, writer)
if err != nil {
db.freeConn(cn, err)
return nil, err
}
db.pool.Put(cn)
return res, nil
}
// Model returns new query for the model.
func (db *DB) Model(model ...interface{}) *orm.Query {
return orm.NewQuery(db, model...)
}
// Select selects the model by primary key.
func (db *DB) Select(model interface{}) error {
return orm.Select(db, model)
}
// Create inserts the model updating primary keys if they are empty.
func (db *DB) Create(model ...interface{}) error {
return orm.Create(db, model...)
}
// Update updates the model by primary key.
func (db *DB) Update(model interface{}) error {
return orm.Update(db, model)
}
// Delete deletes the model by primary key.
func (db *DB) Delete(model interface{}) error {
return orm.Delete(db, model)
}
func (db *DB) FormatQuery(dst []byte, query string, params ...interface{}) []byte {
return orm.Formatter{}.Append(dst, query, params...)
}
func setParams(cn *pool.Conn, params map[string]interface{}) error {
for key, value := range params {
_, err := simpleQuery(cn, "SET ? = ?", F(key), value)
if err != nil {
return err
}
}
return nil
}
func (db *DB) cancelRequest(processId, secretKey int32) error {
cn, err := db.pool.NewConn()
if err != nil {
return err
}
writeCancelRequestMsg(cn.Wr, processId, secretKey)
if err = cn.Wr.Flush(); err != nil {
return err
}
cn.Close()
return nil
}
func simpleQuery(cn *pool.Conn, query interface{}, params ...interface{}) (*types.Result, error) {
if err := writeQueryMsg(cn.Wr, query, params...); err != nil {
return nil, err
}
if err := cn.Wr.Flush(); err != nil {
return nil, err
}
return readSimpleQuery(cn)
}
func simpleQueryData(db orm.DB, cn *pool.Conn, model, query interface{}, params ...interface{}) (*types.Result, error) {
if err := writeQueryMsg(cn.Wr, query, params...); err != nil {
return nil, err
}
if err := cn.Wr.Flush(); err != nil {
return nil, err
}
return readSimpleQueryData(db, cn, model)
}
type singleModel struct {
orm.Model
}
var _ orm.Collection = (*singleModel)(nil)
func newSingleModel(mod interface{}) (*singleModel, error) {
model, ok := mod.(orm.Model)
if !ok {
var err error
model, err = orm.NewModel(mod)
if err != nil {
return nil, err
}
}
return &singleModel{
Model: model,
}, nil
}
func (m *singleModel) AddModel(db orm.DB, model orm.ColumnScanner) error {
return m.Model.AddModel(db, model)
}
func assertOne(l int) error {
switch {
case l == 0:
return ErrNoRows
case l > 1:
return ErrMultiRows
default:
return nil
}
}
func assertOneAffected(res *types.Result) (*types.Result, error) {
if err := assertOne(res.Affected()); err != nil {
return nil, err
}
return res, nil
}
func copyFrom(cn *pool.Conn, r io.Reader, query interface{}, params ...interface{}) (*types.Result, error) {
if err := writeQueryMsg(cn.Wr, query, params...); err != nil {
return nil, err
}
if err := cn.Wr.Flush(); err != nil {
return nil, err
}
if err := readCopyInResponse(cn); err != nil {
return nil, err
}
for {
if _, err := writeCopyData(cn.Wr, r); err != nil {
if err == io.EOF {
break
}
return nil, err
}
if err := cn.Wr.Flush(); err != nil {
return nil, err
}
}
writeCopyDone(cn.Wr)
if err := cn.Wr.Flush(); err != nil {
return nil, err
}
return readReadyForQuery(cn)
}