-
Notifications
You must be signed in to change notification settings - Fork 101
/
qbs.go
776 lines (725 loc) · 20.5 KB
/
qbs.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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
package qbs
import (
"database/sql"
"errors"
"fmt"
"log"
"os"
"reflect"
"strings"
"sync"
"time"
)
var driver, driverSource, dbName string
var dial Dialect
var connectionLimit chan struct{}
var blockingOnLimit bool
var ConnectionLimitError = errors.New("Connection limit reached")
var db *sql.DB
var stmtMap map[string]*sql.Stmt
var mu *sync.RWMutex
var queryLogger *log.Logger = log.New(os.Stdout, "qbs:", log.LstdFlags)
var errorLogger *log.Logger = log.New(os.Stderr, "qbs:", log.LstdFlags)
type Qbs struct {
Dialect Dialect
Log bool //Set to true to print out sql statement.
tx *sql.Tx
txStmtMap map[string]*sql.Stmt
criteria *criteria
firstTxError error
}
type Validator interface {
Validate(*Qbs) error
}
//Register a database, should be call at the beginning of the application.
func Register(driverName, driverSourceName, databaseName string, dialect Dialect) {
driverSource = driverSourceName
dbName = databaseName
if db == nil {
var err error
var database *sql.DB
database, err = sql.Open(driverName, driverSource)
if err != nil {
panic(err)
}
RegisterWithDb(driverName, database, dialect)
}
}
func RegisterWithDb(driverName string, database *sql.DB, dialect Dialect) {
driver = driverName
dial = dialect
db = database
db.SetMaxIdleConns(100)
stmtMap = make(map[string]*sql.Stmt)
mu = new(sync.RWMutex)
}
//A safe and easy way to work with *Qbs instance without the need to open and close it.
func WithQbs(task func(*Qbs) error) error {
q, err := GetQbs()
if err != nil {
return err
}
defer q.Close()
return task(q)
}
//Get an Qbs instance, should call `defer q.Close()` next, like:
//
// q, err := qbs.GetQbs()
// if err != nil {
// fmt.Println(err)
// return
// }
// defer q.Close()
// ...
//
func GetQbs() (q *Qbs, err error) {
if driver == "" || dial == nil {
panic("database driver has not been registered, should call Register first.")
}
if connectionLimit != nil {
if blockingOnLimit {
connectionLimit <- struct{}{}
} else {
select {
case connectionLimit <- struct{}{}:
default:
return nil, ConnectionLimitError
}
}
}
q = new(Qbs)
q.Dialect = dial
q.criteria = new(criteria)
return q, nil
}
//The default connection pool size is 100.
func ChangePoolSize(size int) {
db.SetMaxIdleConns(size)
}
func SetLogger(query *log.Logger, err *log.Logger) {
queryLogger = query
errorLogger = err
}
//Set the connection limit, there is no limit by default.
//If blocking is true, GetQbs method will be blocked, otherwise returns ConnectionLimitError.
func SetConnectionLimit(maxCon int, blocking bool) {
if maxCon > 0 {
connectionLimit = make(chan struct{}, maxCon)
} else if maxCon < 0 {
connectionLimit = nil
}
blockingOnLimit = blocking
}
// Create a new criteria for subsequent query
func (q *Qbs) Reset() {
q.criteria = new(criteria)
}
// Begin create a transaction object internally
// You can perform queries with the same Qbs object
// no matter it is in transaction or not.
// It panics if it's already in a transaction.
func (q *Qbs) Begin() error {
if q.tx != nil {
panic("cannot start nested transaction")
}
tx, err := db.Begin()
q.tx = tx
q.txStmtMap = make(map[string]*sql.Stmt)
return err
}
func (q *Qbs) InTransaction() bool {
return q.tx != nil
}
func (q *Qbs) updateTxError(e error) error {
if e != nil {
if errorLogger != nil {
errorLogger.Println(e)
}
// don't shadow the first error
if q.firstTxError == nil {
q.firstTxError = e
}
}
return e
}
// Commit commits a started transaction and will report the first error that
// occurred inside the transaction.
func (q *Qbs) Commit() error {
err := q.tx.Commit()
q.updateTxError(err)
q.tx = nil
for _, v := range q.txStmtMap {
v.Close()
}
q.txStmtMap = nil
return q.firstTxError
}
// Rollback rolls back a started transaction.
func (q *Qbs) Rollback() error {
err := q.tx.Rollback()
q.tx = nil
for _, v := range q.txStmtMap {
v.Close()
}
q.txStmtMap = nil
return q.updateTxError(err)
}
// Where is a shortcut method to call Condtion(NewCondtition(expr, args...)).
func (q *Qbs) Where(expr string, args ...interface{}) *Qbs {
q.criteria.condition = NewCondition(expr, args...)
return q
}
//Snakecase column name
func (q *Qbs) WhereEqual(column string, value interface{}) *Qbs {
q.criteria.condition = NewEqualCondition(column, value)
return q
}
func (q *Qbs) WhereIn(column string, values []interface{}) *Qbs {
q.criteria.condition = NewInCondition(column, values)
return q
}
//Condition defines the SQL "WHERE" clause
//If other condition can be inferred by the struct argument in
//Find method, it will be merged with AND
func (q *Qbs) Condition(condition *Condition) *Qbs {
q.criteria.condition = condition
return q
}
func (q *Qbs) Limit(limit int) *Qbs {
q.criteria.limit = limit
return q
}
func (q *Qbs) Offset(offset int) *Qbs {
q.criteria.offset = offset
return q
}
func (q *Qbs) OrderBy(path string) *Qbs {
q.criteria.orderBys = append(q.criteria.orderBys, order{q.Dialect.quote(path), false})
return q
}
func (q *Qbs) OrderByDesc(path string) *Qbs {
q.criteria.orderBys = append(q.criteria.orderBys, order{q.Dialect.quote(path), true})
return q
}
// Camel case field names
func (q *Qbs) OmitFields(fieldName ...string) *Qbs {
q.criteria.omitFields = fieldName
return q
}
func (q *Qbs) OmitJoin() *Qbs {
q.criteria.omitJoin = true
return q
}
// Perform select query by parsing the struct's type and then fill the values into the struct
// All fields of supported types in the struct will be added in select clause.
// If Id value is provided, it will be added into the where clause
// If a foreign key field with its referenced struct pointer field are provided,
// It will perform a join query, the referenced struct pointer field will be filled in
// the values obtained by the query.
// If not found, "sql.ErrNoRows" will be returned.
func (q *Qbs) Find(structPtr interface{}) error {
q.criteria.model = structPtrToModel(structPtr, !q.criteria.omitJoin, q.criteria.omitFields)
q.criteria.limit = 1
if !q.criteria.model.pkZero() {
idPath := q.Dialect.quote(q.criteria.model.table) + "." + q.Dialect.quote(q.criteria.model.pk.name)
idCondition := NewCondition(idPath+" = ?", q.criteria.model.pk.value)
if q.criteria.condition == nil {
q.criteria.condition = idCondition
} else {
q.criteria.condition = idCondition.AndCondition(q.criteria.condition)
}
}
query, args := q.Dialect.querySql(q.criteria)
return q.doQueryRow(structPtr, query, args...)
}
// Similar to Find, except that FindAll accept pointer of slice of struct pointer,
// rows will be appended to the slice.
func (q *Qbs) FindAll(ptrOfSliceOfStructPtr interface{}) error {
strucType := reflect.TypeOf(ptrOfSliceOfStructPtr).Elem().Elem().Elem()
strucPtr := reflect.New(strucType).Interface()
q.criteria.model = structPtrToModel(strucPtr, !q.criteria.omitJoin, q.criteria.omitFields)
query, args := q.Dialect.querySql(q.criteria)
return q.doQueryRows(ptrOfSliceOfStructPtr, query, args...)
}
func (q *Qbs) doQueryRow(out interface{}, query string, args ...interface{}) error {
defer q.Reset()
rowValue := reflect.ValueOf(out)
q.log(query, args...)
stmt, err := q.prepare(query)
if err != nil {
return q.updateTxError(err)
}
rows, err := stmt.Query(args...)
if err != nil {
return q.updateTxError(err)
}
defer rows.Close()
if rows.Next() {
err = q.scanRows(rowValue, rows)
if err != nil {
return err
}
} else {
return sql.ErrNoRows
}
return nil
}
func (q *Qbs) doQueryRows(out interface{}, query string, args ...interface{}) error {
defer q.Reset()
sliceValue := reflect.Indirect(reflect.ValueOf(out))
structType := sliceValue.Type().Elem().Elem()
q.log(query, args...)
stmt, err := q.prepare(query)
if err != nil {
return q.updateTxError(err)
}
rows, err := stmt.Query(args...)
if err != nil {
return q.updateTxError(err)
}
defer rows.Close()
for rows.Next() {
rowValue := reflect.New(structType)
err = q.scanRows(rowValue, rows)
if err != nil {
return err
}
sliceValue.Set(reflect.Append(sliceValue, rowValue))
}
return nil
}
func (q *Qbs) scanRows(rowValue reflect.Value, rows *sql.Rows) (err error) {
cols, _ := rows.Columns()
containers := make([]interface{}, 0, len(cols))
for i := 0; i < cap(containers); i++ {
var v interface{}
containers = append(containers, &v)
}
err = rows.Scan(containers...)
if err != nil {
return
}
for i, v := range containers {
value := reflect.Indirect(reflect.ValueOf(v))
if !value.Elem().IsValid() {
continue
}
key := cols[i]
paths := strings.Split(key, "___")
if len(paths) == 2 {
subStruct := rowValue.Elem().FieldByName(TableNameToStructName(paths[0]))
if subStruct.IsNil() {
subStruct.Set(reflect.New(subStruct.Type().Elem()))
}
subField := subStruct.Elem().FieldByName(ColumnNameToFieldName(paths[1]))
if subField.IsValid() {
err = q.Dialect.setModelValue(value, subField)
if err != nil {
return
}
}
} else {
field := rowValue.Elem().FieldByName(ColumnNameToFieldName(key))
if field.IsValid() {
err = q.Dialect.setModelValue(value, field)
if err != nil {
return
}
}
}
}
return
}
// Same as sql.Db.Exec or sql.Tx.Exec depends on if transaction has began
func (q *Qbs) Exec(query string, args ...interface{}) (sql.Result, error) {
defer q.Reset()
query = q.Dialect.substituteMarkers(query)
q.log(query, args...)
stmt, err := q.prepare(query)
if err != nil {
return nil, q.updateTxError(err)
}
result, err := stmt.Exec(args...)
if err != nil {
return nil, q.updateTxError(err)
}
return result, nil
}
// Same as sql.Db.QueryRow or sql.Tx.QueryRow depends on if transaction has began
func (q *Qbs) QueryRow(query string, args ...interface{}) *sql.Row {
q.log(query, args...)
query = q.Dialect.substituteMarkers(query)
stmt, err := q.prepare(query)
if err != nil {
q.updateTxError(err)
return nil
}
return stmt.QueryRow(args...)
}
// Same as sql.Db.Query or sql.Tx.Query depends on if transaction has began
func (q *Qbs) Query(query string, args ...interface{}) (rows *sql.Rows, err error) {
q.log(query, args...)
query = q.Dialect.substituteMarkers(query)
stmt, err := q.prepare(query)
if err != nil {
q.updateTxError(err)
return
}
return stmt.Query(args...)
}
// Same as sql.Db.Prepare or sql.Tx.Prepare depends on if transaction has began
func (q *Qbs) prepare(query string) (stmt *sql.Stmt, err error) {
var ok bool
if q.tx != nil {
stmt, ok = q.txStmtMap[query]
if ok {
return
}
stmt, err = q.tx.Prepare(query)
if err != nil {
q.updateTxError(err)
return
}
q.txStmtMap[query] = stmt
} else {
mu.RLock()
stmt, ok = stmtMap[query]
mu.RUnlock()
if ok {
return
}
stmt, err = db.Prepare(query + ";")
if err != nil {
q.updateTxError(err)
return
}
mu.Lock()
stmtMap[query] = stmt
mu.Unlock()
}
return
}
// If Id value is not provided, save will insert the record, and the Id value will
// be filled in the struct after insertion.
// If Id value is provided, save will do a query count first to see if the row exists, if not then insert it,
// otherwise update it.
// If struct implements Validator interface, it will be validated first
func (q *Qbs) Save(structPtr interface{}) (affected int64, err error) {
if v, ok := structPtr.(Validator); ok {
err = v.Validate(q)
if err != nil {
return
}
}
model := structPtrToModel(structPtr, true, q.criteria.omitFields)
if model.pk == nil {
panic("no primary key field")
}
q.criteria.model = model
now := time.Now()
var id int64 = 0
updateModelField := model.timeField("updated")
if updateModelField != nil {
updateModelField.value = now
}
createdModelField := model.timeField("created")
var isInsert bool
if !model.pkZero() && q.WhereEqual(model.pk.name, model.pk.value).Count(model.table) > 0 { //id is given, can be an update operation.
affected, err = q.Dialect.update(q)
} else {
if createdModelField != nil {
createdModelField.value = now
}
id, err = q.Dialect.insert(q)
isInsert = true
if err == nil {
affected = 1
}
}
if err == nil {
structValue := reflect.Indirect(reflect.ValueOf(structPtr))
if _, ok := model.pk.value.(int64); ok && id != 0 {
idField := structValue.FieldByName(model.pk.camelName)
idField.SetInt(id)
}
if updateModelField != nil {
updateField := structValue.FieldByName(updateModelField.camelName)
updateField.Set(reflect.ValueOf(now))
}
if isInsert {
if createdModelField != nil {
createdField := structValue.FieldByName(createdModelField.camelName)
createdField.Set(reflect.ValueOf(now))
}
}
}
return affected, q.updateTxError(err)
}
func (q *Qbs) BulkInsert(sliceOfStructPtr interface{}) error {
defer q.Reset()
var err error
if q.tx == nil {
q.Begin()
defer func() {
if err != nil {
q.Rollback()
} else {
q.Commit()
}
}()
}
sliceValue := reflect.ValueOf(sliceOfStructPtr)
for i := 0; i < sliceValue.Len(); i++ {
structPtr := sliceValue.Index(i)
structPtrInter := structPtr.Interface()
if v, ok := structPtrInter.(Validator); ok {
err = v.Validate(q)
if err != nil {
return q.updateTxError(err)
}
}
model := structPtrToModel(structPtrInter, false, nil)
if model.pk == nil {
panic("no primary key field")
}
q.criteria.model = model
var id int64
id, err = q.Dialect.insert(q)
if err != nil {
return q.updateTxError(err)
}
if _, ok := model.pk.value.(int64); ok && id != 0 {
idField := structPtr.Elem().FieldByName(model.pk.camelName)
idField.SetInt(id)
}
}
return nil
}
// If the struct type implements Validator interface, values will be validated before update.
// In order to avoid inadvertently update the struct field to zero value, it is better to define a
// temporary struct in function, only define the fields that should be updated.
// But the temporary struct can not implement Validator interface, we have to validate values manually.
// The update condition can be inferred by the Id value of the struct.
// If neither Id value or condition are provided, it would cause runtime panic
func (q *Qbs) Update(structPtr interface{}) (affected int64, err error) {
if v, ok := structPtr.(Validator); ok {
err := v.Validate(q)
if err != nil {
return 0, err
}
}
model := structPtrToModel(structPtr, true, q.criteria.omitFields)
q.criteria.model = model
q.criteria.mergePkCondition(q.Dialect)
if q.criteria.condition == nil {
panic("Can not update without condition")
}
return q.Dialect.update(q)
}
// The delete condition can be inferred by the Id value of the struct
// If neither Id value or condition are provided, it would cause runtime panic
func (q *Qbs) Delete(structPtr interface{}) (affected int64, err error) {
model := structPtrToModel(structPtr, true, q.criteria.omitFields)
q.criteria.model = model
q.criteria.mergePkCondition(q.Dialect)
if q.criteria.condition == nil {
panic("Can not delete without condition")
}
return q.Dialect.delete(q)
}
// This method can be used to validate unique column before trying to save
// The table parameter can be either a string or a struct pointer
func (q *Qbs) ContainsValue(table interface{}, column string, value interface{}) bool {
quotedColumn := q.Dialect.quote(column)
quotedTable := q.Dialect.quote(tableName(table))
query := fmt.Sprintf("SELECT %v FROM %v WHERE %v = ?", quotedColumn, quotedTable, quotedColumn)
row := q.QueryRow(query, value)
var result interface{}
err := row.Scan(&result)
q.updateTxError(err)
return err == nil
}
// If the connection pool is not full, the Db will be sent back into the pool, otherwise the Db will get closed.
func (q *Qbs) Close() error {
if connectionLimit != nil {
<-connectionLimit
}
if q.tx != nil {
return q.Rollback()
}
return nil
}
//Query the count of rows in a table the talbe parameter can be either a string or struct pointer.
//If condition is given, the count will be the count of rows meet that condition.
func (q *Qbs) Count(table interface{}) int64 {
quotedTable := q.Dialect.quote(tableName(table))
query := "SELECT COUNT(*) FROM " + quotedTable
var row *sql.Row
if q.criteria.condition != nil {
conditionSql, args := q.criteria.condition.Merge()
query += " WHERE " + conditionSql
row = q.QueryRow(query, args...)
} else {
row = q.QueryRow(query)
}
var count int64
err := row.Scan(&count)
if err == sql.ErrNoRows {
return 0
} else if err != nil {
q.updateTxError(err)
}
return count
}
//Query raw sql and return a map.
func (q *Qbs) QueryMap(query string, args ...interface{}) (map[string]interface{}, error) {
mapSlice, err := q.doQueryMap(query, true, args...)
if len(mapSlice) == 1 {
return mapSlice[0], err
}
return nil, sql.ErrNoRows
}
//Query raw sql and return a slice of map..
func (q *Qbs) QueryMapSlice(query string, args ...interface{}) ([]map[string]interface{}, error) {
return q.doQueryMap(query, false, args...)
}
func (q *Qbs) doQueryMap(query string, once bool, args ...interface{}) ([]map[string]interface{}, error) {
query = q.Dialect.substituteMarkers(query)
stmt, err := q.prepare(query)
if err != nil {
return nil, q.updateTxError(err)
}
rows, err := stmt.Query(args...)
if err != nil {
return nil, q.updateTxError(err)
}
defer rows.Close()
var results []map[string]interface{}
columns, _ := rows.Columns()
containers := make([]interface{}, len(columns))
for i := 0; i < len(columns); i++ {
var container interface{}
containers[i] = &container
}
for rows.Next() {
if err := rows.Scan(containers...); err != nil {
return nil, q.updateTxError(err)
}
result := make(map[string]interface{}, len(columns))
for i, key := range columns {
if containers[i] == nil {
continue
}
value := reflect.Indirect(reflect.ValueOf(containers[i]))
if value.Elem().Kind() == reflect.Slice {
result[key] = string(value.Interface().([]byte))
} else {
result[key] = value.Interface()
}
}
results = append(results, result)
if once {
return results, nil
}
}
return results, nil
}
//Do a raw sql query and set the result values in dest parameter.
//The dest parameter can be either a struct pointer or a pointer of struct pointer.slice
//This method do not support pointer field in the struct.
func (q *Qbs) QueryStruct(dest interface{}, query string, args ...interface{}) error {
query = q.Dialect.substituteMarkers(query)
stmt, err := q.prepare(query)
if err != nil {
return q.updateTxError(err)
}
rows, err := stmt.Query(args...)
if err != nil {
return q.updateTxError(err)
}
defer rows.Close()
outPtr := reflect.ValueOf(dest)
outValue := outPtr.Elem()
var structType reflect.Type
var single bool
if outValue.Kind() == reflect.Slice {
structType = outValue.Type().Elem().Elem()
} else {
structType = outValue.Type()
single = true
}
columns, _ := rows.Columns()
fieldNames := make([]string, len(columns))
for i, v := range columns {
upper := snakeToUpperCamel(v)
_, ok := structType.FieldByName(upper)
if ok {
fieldNames[i] = upper
} else {
fieldNames[i] = "-"
}
}
for rows.Next() {
var rowStructPointer reflect.Value
if single { //query row
rowStructPointer = outPtr
} else { //query rows
rowStructPointer = reflect.New(structType)
}
dests := make([]interface{}, len(columns))
for i := 0; i < len(dests); i++ {
fieldName := fieldNames[i]
if fieldName == "-" {
var placeholder interface{}
dests[i] = &placeholder
} else {
field := rowStructPointer.Elem().FieldByName(fieldName)
dests[i] = field.Addr().Interface()
}
}
err = rows.Scan(dests...)
if err != nil {
return err
}
if single {
return nil
}
outValue.Set(reflect.Append(outValue, rowStructPointer))
}
return nil
}
//Iterate the rows, the first parameter is a struct pointer, the second parameter is a fucntion
//which will get called on each row, the in `do` function the structPtr's value will be set to the current row's value..
//if `do` function returns an error, the iteration will be stopped.
func (q *Qbs) Iterate(structPtr interface{}, do func() error) error {
q.criteria.model = structPtrToModel(structPtr, !q.criteria.omitJoin, q.criteria.omitFields)
query, args := q.Dialect.querySql(q.criteria)
q.log(query, args...)
defer q.Reset()
stmt, err := q.prepare(query)
if err != nil {
return q.updateTxError(err)
}
rows, err := stmt.Query(args...)
if err != nil {
return q.updateTxError(err)
}
rowValue := reflect.ValueOf(structPtr)
defer rows.Close()
for rows.Next() {
err = q.scanRows(rowValue, rows)
if err != nil {
return err
}
if err = do(); err != nil {
return err
}
}
return nil
}
func (q *Qbs) log(query string, args ...interface{}) {
if q.Log && queryLogger != nil {
queryLogger.Print(query)
queryLogger.Println(args...)
}
}