-
Notifications
You must be signed in to change notification settings - Fork 0
/
gopg.go
373 lines (327 loc) · 8.38 KB
/
gopg.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
package gopg
import (
"context"
"errors"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"github.com/go-pg/pg/v10/types"
"github.com/gopsql/db"
)
var (
// These functions are copied from the go-pg package, so that you don't
// have to import "github.com/go-pg/pg/v10/types".
TypesScan = types.Scan
TypesScanString = types.ScanString
TypesScanBytes = types.ScanBytes
TypesReadBytes = types.ReadBytes
TypesScanInt = types.ScanInt
TypesScanInt64 = types.ScanInt64
TypesScanUint64 = types.ScanUint64
TypesScanFloat32 = types.ScanFloat32
TypesScanFloat64 = types.ScanFloat64
TypesScanTime = types.ScanTime
TypesScanBool = types.ScanBool
rePosParam = regexp.MustCompile(`\$[0-9]+`)
)
type (
// types.Reader from go-pg package, so that you don't have to import it.
TypesReader = types.Reader
DB struct {
*pg.DB
}
Tx struct {
*pg.Tx
}
Result struct {
rowsAffected int64
}
queryRows struct {
db *DB
tx *Tx
ctx context.Context
query string
args []interface{}
mutex sync.Mutex
closed bool
destChan chan []interface{}
errChan chan error
nextChan chan bool
rowDest []interface{}
rowError error
}
queryRow struct {
db *DB
tx *Tx
ctx context.Context
query string
args []interface{}
}
)
var (
_ db.DB = (*DB)(nil)
_ db.Tx = (*Tx)(nil)
_ db.Result = (*Result)(nil)
_ db.Rows = (*queryRows)(nil)
_ db.Row = (*queryRow)(nil)
)
// MustOpen is like Open but panics if connect operation fails.
func MustOpen(conn string) db.DB {
c, err := Open(conn)
if err != nil {
panic(err)
}
return c
}
// Open creates and establishes one connection to database.
func Open(conn string) (db.DB, error) {
opt, err := pg.ParseURL(conn)
if err != nil {
return nil, err
}
db := pg.Connect(opt)
if err := db.Ping(context.Background()); err != nil {
return nil, err
}
return &DB{db}, nil
}
// Convert positional parameters (like $1 in "WHERE name = $1") to question
// marks ("?") used in go-pg.
func (d *DB) ConvertParameters(query string, args []interface{}) (outQuery string, outArgs []interface{}) {
outQuery = rePosParam.ReplaceAllStringFunc(query, func(in string) string {
pos, _ := strconv.Atoi(strings.TrimPrefix(in, "$"))
outArgs = append(outArgs, args[pos-1])
return "?"
})
return
}
func (d *DB) DriverName() string {
return "postgres"
}
func (d *DB) Exec(query string, args ...interface{}) (db.Result, error) {
return d.ExecContext(d.DB.Context(), query, args...)
}
func (d *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (db.Result, error) {
re, err := d.DB.ExecContext(ctx, query, args...)
if err != nil {
return nil, err
}
return &Result{
rowsAffected: int64(re.RowsAffected()),
}, nil
}
func (d *DB) Query(query string, args ...interface{}) (db.Rows, error) {
return d.QueryContext(d.DB.Context(), query, args...)
}
func (d *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (db.Rows, error) {
return &queryRows{
db: d,
ctx: ctx,
query: query,
args: args,
}, nil
}
func (d *DB) QueryRow(query string, args ...interface{}) db.Row {
return d.QueryRowContext(d.DB.Context(), query, args...)
}
func (d *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) db.Row {
return &queryRow{
db: d,
ctx: ctx,
query: query,
args: args,
}
}
func (d *DB) BeginTx(ctx context.Context, isolationLevel string, readOnly bool) (db.Tx, error) {
// TODO run Exec("SET TRANSACTION ...") here because go-pg doesn't have BeginTx(TxOptions)
tx, err := d.DB.BeginContext(ctx)
if err != nil {
return nil, err
}
return &Tx{tx}, nil
}
func (d *DB) ErrNoRows() error {
return pg.ErrNoRows
}
func (d *DB) ErrGetCode(err error) string {
if e, ok := err.(interface{ Field(byte) string }); ok {
return e.Field('C')
}
return "unknown"
}
func (t *Tx) ExecContext(ctx context.Context, query string, args ...interface{}) (db.Result, error) {
re, err := t.Tx.ExecContext(ctx, query, args...)
if err != nil {
return nil, err
}
return &Result{
rowsAffected: int64(re.RowsAffected()),
}, nil
}
func (t *Tx) QueryContext(ctx context.Context, query string, args ...interface{}) (db.Rows, error) {
return &queryRows{
tx: t,
ctx: ctx,
query: query,
args: args,
}, nil
}
func (t *Tx) QueryRowContext(ctx context.Context, query string, args ...interface{}) db.Row {
return &queryRow{
tx: t,
ctx: ctx,
query: query,
args: args,
}
}
func (t *Tx) Commit(ctx context.Context) error {
return t.Tx.CommitContext(ctx)
}
func (t *Tx) Rollback(ctx context.Context) error {
return t.Tx.RollbackContext(ctx)
}
func (r Result) RowsAffected() (int64, error) {
return r.rowsAffected, nil
}
func (q *queryRows) isClosed() bool {
q.mutex.Lock()
defer q.mutex.Unlock()
return q.closed
}
func (q *queryRows) Close() error {
q.mutex.Lock()
q.closed = true
q.mutex.Unlock()
if q.destChan != nil {
close(q.destChan)
}
if q.errChan != nil {
close(q.errChan)
}
if q.nextChan != nil {
close(q.nextChan)
}
return nil // step 13
}
func (q *queryRows) Columns() (columns []string, err error) {
var stmt *pg.Stmt
if q.tx != nil {
stmt, err = q.tx.Tx.Prepare(q.query)
} else {
stmt, err = q.db.DB.Prepare(q.query)
}
if err != nil {
return
}
defer func() {
if recover() != nil {
err = errors.New("failed to get columns")
}
}()
cols := reflect.ValueOf(*stmt).FieldByName("columns")
for i := 0; i < cols.Len(); i++ {
columns = append(columns, cols.Index(i).FieldByName("Name").String())
}
return
}
func (q *queryRows) Err() error {
if q.nextChan == nil { // no Next() called
return nil
}
return <-q.errChan // step 12
}
// Since go-pg doesn't use something like Go's database/sql.DB.Query, so we
// need to use channels to make it work with db.DB:
// rows, _ := db.Query()
// defer rows.Close()
// for rows.Next() {
// rows.Scan(...)
// }
// rows.Err()
// The "queryRows" implements go-pg's orm model functions and acts like a model
// for go-pg. When rows.Next() is called for the first time, go-pg's Query()
// function will be executed in a new goroutine. The rows.Next() function
// returns true every time when BeforeScan() is called (only when Query() has
// rows to return), returns false once go-pg's Query() function finishes. When
// rows.Next() returns true, rows.Scan() will be called, and all destination
// pointers of rows.Scan() will pass to ScanColumn(). When a row finishes
// scanning, AfterScan() is called.
func (q *queryRows) Next() bool {
if q.nextChan == nil { // step 0
q.destChan = make(chan []interface{}, 1)
q.errChan = make(chan error, 1)
q.nextChan = make(chan bool, 1)
go func() {
var err error
if q.tx != nil {
_, err = q.tx.Tx.QueryContext(q.ctx, q, q.query, q.args...)
} else {
_, err = q.db.DB.QueryContext(q.ctx, q, q.query, q.args...) // step 1
}
if !q.isClosed() {
q.nextChan <- false // step 9
q.errChan <- err // step 11
}
}()
}
select {
case next := <-q.nextChan: // step 3, 10
return next
case <-time.After(1 * time.Second):
panic("timed out: you must call Scan() after Next()")
}
}
func (q *queryRows) Scan(dest ...interface{}) (err error) {
if q.isClosed() {
return
}
q.destChan <- dest // step 4
err = <-q.errChan // step 8
return
}
// orm.HooklessModel interface
func (q *queryRows) Init() error { return nil }
func (q *queryRows) NextColumnScanner() orm.ColumnScanner { return q }
func (q queryRows) AddColumnScanner(orm.ColumnScanner) error { return nil }
// for every row
func (q *queryRows) BeforeScan(c context.Context) error {
if q.isClosed() {
return nil
}
q.nextChan <- true // step 2
q.rowDest = <-q.destChan // step 5
q.rowError = nil
return nil
}
// for every column
func (q *queryRows) ScanColumn(col types.ColumnInfo, rd types.Reader, n int) error {
if q.isClosed() {
return nil
}
err := types.Scan(q.rowDest[col.Index], rd, n) // step 6
if q.rowError == nil {
q.rowError = err
}
return nil
}
// for every row
func (q *queryRows) AfterScan(c context.Context) error {
if q.isClosed() {
return nil
}
q.errChan <- q.rowError // step 7
return q.rowError
}
func (q *queryRow) Scan(dest ...interface{}) (err error) {
if q.tx != nil {
_, err = q.tx.Tx.QueryOneContext(q.ctx, pg.Scan(dest...), q.query, q.args...)
} else {
_, err = q.db.DB.QueryOneContext(q.ctx, pg.Scan(dest...), q.query, q.args...)
}
return
}