This repository has been archived by the owner on Sep 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
orm.go
1479 lines (1301 loc) · 43 KB
/
orm.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
// Copyright 2017 Pilosa Corp.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
package pilosa
import (
"encoding/json"
"fmt"
"math"
"sort"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
)
const timeFormat = "2006-01-02T15:04"
// Schema contains the index properties
type Schema struct {
indexes map[string]*Index
}
func (s *Schema) String() string {
return fmt.Sprintf("%#v", s.indexes)
}
// NewSchema creates a new Schema
func NewSchema() *Schema {
return &Schema{
indexes: make(map[string]*Index),
}
}
// Index returns an index with a name.
func (s *Schema) Index(name string, options ...IndexOption) *Index {
if index, ok := s.indexes[name]; ok {
return index
}
indexOptions := &IndexOptions{}
indexOptions.addOptions(options...)
return s.indexWithOptions(name, 0, indexOptions)
}
func (s *Schema) indexWithOptions(name string, shardWidth uint64, options *IndexOptions) *Index {
index := NewIndex(name)
index.options = options.withDefaults()
index.shardWidth = shardWidth
s.indexes[name] = index
return index
}
// Indexes return a copy of the indexes in this schema
func (s *Schema) Indexes() map[string]*Index {
result := make(map[string]*Index)
for k, v := range s.indexes {
result[k] = v.copy()
}
return result
}
// HasIndex returns true if the given index is in the schema.
func (s *Schema) HasIndex(indexName string) bool {
_, ok := s.indexes[indexName]
return ok
}
func (s *Schema) diff(other *Schema) *Schema {
result := NewSchema()
for indexName, index := range s.indexes {
if otherIndex, ok := other.indexes[indexName]; !ok {
// if the index doesn't exist in the other schema, simply copy it
result.indexes[indexName] = index.copy()
} else {
// the index exists in the other schema; check the fields
resultIndex := NewIndex(indexName)
for fieldName, field := range index.fields {
if _, ok := otherIndex.fields[fieldName]; !ok {
// the field doesn't exist in the other schema, copy it
resultIndex.fields[fieldName] = field.copy()
}
}
// check whether we modified result index
if len(resultIndex.fields) > 0 {
// if so, move it to the result
result.indexes[indexName] = resultIndex
}
}
}
return result
}
type SerializedQuery interface {
String() string
HasWriteKeys() bool
}
type serializedQuery struct {
query string
hasWriteKeys bool
}
func newSerializedQuery(query string, hasWriteKeys bool) serializedQuery {
return serializedQuery{
query: query,
hasWriteKeys: hasWriteKeys,
}
}
func (s serializedQuery) String() string {
return s.query
}
func (s serializedQuery) HasWriteKeys() bool {
return s.hasWriteKeys
}
// PQLQuery is an interface for PQL queries.
type PQLQuery interface {
Index() *Index
Serialize() SerializedQuery
Error() error
}
// PQLBaseQuery is the base implementation for PQLQuery.
type PQLBaseQuery struct {
index *Index
pql string
err error
hasKeys bool
}
// NewPQLBaseQuery creates a new PQLQuery with the given PQL and index.
func NewPQLBaseQuery(pql string, index *Index, err error) *PQLBaseQuery {
var hasKeys bool
if index != nil {
hasKeys = index.options.keys
}
return &PQLBaseQuery{
index: index,
pql: pql,
err: err,
hasKeys: hasKeys,
}
}
// Index returns the index for this query
func (q *PQLBaseQuery) Index() *Index {
return q.index
}
func (q *PQLBaseQuery) Serialize() SerializedQuery {
return newSerializedQuery(q.pql, q.hasKeys)
}
// Error returns the error or nil for this query.
func (q PQLBaseQuery) Error() error {
return q.err
}
// PQLRowQuery is the return type for row queries.
type PQLRowQuery struct {
index *Index
pql string
err error
hasKeys bool
}
// Index returns the index for this query/
func (q *PQLRowQuery) Index() *Index {
return q.index
}
func (q *PQLRowQuery) Serialize() SerializedQuery {
return q.serialize()
}
func (q *PQLRowQuery) serialize() SerializedQuery {
return newSerializedQuery(q.pql, q.hasKeys)
}
// Error returns the error or nil for this query.
func (q PQLRowQuery) Error() error {
return q.err
}
// PQLBatchQuery contains a batch of PQL queries.
// Use Index.BatchQuery function to create an instance.
//
// Usage:
//
// repo, err := NewIndex("repository")
// stargazer, err := repo.Field("stargazer")
// query := repo.BatchQuery(
// stargazer.Row(5),
// stargazer.Row(15),
// repo.Union(stargazer.Row(20), stargazer.Row(25)))
type PQLBatchQuery struct {
index *Index
queries []string
err error
hasKeys bool
}
// Index returns the index for this query.
func (q *PQLBatchQuery) Index() *Index {
return q.index
}
func (q *PQLBatchQuery) Serialize() SerializedQuery {
query := strings.Join(q.queries, "")
return newSerializedQuery(query, q.hasKeys)
}
func (q *PQLBatchQuery) Error() error {
return q.err
}
// Add adds a query to the batch.
func (q *PQLBatchQuery) Add(query PQLQuery) {
err := query.Error()
if err != nil {
q.err = err
}
serializedQuery := query.Serialize()
q.hasKeys = q.hasKeys || serializedQuery.HasWriteKeys()
q.queries = append(q.queries, serializedQuery.String())
}
// NewPQLRowQuery creates a new PqlRowQuery.
func NewPQLRowQuery(pql string, index *Index, err error) *PQLRowQuery {
return &PQLRowQuery{
index: index,
pql: pql,
err: err,
hasKeys: index.options.keys,
}
}
// IndexOptions contains options to customize Index objects.
type IndexOptions struct {
keys bool
keysSet bool
trackExistence bool
trackExistenceSet bool
}
func (io *IndexOptions) withDefaults() (updated *IndexOptions) {
// copy options so the original is not updated
updated = &IndexOptions{}
*updated = *io
if !updated.keysSet {
updated.keys = false
}
if !updated.trackExistenceSet {
updated.trackExistence = true
}
return
}
// Keys return true if this index has keys.
func (io IndexOptions) Keys() bool {
return io.keys
}
// TrackExistence returns true if existence is tracked for this index.
func (io IndexOptions) TrackExistence() bool {
return io.trackExistence
}
// String serializes this index to a JSON string.
func (io IndexOptions) String() string {
mopt := map[string]interface{}{}
if io.keysSet {
mopt["keys"] = io.keys
}
if io.trackExistenceSet {
mopt["trackExistence"] = io.trackExistence
}
return fmt.Sprintf(`{"options":%s}`, encodeMap(mopt))
}
func (io *IndexOptions) addOptions(options ...IndexOption) {
for _, option := range options {
if option == nil {
continue
}
option(io)
}
}
// IndexOption is used to pass an option to Index function.
type IndexOption func(options *IndexOptions)
// OptIndexKeys sets whether index uses string keys.
func OptIndexKeys(keys bool) IndexOption {
return func(options *IndexOptions) {
options.keys = keys
options.keysSet = true
}
}
// OptIndexTrackExistence enables keeping track of existence of columns.
func OptIndexTrackExistence(trackExistence bool) IndexOption {
return func(options *IndexOptions) {
options.trackExistence = trackExistence
options.trackExistenceSet = true
}
}
// OptionsOptions is used to pass an option to Option call.
type OptionsOptions struct {
columnAttrs bool
excludeColumns bool
excludeRowAttrs bool
shards []uint64
}
func (oo OptionsOptions) marshal() string {
part1 := fmt.Sprintf("columnAttrs=%s,excludeColumns=%s,excludeRowAttrs=%s",
strconv.FormatBool(oo.columnAttrs),
strconv.FormatBool(oo.excludeColumns),
strconv.FormatBool(oo.excludeRowAttrs))
if oo.shards != nil {
shardsStr := make([]string, len(oo.shards))
for i, shard := range oo.shards {
shardsStr[i] = strconv.FormatUint(shard, 10)
}
return fmt.Sprintf("%s,shards=[%s]", part1, strings.Join(shardsStr, ","))
}
return part1
}
// OptionsOption is an option for Index.Options call.
type OptionsOption func(options *OptionsOptions)
// OptOptionsColumnAttrs enables returning column attributes.
func OptOptionsColumnAttrs(enable bool) OptionsOption {
return func(options *OptionsOptions) {
options.columnAttrs = enable
}
}
// OptOptionsExcludeColumns enables preventing returning columns.
func OptOptionsExcludeColumns(enable bool) OptionsOption {
return func(options *OptionsOptions) {
options.excludeColumns = enable
}
}
// OptOptionsExcludeRowAttrs enables preventing returning row attributes.
func OptOptionsExcludeRowAttrs(enable bool) OptionsOption {
return func(options *OptionsOptions) {
options.excludeRowAttrs = enable
}
}
// OptOptionsShards run the query using only the data from the given shards.
// By default, the entire data set (i.e. data from all shards) is used.
func OptOptionsShards(shards ...uint64) OptionsOption {
return func(options *OptionsOptions) {
options.shards = shards
}
}
// Index is a Pilosa index. The purpose of the Index is to represent a data namespace.
// You cannot perform cross-index queries. Column-level attributes are global to the Index.
type Index struct {
name string
options *IndexOptions
fields map[string]*Field
shardWidth uint64
}
func (idx *Index) String() string {
return fmt.Sprintf("%#v", idx)
}
// NewIndex creates an index with a name.
func NewIndex(name string) *Index {
options := &IndexOptions{}
return &Index{
name: name,
options: options.withDefaults(),
fields: map[string]*Field{},
}
}
func (idx *Index) ShardWidth() uint64 {
return idx.shardWidth
}
// Fields return a copy of the fields in this index
func (idx *Index) Fields() map[string]*Field {
result := make(map[string]*Field)
for k, v := range idx.fields {
result[k] = v.copy()
}
return result
}
// HasFields returns true if the given field exists in the index.
func (idx *Index) HasField(fieldName string) bool {
_, ok := idx.fields[fieldName]
return ok
}
func (idx *Index) copy() *Index {
fields := make(map[string]*Field)
for name, f := range idx.fields {
fields[name] = f.copy()
}
index := &Index{
name: idx.name,
options: &IndexOptions{},
fields: fields,
shardWidth: idx.shardWidth,
}
*index.options = *idx.options
return index
}
// Name returns the name of this index.
func (idx *Index) Name() string {
return idx.name
}
// Opts returns the options of this index.
func (idx *Index) Opts() IndexOptions {
return *idx.options
}
// Field creates a Field struct with the specified name and defaults.
func (idx *Index) Field(name string, options ...FieldOption) *Field {
if field, ok := idx.fields[name]; ok {
return field
}
fieldOptions := &FieldOptions{}
fieldOptions = fieldOptions.withDefaults()
fieldOptions.addOptions(options...)
return idx.fieldWithOptions(name, fieldOptions)
}
func (idx *Index) fieldWithOptions(name string, fieldOptions *FieldOptions) *Field {
field := newField(name, idx)
fieldOptions = fieldOptions.withDefaults()
field.options = fieldOptions
idx.fields[name] = field
return field
}
// BatchQuery creates a batch query with the given queries.
func (idx *Index) BatchQuery(queries ...PQLQuery) *PQLBatchQuery {
stringQueries := make([]string, 0, len(queries))
hasKeys := false
for _, query := range queries {
serializedQuery := query.Serialize()
hasKeys = hasKeys || serializedQuery.HasWriteKeys()
stringQueries = append(stringQueries, serializedQuery.String())
}
return &PQLBatchQuery{
index: idx,
queries: stringQueries,
hasKeys: hasKeys,
}
}
// RawQuery creates a query with the given string.
// Note that the query is not validated before sending to the server.
func (idx *Index) RawQuery(query string) *PQLBaseQuery {
q := NewPQLBaseQuery(query, idx, nil)
// NOTE: raw queries always assumed to have keys set
q.hasKeys = true
return q
}
// Union creates a Union query.
// Union performs a logical OR on the results of each ROW_CALL query passed to it.
func (idx *Index) Union(rows ...*PQLRowQuery) *PQLRowQuery {
return idx.rowOperation("Union", rows...)
}
// Intersect creates an Intersect query.
// Intersect performs a logical AND on the results of each ROW_CALL query passed to it.
func (idx *Index) Intersect(rows ...*PQLRowQuery) *PQLRowQuery {
if len(rows) < 1 {
return NewPQLRowQuery("", idx, NewError("Intersect operation requires at least 1 row"))
}
return idx.rowOperation("Intersect", rows...)
}
// Difference creates an Intersect query.
// Difference returns all of the columns from the first ROW_CALL argument passed to it, without the columns from each subsequent ROW_CALL.
func (idx *Index) Difference(rows ...*PQLRowQuery) *PQLRowQuery {
if len(rows) < 1 {
return NewPQLRowQuery("", idx, NewError("Difference operation requires at least 1 row"))
}
return idx.rowOperation("Difference", rows...)
}
// Xor creates an Xor query.
func (idx *Index) Xor(rows ...*PQLRowQuery) *PQLRowQuery {
if len(rows) < 2 {
return NewPQLRowQuery("", idx, NewError("Xor operation requires at least 2 rows"))
}
return idx.rowOperation("Xor", rows...)
}
// Not creates a Not query.
func (idx *Index) Not(row *PQLRowQuery) *PQLRowQuery {
return NewPQLRowQuery(fmt.Sprintf("Not(%s)", row.serialize()), idx, row.Error())
}
// Count creates a Count query.
// Returns the number of set columns in the ROW_CALL passed in.
func (idx *Index) Count(row *PQLRowQuery) *PQLBaseQuery {
serializedQuery := row.serialize()
q := NewPQLBaseQuery(fmt.Sprintf("Count(%s)", serializedQuery.String()), idx, nil)
q.hasKeys = q.hasKeys || serializedQuery.HasWriteKeys()
return q
}
// SetColumnAttrs creates a SetColumnAttrs query.
// SetColumnAttrs associates arbitrary key/value pairs with a column in an index.
// Following types are accepted: integer, float, string and boolean types.
func (idx *Index) SetColumnAttrs(colIDOrKey interface{}, attrs map[string]interface{}) *PQLBaseQuery {
colStr, err := formatIDKey(colIDOrKey)
if err != nil {
return NewPQLBaseQuery("", idx, err)
}
attrsString, err := createAttributesString(attrs)
if err != nil {
return NewPQLBaseQuery("", idx, err)
}
q := fmt.Sprintf("SetColumnAttrs(%s,%s)", colStr, attrsString)
return NewPQLBaseQuery(q, idx, nil)
}
// Options creates an Options query.
func (idx *Index) Options(row *PQLRowQuery, opts ...OptionsOption) *PQLBaseQuery {
oo := &OptionsOptions{}
for _, opt := range opts {
opt(oo)
}
text := fmt.Sprintf("Options(%s,%s)", row.serialize(), oo.marshal())
return NewPQLBaseQuery(text, idx, nil)
}
type groupByBuilder struct {
rows []*PQLRowsQuery
limit int64
filter *PQLRowQuery
aggregate *PQLBaseQuery
having *PQLBaseQuery
}
// GroupByBuilderOption is a functional option type for index.GroupBy
type GroupByBuilderOption func(g *groupByBuilder) error
// OptGroupByBuilderRows is a functional option on groupByBuilder
// used to set the rows.
func OptGroupByBuilderRows(rows ...*PQLRowsQuery) GroupByBuilderOption {
return func(g *groupByBuilder) error {
g.rows = rows
return nil
}
}
// OptGroupByBuilderLimit is a functional option on groupByBuilder
// used to set the limit.
func OptGroupByBuilderLimit(l int64) GroupByBuilderOption {
return func(g *groupByBuilder) error {
g.limit = l
return nil
}
}
// OptGroupByBuilderFilter is a functional option on groupByBuilder
// used to set the filter.
func OptGroupByBuilderFilter(q *PQLRowQuery) GroupByBuilderOption {
return func(g *groupByBuilder) error {
g.filter = q
return nil
}
}
// OptGroupByBuilderAggregate is a functional option on groupByBuilder
// used to set the aggregate.
func OptGroupByBuilderAggregate(agg *PQLBaseQuery) GroupByBuilderOption {
return func(g *groupByBuilder) error {
g.aggregate = agg
return nil
}
}
// OptGroupByBuilderHaving is a functional option on groupByBuilder
// used to set the having clause.
func OptGroupByBuilderHaving(having *PQLBaseQuery) GroupByBuilderOption {
return func(g *groupByBuilder) error {
g.having = having
return nil
}
}
// GroupByBase creates a GroupBy query with the given functional options.
func (idx *Index) GroupByBase(opts ...GroupByBuilderOption) *PQLBaseQuery {
bldr := &groupByBuilder{}
for _, opt := range opts {
err := opt(bldr)
if err != nil {
return NewPQLBaseQuery("", idx, errors.Wrap(err, "applying option"))
}
}
if len(bldr.rows) < 1 {
return NewPQLBaseQuery("", idx, errors.New("there should be at least one rows query"))
}
if bldr.limit < 0 {
return NewPQLBaseQuery("", idx, errors.New("limit must be non-negative"))
}
// rows
text := fmt.Sprintf("GroupBy(%s", strings.Join(serializeGroupBy(bldr.rows...), ","))
// limit
if bldr.limit > 0 {
text += fmt.Sprintf(",limit=%d", bldr.limit)
}
// filter
if bldr.filter != nil {
filterText := bldr.filter.serialize().String()
text += fmt.Sprintf(",filter=%s", filterText)
}
// aggregate
if bldr.aggregate != nil {
aggregateText := bldr.aggregate.Serialize().String()
text += fmt.Sprintf(",aggregate=%s", aggregateText)
}
// having
if bldr.having != nil {
havingText := bldr.having.Serialize().String()
text += fmt.Sprintf(",having=%s", havingText)
}
text += ")"
return NewPQLBaseQuery(text, idx, nil)
}
// GroupBy creates a GroupBy query with the given Rows queries
func (idx *Index) GroupBy(rowsQueries ...*PQLRowsQuery) *PQLBaseQuery {
if len(rowsQueries) < 1 {
return NewPQLBaseQuery("", idx, errors.New("there should be at least one rows query"))
}
text := fmt.Sprintf("GroupBy(%s)", strings.Join(serializeGroupBy(rowsQueries...), ","))
return NewPQLBaseQuery(text, idx, nil)
}
// GroupByLimit creates a GroupBy query with the given limit and Rows queries
func (idx *Index) GroupByLimit(limit int64, rowsQueries ...*PQLRowsQuery) *PQLBaseQuery {
if len(rowsQueries) < 1 {
return NewPQLBaseQuery("", idx, errors.New("there should be at least one rows query"))
}
if limit < 0 {
return NewPQLBaseQuery("", idx, errors.New("limit must be non-negative"))
}
text := fmt.Sprintf("GroupBy(%s,limit=%d)", strings.Join(serializeGroupBy(rowsQueries...), ","), limit)
return NewPQLBaseQuery(text, idx, nil)
}
// GroupByFilter creates a GroupBy query with the given filter and Rows queries
func (idx *Index) GroupByFilter(filterQuery *PQLRowQuery, rowsQueries ...*PQLRowsQuery) *PQLBaseQuery {
if len(rowsQueries) < 1 {
return NewPQLBaseQuery("", idx, errors.New("there should be at least one rows query"))
}
filterText := filterQuery.serialize().String()
text := fmt.Sprintf("GroupBy(%s,filter=%s)", strings.Join(serializeGroupBy(rowsQueries...), ","), filterText)
return NewPQLBaseQuery(text, idx, nil)
}
// GroupByLimitFilter creates a GroupBy query with the given filter and Rows queries
func (idx *Index) GroupByLimitFilter(limit int64, filterQuery *PQLRowQuery, rowsQueries ...*PQLRowsQuery) *PQLBaseQuery {
if len(rowsQueries) < 1 {
return NewPQLBaseQuery("", idx, errors.New("there should be at least one rows query"))
}
if limit < 0 {
return NewPQLBaseQuery("", idx, errors.New("limit must be non-negative"))
}
filterText := filterQuery.serialize().String()
text := fmt.Sprintf("GroupBy(%s,limit=%d,filter=%s)", strings.Join(serializeGroupBy(rowsQueries...), ","), limit, filterText)
return NewPQLBaseQuery(text, idx, nil)
}
func (idx *Index) rowOperation(name string, rows ...*PQLRowQuery) *PQLRowQuery {
var err error
args := make([]string, 0, len(rows))
for _, row := range rows {
if err = row.Error(); err != nil {
return NewPQLRowQuery("", idx, err)
}
args = append(args, row.serialize().String())
}
query := NewPQLRowQuery(fmt.Sprintf("%s(%s)", name, strings.Join(args, ",")), idx, nil)
return query
}
func serializeGroupBy(rowsQueries ...*PQLRowsQuery) []string {
qs := make([]string, 0, len(rowsQueries))
for _, qry := range rowsQueries {
qs = append(qs, qry.serialize().String())
}
return qs
}
// FieldInfo represents schema information for a field.
type FieldInfo struct {
Name string `json:"name"`
}
// FieldOptions contains options to customize Field objects and field queries.
type FieldOptions struct {
fieldType FieldType
timeQuantum TimeQuantum
cacheType CacheType
cacheSize int
min int64
max int64
keys bool
noStandardView bool
}
// Type returns the type of the field. Currently "set", "int", or "time".
func (fo FieldOptions) Type() FieldType {
return fo.fieldType
}
// TimeQuantum returns the configured time quantum for a time field. Empty
// string otherwise.
func (fo FieldOptions) TimeQuantum() TimeQuantum {
return fo.timeQuantum
}
// CacheType returns the configured cache type for a "set" field. Empty string
// otherwise.
func (fo FieldOptions) CacheType() CacheType {
return fo.cacheType
}
// CacheSize returns the cache size for a set field. Zero otherwise.
func (fo FieldOptions) CacheSize() int {
return fo.cacheSize
}
// Min returns the minimum accepted value for an integer field. Zero otherwise.
func (fo FieldOptions) Min() int64 {
return fo.min
}
// Max returns the maximum accepted value for an integer field. Zero otherwise.
func (fo FieldOptions) Max() int64 {
return fo.max
}
// Keys returns whether this field uses keys instead of IDs
func (fo FieldOptions) Keys() bool {
return fo.keys
}
// NoStandardView suppresses creating the standard view for supported field types (currently, time)
func (fo FieldOptions) NoStandardView() bool {
return fo.noStandardView
}
func (fo *FieldOptions) withDefaults() (updated *FieldOptions) {
// copy options so the original is not updated
updated = &FieldOptions{}
*updated = *fo
if updated.fieldType == "" {
updated.fieldType = FieldTypeSet
}
return
}
func (fo FieldOptions) String() string {
mopt := map[string]interface{}{}
switch fo.fieldType {
case FieldTypeSet, FieldTypeMutex:
if fo.cacheType != CacheTypeDefault {
mopt["cacheType"] = string(fo.cacheType)
}
if fo.cacheSize > 0 {
mopt["cacheSize"] = fo.cacheSize
}
case FieldTypeInt:
mopt["min"] = fo.min
mopt["max"] = fo.max
case FieldTypeTime:
mopt["timeQuantum"] = string(fo.timeQuantum)
mopt["noStandardView"] = fo.noStandardView
}
if fo.fieldType != FieldTypeDefault {
mopt["type"] = string(fo.fieldType)
}
if fo.keys {
mopt["keys"] = fo.keys
}
return fmt.Sprintf(`{"options":%s}`, encodeMap(mopt))
}
func (fo *FieldOptions) addOptions(options ...FieldOption) {
for _, option := range options {
if option == nil {
continue
}
option(fo)
}
}
// FieldOption is used to pass an option to index.Field function.
type FieldOption func(options *FieldOptions)
// OptFieldTypeSet adds a set field.
// Specify CacheTypeDefault for the default cache type.
// Specify CacheSizeDefault for the default cache size.
func OptFieldTypeSet(cacheType CacheType, cacheSize int) FieldOption {
return func(options *FieldOptions) {
options.fieldType = FieldTypeSet
options.cacheType = cacheType
options.cacheSize = cacheSize
}
}
// OptFieldTypeInt adds an integer field.
// No arguments: min = min_int, max = max_int
// 1 argument: min = limit[0], max = max_int
// 2 or more arguments: min = limit[0], max = limit[1]
func OptFieldTypeInt(limits ...int64) FieldOption {
min := int64(math.MinInt64)
max := int64(math.MaxInt64)
if len(limits) > 2 {
panic("error: OptFieldTypInt accepts at most 2 arguments")
}
if len(limits) > 0 {
min = limits[0]
}
if len(limits) > 1 {
max = limits[1]
}
return func(options *FieldOptions) {
options.fieldType = FieldTypeInt
options.min = min
options.max = max
}
}
// OptFieldTypeTime adds a time field.
func OptFieldTypeTime(quantum TimeQuantum, opts ...bool) FieldOption {
return func(options *FieldOptions) {
options.fieldType = FieldTypeTime
options.timeQuantum = quantum
if len(opts) > 0 && opts[0] {
options.noStandardView = true
}
}
}
// OptFieldTypeMutex adds a mutex field.
func OptFieldTypeMutex(cacheType CacheType, cacheSize int) FieldOption {
return func(options *FieldOptions) {
options.fieldType = FieldTypeMutex
options.cacheType = cacheType
options.cacheSize = cacheSize
}
}
// OptFieldTypeBool adds a bool field.
func OptFieldTypeBool() FieldOption {
return func(options *FieldOptions) {
options.fieldType = FieldTypeBool
}
}
// OptFieldKeys sets whether field uses string keys.
func OptFieldKeys(keys bool) FieldOption {
return func(options *FieldOptions) {
options.keys = keys
}
}
// Field structs are used to segment and define different functional characteristics within your entire index.
// You can think of a Field as a table-like data partition within your Index.
// Row-level attributes are namespaced at the Field level.
type Field struct {
name string
index *Index
options *FieldOptions
}
func (f *Field) String() string {
return fmt.Sprintf("%#v", f)
}
func newField(name string, index *Index) *Field {
return &Field{
name: name,
index: index,
options: &FieldOptions{},
}
}
// Name returns the name of the field
func (f *Field) Name() string {
return f.name
}
// Opts returns the options of the field
func (f *Field) Opts() FieldOptions {
return *f.options
}
func (f *Field) copy() *Field {
field := newField(f.name, f.index)
*field.options = *f.options
return field
}
// Row creates a Row query.
// Row retrieves the indices of all the set columns in a row.
// It also retrieves any attributes set on that row or column.
func (f *Field) Row(rowIDOrKey interface{}) *PQLRowQuery {
rowStr, err := formatIDKeyBool(rowIDOrKey)
if err != nil {
return NewPQLRowQuery("", f.index, err)
}
text := fmt.Sprintf("Row(%s=%s)", f.name, rowStr)
q := NewPQLRowQuery(text, f.index, nil)
return q
}
// Set creates a Set query.
// Set, assigns a value of 1 to a bit in the binary matrix, thus associating the given row in the given field with the given column.
func (f *Field) Set(rowIDOrKey, colIDOrKey interface{}) *PQLBaseQuery {
rowStr, colStr, err := formatRowColIDKey(rowIDOrKey, colIDOrKey)
if err != nil {
return NewPQLBaseQuery("", f.index, err)
}
text := fmt.Sprintf("Set(%s,%s=%s)", colStr, f.name, rowStr)
q := NewPQLBaseQuery(text, f.index, nil)
q.hasKeys = f.options.keys || f.index.options.keys
return q
}
// SetTimestamp creates a Set query with timestamp.
// Set, assigns a value of 1 to a column in the binary matrix,
// thus associating the given row in the given field with the given column.
func (f *Field) SetTimestamp(rowIDOrKey, colIDOrKey interface{}, timestamp time.Time) *PQLBaseQuery {
rowStr, colStr, err := formatRowColIDKey(rowIDOrKey, colIDOrKey)
if err != nil {
return NewPQLBaseQuery("", f.index, err)
}
text := fmt.Sprintf("Set(%s,%s=%s,%s)", colStr, f.name, rowStr, timestamp.Format(timeFormat))
q := NewPQLBaseQuery(text, f.index, nil)
q.hasKeys = f.options.keys || f.index.options.keys
return q