-
Notifications
You must be signed in to change notification settings - Fork 64
/
query.go
1235 lines (1078 loc) · 33.5 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"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"unsafe"
"github.com/restream/reindexer/v3/bindings"
"github.com/restream/reindexer/v3/cjson"
)
// Strict modes for queries
type QueryStrictMode int
const (
queryStrictModeNotSet QueryStrictMode = bindings.QueryStrictModeNotSet
QueryStrictModeNone = bindings.QueryStrictModeNone // Allows any fields in conditions, 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
queryUpdateFieldV2 = bindings.QueryUpdateFieldV2
queryBetweenFieldsCondition = bindings.QueryBetweenFieldsCondition
queryAlwaysFalseCondition = bindings.QueryAlwaysFalseCondition
queryAlwaysTrueCondition = bindings.QueryAlwaysTrueCondition
querySubQueryCondition = bindings.QuerySubQueryCondition
queryFieldSubQueryCondition = bindings.QueryFieldSubQueryCondition
)
// 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
valueUuid = bindings.ValueUuid
)
const (
defaultFetchCount = 1000
)
type nsArrayEntry struct {
*reindexerNamespace
localCjsonState cjson.State
}
type noCopy struct{}
// Lock is a no-op used by -copylocks checker from `go vet`.
func (*noCopy) Lock() {}
func (*noCopy) Unlock() {}
// Query to DB object
type Query struct {
noCopy noCopy
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
traceNew []byte
traceClose []byte
}
var queryPool sync.Pool
var enableDebug bool
func init() {
enableDebug = os.Getenv("REINDEXER_GODEBUG") != ""
}
func mktrace(buf *[]byte) {
if enableDebug {
if *buf == nil {
*buf = make([]byte, 0x4000)
}
*buf = (*buf)[0:runtime.Stack((*buf)[0:cap((*buf))], false)]
}
}
// 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]
}
mktrace(&q.traceNew)
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{}
}
mktrace(&qC.traceNew)
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 real copy
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)
if keys != nil && (t == reflect.TypeOf((*Query)(nil)).Elem() || (t.Kind() == reflect.Ptr && t.Elem() == reflect.TypeOf((*Query)(nil)).Elem())) {
q.ser.PutVarCUInt(queryFieldSubQueryCondition)
q.ser.PutVarCUInt(q.nextOp)
q.ser.PutVString(index)
q.ser.PutVarCUInt(condition)
if t.Kind() == reflect.Ptr {
q.ser.PutVBytes(v.Interface().(*Query).ser.Bytes())
} else {
subQuery := v.Interface().(Query)
q.ser.PutVBytes(subQuery.ser.Bytes())
}
} else {
q.ser.PutVarCUInt(queryCondition)
q.ser.PutVString(index)
q.ser.PutVarCUInt(q.nextOp)
q.ser.PutVarCUInt(condition)
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)
}
}
q.queriesCount++
q.nextOp = opAND
return q
}
func (q *Query) WhereQuery(subQuery *Query, condition int, keys interface{}) *Query {
t := reflect.TypeOf(keys)
v := reflect.ValueOf(keys)
q.ser.PutVarCUInt(querySubQueryCondition)
q.ser.PutVarCUInt(q.nextOp)
q.ser.PutVBytes(subQuery.ser.Bytes())
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
}
// Where - Add comparing two fields where condition to DB query
// For composite indexes keys must be []interface{}, with value of each subindex
func (q *Query) WhereBetweenFields(firstField string, condition int, secondField string) *Query {
q.ser.PutVarCUInt(queryBetweenFieldsCondition)
q.ser.PutVarCUInt(q.nextOp)
q.ser.PutVString(firstField)
q.ser.PutVarCUInt(condition)
q.ser.PutVString(secondField)
q.nextOp = opAND
q.queriesCount++
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
}
// WhereUuid - Add where condition to DB query with UUID args.
// This function applies binary encoding to the uuid value.
// 'index' MUST be declared as uuid index in this case
func (q *Query) WhereUuid(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 {
uuid, err := cjson.ParseUuid(v)
if err != nil {
q.ser.PutVarCUInt(valueString).PutVString(v)
} else {
q.ser.PutVarCUInt(valueUuid).PutUuid(uuid)
}
}
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
}
// DWithin - Add DWithin condition to DB query
func (q *Query) DWithin(index string, point Point, distance float64) *Query {
q.ser.PutVarCUInt(queryCondition).PutVString(index).PutVarCUInt(q.nextOp).PutVarCUInt(DWITHIN)
q.nextOp = opAND
q.queriesCount++
q.ser.PutVarCUInt(3)
q.ser.PutVarCUInt(valueDouble).PutDouble(point[0])
q.ser.PutVarCUInt(valueDouble).PutDouble(point[1])
q.ser.PutVarCUInt(valueDouble).PutDouble(distance)
return q
}
func (q *Query) AggregateSum(field string) *Query {
q.ser.PutVarCUInt(queryAggregation).PutVarCUInt(AggSum).PutVarCUInt(1).PutVString(field)
return q
}
func (q *Query) AggregateAvg(field string) *Query {
q.ser.PutVarCUInt(queryAggregation).PutVarCUInt(AggAvg).PutVarCUInt(1).PutVString(field)
return q
}
func (q *Query) AggregateMin(field string) *Query {
q.ser.PutVarCUInt(queryAggregation).PutVarCUInt(AggMin).PutVarCUInt(1).PutVString(field)
return q
}
func (q *Query) AggregateMax(field string) *Query {
q.ser.PutVarCUInt(queryAggregation).PutVarCUInt(AggMax).PutVarCUInt(1).PutVString(field)
return q
}
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
// Forced sort is support for the first sorting field only
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
}
// SortStDistance - wrapper for geometry sorting by shortest distance between geometry field and point (ST_Distance)
func (q *Query) SortStPointDistance(field string, p Point, desc bool) *Query {
var sb strings.Builder
sb.Grow(256)
sb.WriteString("ST_Distance(")
sb.WriteString(field)
sb.WriteString(",ST_GeomFromText('point(")
sb.WriteString(strconv.FormatFloat(p[0], 'f', -1, 64))
sb.WriteRune(' ')
sb.WriteString(strconv.FormatFloat(p[1], 'f', -1, 64))
sb.WriteString(")'))")
return q.Sort(sb.String(), desc)
}
// SortStDistance - wrapper for geometry sorting by shortest distance between 2 geometry fields (ST_Distance)
func (q *Query) SortStFieldDistance(field1 string, field2 string, desc bool) *Query {
var sb strings.Builder
sb.Grow(256)
sb.WriteString("ST_Distance(")
sb.WriteString(field1)
sb.WriteRune(',')
sb.WriteString(field2)
sb.WriteRune(')')
return q.Sort(sb.String(), desc)
}
// AND - next condition will added with AND
// This is the default operation for WHERE statement. Do not have to be called explicitly in user's code. Used in DSL conversion
func (q *Query) And() *Query {
q.nextOp = opAND
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 {
q.panicTrace("Exec call on already closed query. You should create new Query")
}
if q.executed {
q.panicTrace("Exec call on already executed query. You should create new Query")
}
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(), jsonRoots...)
}
// 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 {
q.panicTrace("Exec call on already closed query. You should create new Query")
}
if q.executed {
q.panicTrace("Exec call on already executed query. You should create new Query")
}
q.executed = true
jsonRoot := q.Namespace
if len(jsonRoots) != 0 && len(jsonRoots[0]) != 0 {
jsonRoot = jsonRoots[0]
}
return q.db.execToJsonQuery(ctx, q, jsonRoot)
}
func (q *Query) close() {
if q.root != nil {
q = q.root
}
if q.closed {
q.panicTrace("Close call on already closed query")
}
mktrace(&q.traceClose)
for i, jq := range q.joinQueries {
jq.closed = true
mktrace(&jq.traceClose)
queryPool.Put(jq)
q.joinQueries[i] = nil
}
for i, mq := range q.mergedQueries {
mq.closed = true
mktrace(&mq.traceClose)
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)
}
func (q *Query) panicTrace(msg string) {
if !enableDebug {
fmt.Println("To see query allocation/close traces set REINDEXER_GODEBUG=1 environment variable!")
} else {
fmt.Printf("Query allocation trace: %s\n\nQuery close trace %s\n\n", string(q.traceNew), string(q.traceClose))
}
panic(errors.New(msg))
}
// Delete will execute query, and delete items, matches query
// On success 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 success 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 {
q.panicTrace("Delete call on already closed query. You should 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 || t.Kind() == reflect.Map {
return q.SetObject(field, values)
}
if (t.Kind() == reflect.Slice || t.Kind() == reflect.Array) && t.Elem().Kind() == reflect.Struct {
return q.SetObject(field, values)
}
v := reflect.ValueOf(values)
cmd := queryUpdateField
if (t.Kind() == reflect.Slice || t.Kind() == reflect.Array) && v.Len() <= 1 {
// If field is slice, with size eq 0 or 1, then old
// queryUpdateField command cant encode it properly
cmd = queryUpdateFieldV2
}
q.ser.PutVarCUInt(cmd)
q.ser.PutVString(field)
if values == nil {
if cmd == queryUpdateFieldV2 {
q.ser.PutVarUInt(0) // is array
}
q.ser.PutVarUInt(0) // size
} else if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
if cmd == queryUpdateFieldV2 {
q.ser.PutVarUInt(1) // is 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 {
if cmd == queryUpdateFieldV2 {
q.ser.PutVarUInt(0) // is array
}
q.ser.PutVarCUInt(1) // size
// 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) // size
q.ser.PutVarUInt(1) // is expression
q.putValue(reflect.ValueOf(value))