forked from doug-martin/goqu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
658 lines (594 loc) · 20.5 KB
/
database.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
package goqu
import (
"context"
"database/sql"
"sync"
"github.com/doug-martin/goqu/v9/exec"
)
type (
Logger interface {
Printf(format string, v ...interface{})
}
// Interface for sql.DB, an interface is used so you can use with other
// libraries such as sqlx instead of the native sql.DB
SQLDatabase interface {
Begin() (*sql.Tx, error)
BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
}
// This struct is the wrapper for a Db. The struct delegates most calls to either an Exec instance or to the Db
// passed into the constructor.
Database struct {
logger Logger
dialect string
//nolint:stylecheck // keep for backwards compatibility
Db SQLDatabase
qf exec.QueryFactory
qfOnce sync.Once
}
)
// This is the common entry point into goqu.
//
// dialect: This is the adapter dialect, you should see your database adapter for the string to use. Built in adapters
// can be found at https://github.com/doug-martin/goqu/tree/master/adapters
//
// db: A sql.Db to use for querying the database
//
// import (
// "database/sql"
// "fmt"
// "github.com/doug-martin/goqu/v9"
// _ "github.com/doug-martin/goqu/v9/dialect/postgres"
// _ "github.com/lib/pq"
// )
//
// func main() {
// sqlDb, err := sql.Open("postgres", "user=postgres dbname=goqupostgres sslmode=disable ")
// if err != nil {
// panic(err.Error())
// }
// db := goqu.New("postgres", sqlDb)
// }
//
// The most commonly used Database method is From, which creates a new Dataset that uses the correct adapter and
// supports queries.
//
// var ids []uint32
// if err := db.From("items").Where(goqu.I("id").Gt(10)).Pluck("id", &ids); err != nil {
// panic(err.Error())
// }
// fmt.Printf("%+v", ids)
func newDatabase(dialect string, db SQLDatabase) *Database {
return &Database{
logger: nil,
dialect: dialect,
Db: db,
qf: nil,
qfOnce: sync.Once{},
}
}
// returns this databases dialect
func (d *Database) Dialect() string {
return d.dialect
}
// Starts a new Transaction.
func (d *Database) Begin() (*TxDatabase, error) {
sqlTx, err := d.Db.Begin()
if err != nil {
return nil, err
}
tx := NewTx(d.dialect, sqlTx)
tx.Logger(d.logger)
return tx, nil
}
// Starts a new Transaction. See sql.DB#BeginTx for option description
func (d *Database) BeginTx(ctx context.Context, opts *sql.TxOptions) (*TxDatabase, error) {
sqlTx, err := d.Db.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
tx := NewTx(d.dialect, sqlTx)
tx.Logger(d.logger)
return tx, nil
}
// WithTx starts a new transaction and executes it in Wrap method
func (d *Database) WithTx(fn func(*TxDatabase) error) error {
tx, err := d.Begin()
if err != nil {
return err
}
return tx.Wrap(func() error { return fn(tx) })
}
// Creates a new Dataset that uses the correct adapter and supports queries.
//
// var ids []uint32
// if err := db.From("items").Where(goqu.I("id").Gt(10)).Pluck("id", &ids); err != nil {
// panic(err.Error())
// }
// fmt.Printf("%+v", ids)
//
// from...: Sources for you dataset, could be table names (strings), a goqu.Literal or another goqu.Dataset
func (d *Database) From(from ...interface{}) *SelectDataset {
return newDataset(d.dialect, d.queryFactory()).From(from...)
}
func (d *Database) Select(cols ...interface{}) *SelectDataset {
return newDataset(d.dialect, d.queryFactory()).Select(cols...)
}
func (d *Database) Update(table interface{}) *UpdateDataset {
return newUpdateDataset(d.dialect, d.queryFactory()).Table(table)
}
func (d *Database) Insert(table interface{}) *InsertDataset {
return newInsertDataset(d.dialect, d.queryFactory()).Into(table)
}
func (d *Database) Delete(table interface{}) *DeleteDataset {
return newDeleteDataset(d.dialect, d.queryFactory()).From(table)
}
func (d *Database) Truncate(table ...interface{}) *TruncateDataset {
return newTruncateDataset(d.dialect, d.queryFactory()).Table(table...)
}
// Sets the logger for to use when logging queries
func (d *Database) Logger(logger Logger) {
d.logger = logger
}
// Logs a given operation with the specified sql and arguments
func (d *Database) Trace(op, sqlString string, args ...interface{}) {
if d.logger != nil {
if sqlString != "" {
if len(args) != 0 {
d.logger.Printf("[goqu] %s [query:=`%s` args:=%+v]", op, sqlString, args)
} else {
d.logger.Printf("[goqu] %s [query:=`%s`]", op, sqlString)
}
} else {
d.logger.Printf("[goqu] %s", op)
}
}
}
// Uses the db to Execute the query with arguments and return the sql.Result
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) Exec(query string, args ...interface{}) (sql.Result, error) {
return d.ExecContext(context.Background(), query, args...)
}
// Uses the db to Execute the query with arguments and return the sql.Result
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
d.Trace("EXEC", query, args...)
return d.Db.ExecContext(ctx, query, args...)
}
// Can be used to prepare a query.
//
// You can use this in tandem with a dataset by doing the following.
//
// sql, args, err := db.From("items").Where(goqu.I("id").Gt(10)).ToSQL(true)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// stmt, err := db.Prepare(sql)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// defer stmt.Close()
// rows, err := stmt.Query(args)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// defer rows.Close()
// for rows.Next(){
// //scan your rows
// }
// if rows.Err() != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
//
// query: The SQL statement to prepare.
func (d *Database) Prepare(query string) (*sql.Stmt, error) {
return d.PrepareContext(context.Background(), query)
}
// Can be used to prepare a query.
//
// You can use this in tandem with a dataset by doing the following.
//
// sql, args, err := db.From("items").Where(goqu.I("id").Gt(10)).ToSQL(true)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// stmt, err := db.Prepare(sql)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// defer stmt.Close()
// rows, err := stmt.QueryContext(ctx, args)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// defer rows.Close()
// for rows.Next(){
// //scan your rows
// }
// if rows.Err() != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
//
// query: The SQL statement to prepare.
func (d *Database) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) {
d.Trace("PREPARE", query)
return d.Db.PrepareContext(ctx, query)
}
// Used to query for multiple rows.
//
// You can use this in tandem with a dataset by doing the following.
//
// sql, err := db.From("items").Where(goqu.I("id").Gt(10)).ToSQL()
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// rows, err := stmt.Query(args)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// defer rows.Close()
// for rows.Next(){
// //scan your rows
// }
// if rows.Err() != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) Query(query string, args ...interface{}) (*sql.Rows, error) {
return d.QueryContext(context.Background(), query, args...)
}
// Used to query for multiple rows.
//
// You can use this in tandem with a dataset by doing the following.
//
// sql, err := db.From("items").Where(goqu.I("id").Gt(10)).ToSQL()
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// rows, err := stmt.QueryContext(ctx, args)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// defer rows.Close()
// for rows.Next(){
// //scan your rows
// }
// if rows.Err() != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
d.Trace("QUERY", query, args...)
return d.Db.QueryContext(ctx, query, args...)
}
// Used to query for a single row.
//
// You can use this in tandem with a dataset by doing the following.
//
// sql, err := db.From("items").Where(goqu.I("id").Gt(10)).Limit(1).ToSQL()
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// rows, err := stmt.QueryRow(args)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// //scan your row
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) QueryRow(query string, args ...interface{}) *sql.Row {
return d.QueryRowContext(context.Background(), query, args...)
}
// Used to query for a single row.
//
// You can use this in tandem with a dataset by doing the following.
//
// sql, err := db.From("items").Where(goqu.I("id").Gt(10)).Limit(1).ToSQL()
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// rows, err := stmt.QueryRowContext(ctx, args)
// if err != nil{
// panic(err.Error()) //you could gracefully handle the error also
// }
// //scan your row
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
d.Trace("QUERY ROW", query, args...)
return d.Db.QueryRowContext(ctx, query, args...)
}
func (d *Database) queryFactory() exec.QueryFactory {
d.qfOnce.Do(func() {
d.qf = exec.NewQueryFactory(d)
})
return d.qf
}
// Queries the database using the supplied query, and args and uses CrudExec.ScanStructs to scan the results into a
// slice of structs
//
// i: A pointer to a slice of structs
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) ScanStructs(i interface{}, query string, args ...interface{}) error {
return d.ScanStructsContext(context.Background(), i, query, args...)
}
// Queries the database using the supplied context, query, and args and uses CrudExec.ScanStructsContext to scan the
// results into a slice of structs
//
// i: A pointer to a slice of structs
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) ScanStructsContext(ctx context.Context, i interface{}, query string, args ...interface{}) error {
return d.queryFactory().FromSQL(query, args...).ScanStructsContext(ctx, i)
}
// Queries the database using the supplied query, and args and uses CrudExec.ScanStruct to scan the results into a
// struct
//
// i: A pointer to a struct
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) ScanStruct(i interface{}, query string, args ...interface{}) (bool, error) {
return d.ScanStructContext(context.Background(), i, query, args...)
}
// Queries the database using the supplied context, query, and args and uses CrudExec.ScanStructContext to scan the
// results into a struct
//
// i: A pointer to a struct
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) ScanStructContext(ctx context.Context, i interface{}, query string, args ...interface{}) (bool, error) {
return d.queryFactory().FromSQL(query, args...).ScanStructContext(ctx, i)
}
// Queries the database using the supplied query, and args and uses CrudExec.ScanVals to scan the results into a slice
// of primitive values
//
// i: A pointer to a slice of primitive values
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) ScanVals(i interface{}, query string, args ...interface{}) error {
return d.ScanValsContext(context.Background(), i, query, args...)
}
// Queries the database using the supplied context, query, and args and uses CrudExec.ScanValsContext to scan the
// results into a slice of primitive values
//
// i: A pointer to a slice of primitive values
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) ScanValsContext(ctx context.Context, i interface{}, query string, args ...interface{}) error {
return d.queryFactory().FromSQL(query, args...).ScanValsContext(ctx, i)
}
// Queries the database using the supplied query, and args and uses CrudExec.ScanVal to scan the results into a
// primitive value
//
// i: A pointer to a primitive value
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) ScanVal(i interface{}, query string, args ...interface{}) (bool, error) {
return d.ScanValContext(context.Background(), i, query, args...)
}
// Queries the database using the supplied context, query, and args and uses CrudExec.ScanValContext to scan the
// results into a primitive value
//
// i: A pointer to a primitive value
//
// query: The SQL to execute
//
// args...: for any placeholder parameters in the query
func (d *Database) ScanValContext(ctx context.Context, i interface{}, query string, args ...interface{}) (bool, error) {
return d.queryFactory().FromSQL(query, args...).ScanValContext(ctx, i)
}
// A wrapper around a sql.Tx and works the same way as Database
type (
// Interface for sql.Tx, an interface is used so you can use with other
// libraries such as sqlx instead of the native sql.DB
SQLTx interface {
ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
Commit() error
Rollback() error
}
TxDatabase struct {
logger Logger
dialect string
Tx SQLTx
qf exec.QueryFactory
qfOnce sync.Once
}
)
// Creates a new TxDatabase
func NewTx(dialect string, tx SQLTx) *TxDatabase {
return &TxDatabase{dialect: dialect, Tx: tx}
}
// returns this databases dialect
func (td *TxDatabase) Dialect() string {
return td.dialect
}
// Creates a new Dataset for querying a Database.
func (td *TxDatabase) From(cols ...interface{}) *SelectDataset {
return newDataset(td.dialect, td.queryFactory()).From(cols...)
}
func (td *TxDatabase) Select(cols ...interface{}) *SelectDataset {
return newDataset(td.dialect, td.queryFactory()).Select(cols...)
}
func (td *TxDatabase) Update(table interface{}) *UpdateDataset {
return newUpdateDataset(td.dialect, td.queryFactory()).Table(table)
}
func (td *TxDatabase) Insert(table interface{}) *InsertDataset {
return newInsertDataset(td.dialect, td.queryFactory()).Into(table)
}
func (td *TxDatabase) Delete(table interface{}) *DeleteDataset {
return newDeleteDataset(td.dialect, td.queryFactory()).From(table)
}
func (td *TxDatabase) Truncate(table ...interface{}) *TruncateDataset {
return newTruncateDataset(td.dialect, td.queryFactory()).Table(table...)
}
// Sets the logger
func (td *TxDatabase) Logger(logger Logger) {
td.logger = logger
}
func (td *TxDatabase) Trace(op, sqlString string, args ...interface{}) {
if td.logger != nil {
if sqlString != "" {
if len(args) != 0 {
td.logger.Printf("[goqu - transaction] %s [query:=`%s` args:=%+v] ", op, sqlString, args)
} else {
td.logger.Printf("[goqu - transaction] %s [query:=`%s`] ", op, sqlString)
}
} else {
td.logger.Printf("[goqu - transaction] %s", op)
}
}
}
// See Database#Exec
func (td *TxDatabase) Exec(query string, args ...interface{}) (sql.Result, error) {
return td.ExecContext(context.Background(), query, args...)
}
// See Database#ExecContext
func (td *TxDatabase) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) {
td.Trace("EXEC", query, args...)
return td.Tx.ExecContext(ctx, query, args...)
}
// See Database#Prepare
func (td *TxDatabase) Prepare(query string) (*sql.Stmt, error) {
return td.PrepareContext(context.Background(), query)
}
// See Database#PrepareContext
func (td *TxDatabase) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) {
td.Trace("PREPARE", query)
return td.Tx.PrepareContext(ctx, query)
}
// See Database#Query
func (td *TxDatabase) Query(query string, args ...interface{}) (*sql.Rows, error) {
return td.QueryContext(context.Background(), query, args...)
}
// See Database#QueryContext
func (td *TxDatabase) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) {
td.Trace("QUERY", query, args...)
return td.Tx.QueryContext(ctx, query, args...)
}
// See Database#QueryRow
func (td *TxDatabase) QueryRow(query string, args ...interface{}) *sql.Row {
return td.QueryRowContext(context.Background(), query, args...)
}
// See Database#QueryRowContext
func (td *TxDatabase) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row {
td.Trace("QUERY ROW", query, args...)
return td.Tx.QueryRowContext(ctx, query, args...)
}
func (td *TxDatabase) queryFactory() exec.QueryFactory {
td.qfOnce.Do(func() {
td.qf = exec.NewQueryFactory(td)
})
return td.qf
}
// See Database#ScanStructs
func (td *TxDatabase) ScanStructs(i interface{}, query string, args ...interface{}) error {
return td.ScanStructsContext(context.Background(), i, query, args...)
}
// See Database#ScanStructsContext
func (td *TxDatabase) ScanStructsContext(ctx context.Context, i interface{}, query string, args ...interface{}) error {
return td.queryFactory().FromSQL(query, args...).ScanStructsContext(ctx, i)
}
// See Database#ScanStruct
func (td *TxDatabase) ScanStruct(i interface{}, query string, args ...interface{}) (bool, error) {
return td.ScanStructContext(context.Background(), i, query, args...)
}
// See Database#ScanStructContext
func (td *TxDatabase) ScanStructContext(ctx context.Context, i interface{}, query string, args ...interface{}) (bool, error) {
return td.queryFactory().FromSQL(query, args...).ScanStructContext(ctx, i)
}
// See Database#ScanVals
func (td *TxDatabase) ScanVals(i interface{}, query string, args ...interface{}) error {
return td.ScanValsContext(context.Background(), i, query, args...)
}
// See Database#ScanValsContext
func (td *TxDatabase) ScanValsContext(ctx context.Context, i interface{}, query string, args ...interface{}) error {
return td.queryFactory().FromSQL(query, args...).ScanValsContext(ctx, i)
}
// See Database#ScanVal
func (td *TxDatabase) ScanVal(i interface{}, query string, args ...interface{}) (bool, error) {
return td.ScanValContext(context.Background(), i, query, args...)
}
// See Database#ScanValContext
func (td *TxDatabase) ScanValContext(ctx context.Context, i interface{}, query string, args ...interface{}) (bool, error) {
return td.queryFactory().FromSQL(query, args...).ScanValContext(ctx, i)
}
// COMMIT the transaction
func (td *TxDatabase) Commit() error {
td.Trace("COMMIT", "")
return td.Tx.Commit()
}
// ROLLBACK the transaction
func (td *TxDatabase) Rollback() error {
td.Trace("ROLLBACK", "")
return td.Tx.Rollback()
}
// A helper method that will automatically COMMIT or ROLLBACK once the supplied function is done executing
//
// tx, err := db.Begin()
// if err != nil{
// panic(err.Error()) // you could gracefully handle the error also
// }
// if err := tx.Wrap(func() error{
// if _, err := tx.From("test").Insert(Record{"a":1, "b": "b"}).Exec(){
// // this error will be the return error from the Wrap call
// return err
// }
// return nil
// }); err != nil{
// panic(err.Error()) // you could gracefully handle the error also
// }
func (td *TxDatabase) Wrap(fn func() error) (err error) {
defer func() {
if p := recover(); p != nil {
_ = td.Rollback()
panic(p)
}
if err != nil {
if rollbackErr := td.Rollback(); rollbackErr != nil {
err = rollbackErr
}
} else {
if commitErr := td.Commit(); commitErr != nil {
err = commitErr
}
}
}()
return fn()
}