forked from go-pg/pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
412 lines (340 loc) · 9.15 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package pg
import (
"fmt"
"io"
"time"
"github.com/go-pg/pg/internal"
"github.com/go-pg/pg/internal/pool"
"github.com/go-pg/pg/orm"
)
// 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
fmter orm.Formatter
queryProcessedHooks []queryProcessedHook
}
var _ orm.DB = (*DB)(nil)
func (db *DB) String() string {
return fmt.Sprintf("DB<Addr=%q%s>", db.opt.Addr, db.fmter)
}
// 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,
fmter: db.fmter,
queryProcessedHooks: db.queryProcessedHooks[:len(db.queryProcessedHooks):len(db.queryProcessedHooks)],
}
}
// WithParam returns a DB that replaces the param with the value in queries.
func (db *DB) WithParam(param string, value interface{}) *DB {
return &DB{
opt: db.opt,
pool: db.pool,
fmter: db.fmter.WithParam(param, value),
queryProcessedHooks: db.queryProcessedHooks[:len(db.queryProcessedHooks):len(db.queryProcessedHooks)],
}
}
func (db *DB) conn() (*pool.Conn, error) {
cn, _, err := db.pool.Get()
if err != nil {
return nil, err
}
cn.SetReadWriteTimeout(db.opt.ReadTimeout, db.opt.WriteTimeout)
if cn.InitedAt.IsZero() {
if err := db.initConn(cn); err != nil {
_ = db.pool.Remove(cn)
return nil, err
}
cn.InitedAt = time.Now()
}
return cn, nil
}
func (db *DB) initConn(cn *pool.Conn) error {
if db.opt.TLSConfig != nil {
if err := enableSSL(cn, db.opt.TLSConfig); err != nil {
return err
}
}
return startup(cn, db.opt.User, db.opt.Password, db.opt.Database)
}
func (db *DB) freeConn(cn *pool.Conn, err error) error {
if !isBadConn(err, false) {
return db.pool.Put(cn)
}
return db.pool.Remove(cn)
}
func (db *DB) shouldRetry(err error) bool {
if err == nil {
return false
}
if pgerr, ok := err.(Error); ok {
switch pgerr.Field('C') {
case "40001": // serialization_failure
return true
case "55000": // attempted to delete invisible tuple
return true
case "57014": // statement_timeout
return db.opt.RetryStatementTimeout
default:
return false
}
}
return isNetworkError(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
// placeholders in the query.
func (db *DB) Exec(query interface{}, params ...interface{}) (res orm.Result, err error) {
for i := 0; i <= db.opt.MaxRetries; i++ {
var cn *pool.Conn
if i >= 1 {
time.Sleep(internal.RetryBackoff(i - 1))
}
cn, err = db.conn()
if err != nil {
continue
}
start := time.Now()
res, err = db.simpleQuery(cn, query, params...)
db.freeConn(cn, err)
db.queryProcessed(db, start, query, params, res, err)
if !db.shouldRetry(err) {
break
}
}
return res, err
}
// 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{}) (orm.Result, error) {
res, err := db.Exec(query, params...)
if err != nil {
return nil, err
}
if err := internal.AssertOneRow(res.RowsAffected()); err != nil {
return nil, err
}
return res, nil
}
// Query executes a query that returns rows, typically a SELECT.
// The params are for any placeholders in the query.
func (db *DB) Query(model, query interface{}, params ...interface{}) (res orm.Result, err error) {
for i := 0; i <= db.opt.MaxRetries; i++ {
var cn *pool.Conn
if i >= 1 {
time.Sleep(internal.RetryBackoff(i - 1))
}
cn, err = db.conn()
if err != nil {
continue
}
start := time.Now()
res, err = db.simpleQueryData(cn, model, query, params...)
db.freeConn(cn, err)
db.queryProcessed(db, start, query, params, res, err)
if !db.shouldRetry(err) {
break
}
}
if err != nil {
return nil, err
}
if mod := res.Model(); mod != nil && res.RowsReturned() > 0 {
if err = mod.AfterQuery(db); err != nil {
return res, err
}
}
return res, nil
}
// 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{}) (orm.Result, error) {
res, err := db.Query(model, query, params...)
if err != nil {
return nil, err
}
if err := internal.AssertOneRow(res.RowsAffected()); err != nil {
return nil, err
}
return res, nil
}
// Listen listens for notifications sent with NOTIFY command.
func (db *DB) Listen(channels ...string) *Listener {
ln := &Listener{
db: db,
}
_ = ln.Listen(channels...)
return ln
}
// CopyFrom copies data from reader to a table.
func (db *DB) CopyFrom(reader io.Reader, query interface{}, params ...interface{}) (orm.Result, error) {
cn, err := db.conn()
if err != nil {
return nil, err
}
res, err := db.copyFrom(cn, reader, query, params...)
db.freeConn(cn, err)
return res, err
}
// CopyTo copies data from a table to writer.
func (db *DB) CopyTo(writer io.Writer, query interface{}, params ...interface{}) (orm.Result, error) {
cn, err := db.conn()
if err != nil {
return nil, err
}
if err := writeQueryMsg(cn.Wr, db, query, params...); err != nil {
db.pool.Put(cn)
return nil, err
}
if err := cn.FlushWriter(); 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)
}
// Insert inserts the model updating primary keys if they are empty.
func (db *DB) Insert(model ...interface{}) error {
return orm.Insert(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)
}
// CreateTable creates table for the model. It recognizes following field tags:
// - notnull - sets NOT NULL constraint.
// - unique - sets UNIQUE constraint.
func (db *DB) CreateTable(model interface{}, opt *orm.CreateTableOptions) error {
_, err := orm.CreateTable(db, model, opt)
return err
}
func (db *DB) FormatQuery(dst []byte, query string, params ...interface{}) []byte {
return db.fmter.Append(dst, query, params...)
}
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.FlushWriter(); err != nil {
return err
}
cn.Close()
return nil
}
func (db *DB) simpleQuery(
cn *pool.Conn, query interface{}, params ...interface{},
) (orm.Result, error) {
if err := writeQueryMsg(cn.Wr, db, query, params...); err != nil {
return nil, err
}
if err := cn.FlushWriter(); err != nil {
return nil, err
}
res, err := readSimpleQuery(cn)
if err != nil {
return nil, err
}
return res, nil
}
func (db *DB) simpleQueryData(
cn *pool.Conn, model, query interface{}, params ...interface{},
) (orm.Result, error) {
if err := writeQueryMsg(cn.Wr, db, query, params...); err != nil {
return nil, err
}
if err := cn.FlushWriter(); err != nil {
return nil, err
}
res, err := readSimpleQueryData(cn, model)
if err != nil {
return nil, err
}
return res, nil
}
func (db *DB) copyFrom(cn *pool.Conn, r io.Reader, query interface{}, params ...interface{}) (orm.Result, error) {
if err := writeQueryMsg(cn.Wr, db, query, params...); err != nil {
return nil, err
}
if err := cn.FlushWriter(); 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.FlushWriter(); err != nil {
return nil, err
}
}
writeCopyDone(cn.Wr)
if err := cn.FlushWriter(); err != nil {
return nil, err
}
return readReadyForQuery(cn)
}