forked from Restream/reindexer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
1025 lines (894 loc) · 27.2 KB
/
query.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
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package reindexer
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"sync"
"unsafe"
"github.com/restream/reindexer/bindings"
"github.com/restream/reindexer/cjson"
)
// Srict modes for queries
type QueryStrictMode int
const (
queryStrictModeNotSet QueryStrictMode = bindings.QueryStrictModeNotSet
QueryStrictModeNone = bindings.QueryStrictModeNone // Allows any fields in coditions, but doesn't check actual values for non-existing names
QueryStrictModeNames = bindings.QueryStrictModeNames // Allows only valid fields and indexes in conditions. Otherwise query will return error
QueryStrictModeIndexes = bindings.QueryStrictModeIndexes // Allows only indexes in conditions. Otherwise query will return error
)
// Constants for query serialization
const (
queryCondition = bindings.QueryCondition
querySortIndex = bindings.QuerySortIndex
queryJoinOn = bindings.QueryJoinOn
queryLimit = bindings.QueryLimit
queryOffset = bindings.QueryOffset
queryReqTotal = bindings.QueryReqTotal
queryDebugLevel = bindings.QueryDebugLevel
queryAggregation = bindings.QueryAggregation
querySelectFilter = bindings.QuerySelectFilter
queryExplain = bindings.QueryExplain
querySelectFunction = bindings.QuerySelectFunction
queryEqualPosition = bindings.QueryEqualPosition
queryUpdateField = bindings.QueryUpdateField
queryEnd = bindings.QueryEnd
queryAggregationLimit = bindings.QueryAggregationLimit
queryAggregationOffset = bindings.QueryAggregationOffset
queryAggregationSort = bindings.QueryAggregationSort
queryOpenBracket = bindings.QueryOpenBracket
queryCloseBracket = bindings.QueryCloseBracket
queryJoinCondition = bindings.QueryJoinCondition
queryDropField = bindings.QueryDropField
queryUpdateObject = bindings.QueryUpdateObject
queryWithRank = bindings.QueryWithRank
queryStrictMode = bindings.QueryStrictMode
)
// Constants for calc total
const (
modeNoCalc = bindings.ModeNoCalc
modeCachedTotal = bindings.ModeCachedTotal
modeAccurateTotal = bindings.ModeAccurateTotal
)
// Operator
const (
opAND = bindings.OpAnd
opOR = bindings.OpOr
opNOT = bindings.OpNot
)
// Join type
const (
innerJoin = bindings.InnerJoin
orInnerJoin = bindings.OrInnerJoin
leftJoin = bindings.LeftJoin
merge = bindings.Merge
)
const (
cInt32Max = bindings.CInt32Max
valueInt = bindings.ValueInt
valueBool = bindings.ValueBool
valueInt64 = bindings.ValueInt64
valueDouble = bindings.ValueDouble
valueString = bindings.ValueString
valueComposite = bindings.ValueComposite
valueTuple = bindings.ValueTuple
)
const (
defaultFetchCount = 100
)
type nsArrayEntry struct {
*reindexerNamespace
localCjsonState cjson.State
}
// Query to DB object
type Query struct {
Namespace string
db *reindexerImpl
nextOp int
ser cjson.Serializer
root *Query
joinQueries []*Query
mergedQueries []*Query
joinToFields []string
joinHandlers []JoinHandler
context interface{}
joinType int
closed bool
initBuf [256]byte
nsArray []nsArrayEntry
ptVersions []int32
iterator Iterator
jsonIterator JSONIterator
items []interface{}
json []byte
jsonOffsets []int
totalName string
executed bool
fetchCount int
queriesCount int
opennedBrackets []int
tx *Tx
}
var queryPool sync.Pool
// Create new DB query
func newQuery(db *reindexerImpl, namespace string, tx *Tx) *Query {
var q *Query
obj := queryPool.Get()
if obj != nil {
q = obj.(*Query)
}
if q == nil {
q = &Query{}
q.ser = cjson.NewSerializer(q.initBuf[:0])
} else {
q.tx = nil
q.nextOp = 0
q.root = nil
q.joinType = 0
q.context = nil
q.joinToFields = q.joinToFields[:0]
q.joinQueries = q.joinQueries[:0]
q.joinHandlers = q.joinHandlers[:0]
q.mergedQueries = q.mergedQueries[:0]
q.ptVersions = q.ptVersions[:0]
q.ser = cjson.NewSerializer(q.ser.Bytes()[:0])
q.closed = false
q.totalName = ""
q.executed = false
q.nsArray = q.nsArray[:0]
q.queriesCount = 0
q.opennedBrackets = q.opennedBrackets[:0]
}
q.Namespace = namespace
q.db = db
q.nextOp = opAND
q.fetchCount = defaultFetchCount
q.tx = tx
q.ser.PutVString(namespace)
return q
}
// MakeCopy - copy of query with same or other db, resets query context
func (q *Query) MakeCopy(db *Reindexer) *Query {
return q.makeCopy(db.impl, nil)
}
func (q *Query) makeCopy(db *reindexerImpl, root *Query) *Query {
var qC *Query
obj := queryPool.Get()
if obj != nil {
qC = obj.(*Query)
}
if qC == nil {
qC = &Query{}
}
qC.ser = cjson.NewSerializer(qC.initBuf[:0])
qC.db = db
qC.Namespace = q.Namespace
qC.nextOp = q.nextOp
qC.ser.Append(q.ser)
qC.joinToFields = append(q.joinToFields[:0:0], q.joinToFields...)
qC.joinHandlers = append(q.joinHandlers[:0:0], q.joinHandlers...)
//TODO not realycopy
qC.context = q.context
qC.joinType = q.joinType
qC.nsArray = append(q.nsArray[:0:0], q.nsArray...)
qC.ptVersions = append(q.ptVersions[:0:0], q.ptVersions...)
qC.items = append(q.items[:0:0], q.items...)
qC.json = append(q.json[:0:0], q.json...)
qC.jsonOffsets = append(q.jsonOffsets[:0:0], q.jsonOffsets...)
qC.totalName = q.totalName
qC.executed = q.executed
qC.fetchCount = q.fetchCount
qC.closed = q.closed
if q.root != nil && root == nil {
qC.root = q.root.makeCopy(db, nil)
} else if root != nil {
qC.root = root
} else {
qC.root = nil
}
qC.joinQueries = qC.joinQueries[:0]
for _, qj := range q.joinQueries {
qC.joinQueries = append(qC.joinQueries, qj.makeCopy(db, qC))
}
qC.mergedQueries = qC.mergedQueries[:0]
for _, qm := range q.mergedQueries {
qC.mergedQueries = append(qC.mergedQueries, qm.makeCopy(db, qC))
}
return qC
}
// Where - Add where condition to DB query
// For composite indexes keys must be []interface{}, with value of each subindex
func (q *Query) Where(index string, condition int, keys interface{}) *Query {
t := reflect.TypeOf(keys)
v := reflect.ValueOf(keys)
q.ser.PutVarCUInt(queryCondition)
q.ser.PutVString(index)
q.ser.PutVarCUInt(q.nextOp)
q.ser.PutVarCUInt(condition)
q.nextOp = opAND
q.queriesCount++
if keys == nil {
q.ser.PutVarUInt(0)
} else if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
q.ser.PutVarCUInt(v.Len())
for i := 0; i < v.Len(); i++ {
q.putValue(v.Index(i))
}
} else {
q.ser.PutVarCUInt(1)
q.putValue(v)
}
return q
}
// OpenBracket - Open bracket for where condition to DB query
func (q *Query) OpenBracket() *Query {
q.ser.PutVarCUInt(queryOpenBracket)
q.ser.PutVarCUInt(q.nextOp)
q.nextOp = opAND
q.opennedBrackets = append(q.opennedBrackets, q.queriesCount)
q.queriesCount++
return q
}
// CloseBracket - Close bracket for where condition to DB query
func (q *Query) CloseBracket() *Query {
if q.nextOp != opAND {
panic(fmt.Errorf("Operation before close bracket"))
}
if len(q.opennedBrackets) < 1 {
panic(fmt.Errorf("Close bracket before open it"))
}
q.ser.PutVarCUInt(queryCloseBracket)
q.opennedBrackets = q.opennedBrackets[:len(q.opennedBrackets)-1]
return q
}
func (q *Query) putValue(v reflect.Value) error {
k := v.Kind()
if k == reflect.Ptr || k == reflect.Interface {
v = v.Elem()
k = v.Kind()
}
switch k {
case reflect.Bool:
q.ser.PutVarCUInt(valueBool)
if v.Bool() {
q.ser.PutVarUInt(1)
} else {
q.ser.PutVarUInt(0)
}
case reflect.Uint:
if unsafe.Sizeof(int(0)) == unsafe.Sizeof(int64(0)) {
q.ser.PutVarCUInt(valueInt64)
} else {
q.ser.PutVarCUInt(valueInt)
}
q.ser.PutVarInt(int64(v.Uint()))
case reflect.Int:
if unsafe.Sizeof(int(0)) == unsafe.Sizeof(int64(0)) {
q.ser.PutVarCUInt(valueInt64)
} else {
q.ser.PutVarCUInt(valueInt)
}
q.ser.PutVarInt(v.Int())
case reflect.Int16, reflect.Int32, reflect.Int8:
q.ser.PutVarCUInt(valueInt)
q.ser.PutVarInt(v.Int())
case reflect.Uint8, reflect.Uint16, reflect.Uint32:
q.ser.PutVarCUInt(valueInt)
q.ser.PutVarInt(int64(v.Uint()))
case reflect.Int64:
q.ser.PutVarCUInt(valueInt64)
q.ser.PutVarInt(v.Int())
case reflect.Uint64:
q.ser.PutVarCUInt(valueInt64)
q.ser.PutVarInt(int64(v.Uint()))
case reflect.String:
q.ser.PutVarCUInt(valueString)
q.ser.PutVString(v.String())
case reflect.Float32, reflect.Float64:
q.ser.PutVarCUInt(valueDouble)
q.ser.PutDouble(v.Float())
case reflect.Slice, reflect.Array:
q.ser.PutVarCUInt(valueTuple)
q.ser.PutVarCUInt(v.Len())
for i := 0; i < v.Len(); i++ {
q.putValue(v.Index(i))
}
default:
panic(fmt.Errorf("rq: Invalid reflection type %s", v.Kind().String()))
}
return nil
}
// WhereInt - Add where condition to DB query with int args
func (q *Query) WhereInt(index string, condition int, keys ...int) *Query {
q.ser.PutVarCUInt(queryCondition).PutVString(index).PutVarCUInt(q.nextOp).PutVarCUInt(condition)
q.nextOp = opAND
q.queriesCount++
q.ser.PutVarCUInt(len(keys))
for _, v := range keys {
q.ser.PutVarCUInt(valueInt).PutVarInt(int64(v))
}
return q
}
// WhereInt - Add where condition to DB query with int args
func (q *Query) WhereInt32(index string, condition int, keys ...int32) *Query {
q.ser.PutVarCUInt(queryCondition).PutVString(index).PutVarCUInt(q.nextOp).PutVarCUInt(condition)
q.nextOp = opAND
q.queriesCount++
q.ser.PutVarCUInt(len(keys))
for _, v := range keys {
q.ser.PutVarCUInt(valueInt).PutVarInt(int64(v))
}
return q
}
// WhereInt64 - Add where condition to DB query with int64 args
func (q *Query) WhereInt64(index string, condition int, keys ...int64) *Query {
q.ser.PutVarCUInt(queryCondition).PutVString(index).PutVarCUInt(q.nextOp).PutVarCUInt(condition)
q.nextOp = opAND
q.queriesCount++
q.ser.PutVarCUInt(len(keys))
for _, v := range keys {
q.ser.PutVarCUInt(valueInt64).PutVarInt(v)
}
return q
}
// WhereString - Add where condition to DB query with string args
func (q *Query) WhereString(index string, condition int, keys ...string) *Query {
q.ser.PutVarCUInt(queryCondition).PutVString(index).PutVarCUInt(q.nextOp).PutVarCUInt(condition)
q.nextOp = opAND
q.queriesCount++
q.ser.PutVarCUInt(len(keys))
for _, v := range keys {
q.ser.PutVarCUInt(valueString).PutVString(v)
}
return q
}
// WhereComposite - Add where condition to DB query with interface args for composite indexes
func (q *Query) WhereComposite(index string, condition int, keys ...interface{}) *Query {
return q.Where(index, condition, keys)
}
// WhereString - Add where condition to DB query with string args
func (q *Query) Match(index string, keys ...string) *Query {
return q.WhereString(index, EQ, keys...)
}
// WhereString - Add where condition to DB query with bool args
func (q *Query) WhereBool(index string, condition int, keys ...bool) *Query {
q.ser.PutVarCUInt(queryCondition).PutVString(index).PutVarCUInt(q.nextOp).PutVarCUInt(condition)
q.nextOp = opAND
q.queriesCount++
q.ser.PutVarCUInt(len(keys))
for _, v := range keys {
q.ser.PutVarCUInt(valueBool)
if v {
q.ser.PutVarUInt(1)
} else {
q.ser.PutVarUInt(0)
}
}
return q
}
// WhereDouble - Add where condition to DB query with float args
func (q *Query) WhereDouble(index string, condition int, keys ...float64) *Query {
q.ser.PutVarCUInt(queryCondition).PutVString(index).PutVarCUInt(q.nextOp).PutVarCUInt(condition)
q.nextOp = opAND
q.queriesCount++
q.ser.PutVarCUInt(len(keys))
for _, v := range keys {
q.ser.PutVarCUInt(valueDouble).PutDouble(v)
}
return q
}
func (q *Query) AggregateSum(field string) {
q.ser.PutVarCUInt(queryAggregation).PutVarCUInt(AggSum).PutVarCUInt(1).PutVString(field)
}
func (q *Query) AggregateAvg(field string) {
q.ser.PutVarCUInt(queryAggregation).PutVarCUInt(AggAvg).PutVarCUInt(1).PutVString(field)
}
func (q *Query) AggregateMin(field string) {
q.ser.PutVarCUInt(queryAggregation).PutVarCUInt(AggMin).PutVarCUInt(1).PutVString(field)
}
func (q *Query) AggregateMax(field string) {
q.ser.PutVarCUInt(queryAggregation).PutVarCUInt(AggMax).PutVarCUInt(1).PutVString(field)
}
type AggregateFacetRequest struct {
query *Query
}
// fields should not be empty.
func (q *Query) AggregateFacet(fields ...string) *AggregateFacetRequest {
q.ser.PutVarCUInt(queryAggregation).PutVarCUInt(AggFacet).PutVarCUInt(len(fields))
for _, f := range fields {
q.ser.PutVString(f)
}
r := AggregateFacetRequest{q}
return &r
}
func (r *AggregateFacetRequest) Limit(limit int) *AggregateFacetRequest {
r.query.ser.PutVarCUInt(queryAggregationLimit).PutVarCUInt(limit)
return r
}
func (r *AggregateFacetRequest) Offset(offset int) *AggregateFacetRequest {
r.query.ser.PutVarCUInt(queryAggregationOffset).PutVarCUInt(offset)
return r
}
// Use field 'count' to sort by facet's count value.
func (r *AggregateFacetRequest) Sort(field string, desc bool) *AggregateFacetRequest {
r.query.ser.PutVarCUInt(queryAggregationSort).PutVString(field)
if desc {
r.query.ser.PutVarCUInt(1)
} else {
r.query.ser.PutVarCUInt(0)
}
return r
}
// Sort - Apply sort order to returned from query items
// If values argument specified, then items equal to values, if found will be placed in the top positions
// For composite indexes values must be []interface{}, with value of each subindex
func (q *Query) Sort(sortIndex string, desc bool, values ...interface{}) *Query {
q.ser.PutVarCUInt(querySortIndex)
q.ser.PutVString(sortIndex)
if desc {
q.ser.PutVarUInt(1)
} else {
q.ser.PutVarUInt(0)
}
q.ser.PutVarCUInt(len(values))
for i := 0; i < len(values); i++ {
q.putValue(reflect.ValueOf(values[i]))
}
return q
}
// OR - next condition will added with OR
// Implements short-circuiting:
// if the previous condition is successful the next will not be evaluated, but except Join conditions
func (q *Query) Or() *Query {
q.nextOp = opOR
return q
}
// Not - next condition will added with NOT AND
// Implements short-circuiting:
// if the previous condition is failed the next will not be evaluated
func (q *Query) Not() *Query {
q.nextOp = opNOT
return q
}
// Distinct - Return only items with uniq value of field
func (q *Query) Distinct(distinctIndex string) *Query {
q.ser.PutVarCUInt(queryAggregation).PutVarCUInt(AggDistinct).PutVarCUInt(1).PutVString(distinctIndex)
return q
}
// ReqTotal Request total items calculation
func (q *Query) ReqTotal(totalNames ...string) *Query {
q.ser.PutVarCUInt(queryReqTotal)
q.ser.PutVarCUInt(modeAccurateTotal)
if len(totalNames) != 0 {
q.totalName = totalNames[0]
}
return q
}
// CachedTotal Request cached total items calculation
func (q *Query) CachedTotal(totalNames ...string) *Query {
q.ser.PutVarCUInt(queryReqTotal)
q.ser.PutVarCUInt(modeCachedTotal)
if len(totalNames) != 0 {
q.totalName = totalNames[0]
}
return q
}
// Limit - Set limit (count) of returned items
func (q *Query) Limit(limitItems int) *Query {
if limitItems > cInt32Max {
limitItems = cInt32Max
}
q.ser.PutVarCUInt(queryLimit).PutVarCUInt(limitItems)
return q
}
// Offset - Set start offset of returned items
func (q *Query) Offset(startOffset int) *Query {
if startOffset > cInt32Max {
startOffset = cInt32Max
}
q.ser.PutVarCUInt(queryOffset).PutVarCUInt(startOffset)
return q
}
// Debug - Set debug level
func (q *Query) Debug(level int) *Query {
q.ser.PutVarCUInt(queryDebugLevel).PutVarCUInt(level)
return q
}
// Strict - Set query strict mode
func (q *Query) Strict(mode QueryStrictMode) *Query {
q.ser.PutVarCUInt(queryStrictMode).PutVarCUInt(int(mode))
return q
}
// Explain - Request explain for query
func (q *Query) Explain() *Query {
q.ser.PutVarCUInt(queryExplain)
return q
}
// Output fulltext rank
// Allowed only with fulltext query
func (q *Query) WithRank() *Query {
q.ser.PutVarCUInt(queryWithRank)
return q
}
// SetContext set interface, which will be passed to Joined interface
func (q *Query) SetContext(ctx interface{}) *Query {
q.context = ctx
if q.root != nil {
q.root.context = ctx
}
return q
}
// Exec will execute query, and return slice of items
func (q *Query) Exec() *Iterator {
return q.ExecCtx(context.Background())
}
// ExecCtx will execute query, and return slice of items
func (q *Query) ExecCtx(ctx context.Context) *Iterator {
if q.root != nil {
q = q.root
}
if q.closed {
panic(errors.New("Exec call on already closed query. You shoud create new Query"))
}
if q.executed {
panic(errors.New("Exec call on already executed query. You shoud create new Query"))
}
// if q.tx != nil {
// panic(errors.New("For tx query only Update or Delete operations are supported"))
// }
q.executed = true
return q.db.execQuery(ctx, q)
}
// ExecToJson will execute query, and return iterator
func (q *Query) ExecToJson(jsonRoots ...string) *JSONIterator {
return q.ExecToJsonCtx(context.Background())
}
// ExecToJsonCtx will execute query, and return iterator
func (q *Query) ExecToJsonCtx(ctx context.Context, jsonRoots ...string) *JSONIterator {
if q.root != nil {
q = q.root
}
if q.closed {
panic(errors.New("Exec call on already closed query. You shoud create new Query"))
}
if q.executed {
panic(errors.New("Exec call on already executed query. You shoud create new Query"))
}
// if q.tx != nil {
// panic(errors.New("For tx query only Update or Delete operations are supported"))
// }
q.executed = true
jsonRoot := q.Namespace
if len(jsonRoots) != 0 && len(jsonRoots[0]) != 0 {
jsonRoot = jsonRoots[0]
}
return q.db.execJSONQuery(ctx, q, jsonRoot)
}
func (q *Query) close() {
if q.root != nil {
q = q.root
}
if q.closed {
panic(errors.New("Close call on already closed query"))
}
for i, jq := range q.joinQueries {
jq.closed = true
queryPool.Put(jq)
q.joinQueries[i] = nil
}
for i, mq := range q.mergedQueries {
mq.closed = true
queryPool.Put(mq)
q.mergedQueries[i] = nil
}
for i := range q.joinHandlers {
q.joinHandlers[i] = nil
}
q.closed = true
q.tx = nil
queryPool.Put(q)
}
// Delete will execute query, and delete items, matches query
// On sucess return number of deleted elements
func (q *Query) Delete() (int, error) {
return q.DeleteCtx(context.Background())
}
// DeleteCtx will execute query, and delete items, matches query
// On sucess return number of deleted elements
func (q *Query) DeleteCtx(ctx context.Context) (int, error) {
if q.root != nil || len(q.joinQueries) != 0 {
return 0, errors.New("Delete does not support joined queries")
}
if q.closed {
panic(errors.New("Delete call on already closed query. You shoud create new Query"))
}
defer q.close()
if q.tx != nil {
return q.db.deleteQueryTx(ctx, q, q.tx)
}
return q.db.deleteQuery(ctx, q)
}
func getValueJSON(value interface{}) string {
ok := false
var err error
var objectJSON []byte
t := reflect.TypeOf(value)
if value == nil {
objectJSON = []byte("{}")
} else if t.Kind() == reflect.Struct || t.Kind() == reflect.Map {
objectJSON, err = json.Marshal(value)
if err != nil {
panic(err)
}
} else if objectJSON, ok = value.([]byte); !ok {
panic(errors.New("SetObject doesn't support this type of objects: " + t.Kind().String()))
}
return string(objectJSON)
}
// SetObject adds update of object field request for update query
func (q *Query) SetObject(field string, values interface{}) *Query {
size := 1
isArray := false
t := reflect.TypeOf(values)
v := reflect.ValueOf(values)
if t != reflect.TypeOf([]byte{}) && (t.Kind() == reflect.Array || t.Kind() == reflect.Slice) {
size = v.Len()
isArray = true
}
jsonValues := make([]string, size)
if isArray {
for i := 0; i < size; i++ {
jsonValues[i] = getValueJSON(v.Index(i).Interface())
}
} else if size > 0 {
jsonValues[0] = getValueJSON(values)
}
q.ser.PutVarCUInt(queryUpdateObject)
q.ser.PutVString(field)
// values count
q.ser.PutVarCUInt(size)
// is array flag
if isArray {
q.ser.PutVarCUInt(1)
} else {
q.ser.PutVarCUInt(0)
}
for i := 0; i < size; i++ {
// function/value flag
q.ser.PutVarUInt(0)
q.ser.PutVarCUInt(valueString)
q.ser.PutVString(jsonValues[i])
}
return q
}
// Set adds update field request for update query
func (q *Query) Set(field string, values interface{}) *Query {
t := reflect.TypeOf(values)
if t.Kind() == reflect.Struct {
return q.SetObject(field, values)
}
v := reflect.ValueOf(values)
q.ser.PutVarCUInt(queryUpdateField)
q.ser.PutVString(field)
if values == nil {
q.ser.PutVarUInt(0)
} else if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
q.ser.PutVarCUInt(v.Len())
for i := 0; i < v.Len(); i++ {
// function/value flag
q.ser.PutVarUInt(0)
q.putValue(v.Index(i))
}
} else {
q.ser.PutVarCUInt(1)
// function/value flag
q.ser.PutVarUInt(0)
q.putValue(v)
}
return q
}
// Drop removes field from item within Update statement
func (q *Query) Drop(field string) *Query {
q.ser.PutVarCUInt(queryDropField)
q.ser.PutVString(field)
return q
}
// SetExpression updates indexed field by arithmetical expression
func (q *Query) SetExpression(field string, value string) *Query {
q.ser.PutVarCUInt(queryUpdateField)
q.ser.PutVString(field)
q.ser.PutVarCUInt(1)
q.ser.PutVarUInt(1)
q.putValue(reflect.ValueOf(value))
return q
}
// Update will execute query, and update fields in items, which matches query
// On sucess return number of update elements
func (q *Query) Update() *Iterator {
return q.UpdateCtx(context.Background())
}
// UpdateCtx will execute query, and update fields in items, which matches query
// On sucess return number of update elements
func (q *Query) UpdateCtx(ctx context.Context) *Iterator {
if q.root != nil || len(q.joinQueries) != 0 {
return errIterator(errors.New("Update does not support joined queries"))
}
if q.closed {
panic(errors.New("Update call on already closed query. You shoud create new Query"))
}
q.executed = true
if q.tx != nil {
return q.db.updateQueryTx(ctx, q, q.tx)
}
return q.db.updateQuery(ctx, q)
}
// MustExec will execute query, and return iterator, panic on error
func (q *Query) MustExec() *Iterator {
return q.MustExecCtx(context.Background())
}
// MustExecCtx will execute query, and return iterator, panic on error
func (q *Query) MustExecCtx(ctx context.Context) *Iterator {
it := q.ExecCtx(ctx)
if it.err != nil {
panic(it.err)
}
return it
}
// Get will execute query, and return 1 st item, panic on error
func (q *Query) Get() (item interface{}, found bool) {
return q.GetCtx(context.Background())
}
// GetCtx will execute query, and return 1 st item, panic on error
func (q *Query) GetCtx(ctx context.Context) (item interface{}, found bool) {
iter := q.Limit(1).MustExecCtx(ctx)
defer iter.Close()
if iter.Next() {
return iter.Object(), true
}
return nil, false
}
// GetJson will execute query, and return 1 st item, panic on error
func (q *Query) GetJson() (json []byte, found bool) {
return q.GetJsonCtx(context.Background())
}
// GetJsonCtx will execute query, and return 1 st item, panic on error
func (q *Query) GetJsonCtx(ctx context.Context) (json []byte, found bool) {
it := q.Limit(1).ExecToJsonCtx(ctx)
defer it.Close()
if it.Error() != nil {
panic(it.Error())
}
if !it.Next() {
return nil, false
}
return it.JSON(), true
}
// Join joins 2 queries
func (q *Query) join(q2 *Query, field string, joinType int) *Query {
if q.root != nil {
q = q.root
}
if q2.root != nil {
panic(errors.New("query.Join call on already joined query. You shoud create new Query"))
}
if joinType != leftJoin {
q.ser.PutVarCUInt(queryJoinCondition)
q.ser.PutVarCUInt(joinType)
q.ser.PutVarCUInt(len(q.joinQueries)) // index of join query
}
q2.joinType = joinType
q2.root = q
q.joinQueries = append(q.joinQueries, q2)
q.joinToFields = append(q.joinToFields, field)
q.joinHandlers = append(q.joinHandlers, nil)
return q2
}
// InnerJoin joins 2 queries
// Items from the 1-st query are filtered by and expanded with the data from the 2-nd query
//
// `field` parameter serves as unique identifier for the join between `q` and `q2`
// One of the conditions below must hold for `field` parameter in order for InnerJoin to work:
// - namespace of `q2` contains `field` as one of its fields marked as `joined`
// - `q` has a join handler (registered via `q.JoinHandler(...)` call) with the same `field` value
func (q *Query) InnerJoin(q2 *Query, field string) *Query {
if q.nextOp == opOR {
q.nextOp = opAND
return q.join(q2, field, orInnerJoin)
}
return q.join(q2, field, innerJoin)
}
// Join is an alias for LeftJoin
func (q *Query) Join(q2 *Query, field string) *Query {
return q.join(q2, field, leftJoin)
}
// LeftJoin joins 2 queries
// Items from the 1-st query are expanded with the data from the 2-nd query
//
// `field` parameter serves as unique identifier for the join between `q` and `q2`
// One of the conditions below must hold for `field` parameter in order for LeftJoin to work:
// - namespace of `q2` contains `field` as one of its fields marked as `joined`
// - `q` has a join handler (registered via `q.JoinHandler(...)` call) with the same `field` value
func (q *Query) LeftJoin(q2 *Query, field string) *Query {
return q.join(q2, field, leftJoin)
}
// JoinHandler registers join handler that will be called when join, registered on `field` value, finds a match
func (q *Query) JoinHandler(field string, handler JoinHandler) *Query {
index := -1
for i := range q.joinToFields {
if strings.EqualFold(q.joinToFields[i], field) {
index = i
}
}
if index != -1 {
q.joinHandlers[index] = handler
}
return q
}
// Merge 2 queries
func (q *Query) Merge(q2 *Query) *Query {
if q.root != nil {
q = q.root
}
if q2.root != nil {
q2 = q2.root
}
q2.root = q
q.mergedQueries = append(q.mergedQueries, q2)
return q
}
// On specifies join condition
//
// `index` parameter specifies which field from `q` namespace should be used during join
// `condition` parameter specifies how `q` will be joined with the latest join query issued on `q` (e.g. `EQ`/`GT`/`SET`/...)
// `joinIndex` parameter specifies which field from namespace for the latest join query issued on `q` should be used during join
func (q *Query) On(index string, condition int, joinIndex string) *Query {
if q.closed {
panic(errors.New("query.On call on already closed query. You shoud create new Query"))
}
if q.root == nil {
panic(fmt.Errorf("Can't join on root query"))
}
q.ser.PutVarCUInt(queryJoinOn)
q.ser.PutVarCUInt(q.nextOp)
q.ser.PutVarCUInt(condition)
q.ser.PutVString(index)
q.ser.PutVString(joinIndex)
q.nextOp = opAND
return q
}
// Select add filter to fields of result's objects
func (q *Query) Select(fields ...string) *Query {
for _, field := range fields {
q.ser.PutVarCUInt(querySelectFilter).PutVString(field)
}
return q
}
// FetchCount sets the number of items that will be fetched by one operation
// When n <= 0 query will fetch all results in one operation
func (q *Query) FetchCount(n int) *Query {
q.fetchCount = n