-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathmapper.go
More file actions
2065 lines (1834 loc) · 56.9 KB
/
Copy pathmapper.go
File metadata and controls
2065 lines (1834 loc) · 56.9 KB
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 2022 Democratized Data Foundation
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package mapper
import (
"context"
"reflect"
"strings"
"github.com/sourcenetwork/immutable"
"github.com/sourcenetwork/defradb/client"
"github.com/sourcenetwork/defradb/client/options"
"github.com/sourcenetwork/defradb/client/request"
"github.com/sourcenetwork/defradb/internal/connor"
"github.com/sourcenetwork/defradb/internal/core"
"github.com/sourcenetwork/defradb/internal/db/description"
"github.com/sourcenetwork/defradb/internal/db/id"
iIdentity "github.com/sourcenetwork/defradb/internal/identity"
)
const (
// topLevelCollectionName is a dummy collection name to indicate that this item is at the outer most
// level of the query, typically an aggregate over an entire collection.
topLevelCollectionName string = "_topLevel"
)
var (
FilterEqOp = &Operator{Operation: connor.EqualOp}
)
// SelectionType is the type of selection.
type SelectionType int
const (
ObjectSelection SelectionType = iota
CommitSelection
EncryptedSearchSelection
)
// ToOperation converts the given [request.OperationDefinition] into an [Operation].
//
// In the process of doing so it will construct the document map required to access the data
// yielded by the [Operation].
func ToOperation(
ctx context.Context,
store client.TxnStore,
collectionRepository *description.CollectionRepository,
operationRequest *request.OperationDefinition,
) (*Operation, error) {
operation := &Operation{
DocumentMapping: core.NewDocumentMapping(),
Exhaustive: operationRequest.Directives.Exhaustive,
}
for i, s := range operationRequest.Selections {
switch t := s.(type) {
case *request.CommitSelect:
s, err := toCommitSelect(ctx, store, collectionRepository, t, i)
if err != nil {
return nil, err
}
operation.CommitSelects = append(operation.CommitSelects, s)
operation.addSelection(i, t.Field, s.Select)
case *request.Select:
s, err := toSelect(ctx, store, collectionRepository, ObjectSelection, i, t, "")
if err != nil {
return nil, err
}
operation.Selects = append(operation.Selects, s)
operation.addSelection(i, t.Field, *s)
case *request.ObjectMutation:
m, err := toMutation(ctx, store, collectionRepository, t, i)
if err != nil {
return nil, err
}
operation.Mutations = append(operation.Mutations, m)
operation.addSelection(i, t.Field, m.Select)
default:
return nil, ErrInvalidSelect
}
}
return operation, nil
}
// ToSelect converts the given [request.Select] into a [Select].
//
// In the process of doing so it will construct the document map required to access the data
// yielded by the [Select].
func ToSelect(
ctx context.Context,
store client.TxnStore,
collectionRepository *description.CollectionRepository,
rootSelectType SelectionType,
selectRequest *request.Select,
) (*Select, error) {
// the top-level select will always have index=0, and no parent collection name
return toSelect(ctx, store, collectionRepository, rootSelectType, 0, selectRequest, "")
}
// toSelect converts the given [parser.Select] into a [Select].
//
// In the process of doing so it will construct the document map required to access the data
// yielded by the [Select].
func toSelect(
ctx context.Context,
store client.TxnStore,
collectionRepository *description.CollectionRepository,
rootSelectType SelectionType,
thisIndex int,
selectRequest *request.Select,
parentCollectionName string,
) (*Select, error) {
if rootSelectType == ObjectSelection && selectRequest.Name == request.VersionFieldName {
// WARNING: This is a weird quirk upon which some of the mapper code is dependent upon
// please remove it if/when you have chance to.
rootSelectType = CommitSelection
}
if selectRequest.IsEncrypted {
rootSelectType = EncryptedSearchSelection
}
collectionName, err := getCollectionName(
ctx,
collectionRepository,
rootSelectType,
selectRequest,
parentCollectionName,
)
if err != nil {
return nil, err
}
mapping, definition, err := getTopLevelInfo(ctx, store, rootSelectType, selectRequest, collectionName)
if err != nil {
return nil, err
}
fields, aggregates, err := getRequestables(
ctx,
collectionRepository,
rootSelectType,
selectRequest,
mapping,
collectionName,
store,
)
if err != nil {
return nil, err
}
// Needs to be done before resolving aggregates, else filter conversion may fail there
filterDependencies, err := resolveFilterDependencies(
ctx, store, collectionRepository, rootSelectType, collectionName, selectRequest.Filter, mapping, fields)
if err != nil {
return nil, err
}
fields = append(fields, filterDependencies...)
// Resolve order dependencies that may have been missed due to not being rendered.
err = resolveOrderDependencies(
ctx, store, collectionRepository, rootSelectType, collectionName, selectRequest.OrderBy, mapping, &fields)
if err != nil {
return nil, err
}
aggregates = appendUnderlyingAggregates(aggregates, mapping)
fields, err = resolveAggregates(
ctx,
collectionRepository,
rootSelectType,
aggregates,
fields,
mapping,
collectionName,
definition,
store,
)
if err != nil {
return nil, err
}
if len(definition.Fields) != 0 {
fields, err = resolveSecondaryRelationIDs(
ctx,
store,
collectionRepository,
rootSelectType,
collectionName,
definition,
mapping,
fields,
)
if err != nil {
return nil, err
}
}
// Resolve groupBy dependencies: alias/relation remapping, map the missed inner
// group field, and ensure groupBy fields are fetched even when not part of the
// selection set.
fields, err = resolveGroupByDependencies(definition, selectRequest, mapping, fields)
if err != nil {
return nil, err
}
targetable, err := toTargetable(thisIndex, selectRequest, mapping)
if err != nil {
return nil, err
}
return &Select{
Targetable: targetable,
DocumentMapping: mapping,
Cids: selectRequest.CIDs,
CollectionName: collectionName,
Fields: fields,
IsEncrypted: selectRequest.IsEncrypted,
}, nil
}
// resolveOrderDependencies will map fields that were missed due to them not being requested.
// Modifies the consumed existingFields and mapping accordingly.
func resolveOrderDependencies(
ctx context.Context,
store client.TxnStore,
collectionRepository *description.CollectionRepository,
rootSelectType SelectionType,
descName string,
source immutable.Option[request.OrderBy],
mapping *core.DocumentMapping,
existingFields *[]Requestable,
) error {
if !source.HasValue() {
return nil
}
currentExistingFields := existingFields
// If there is orderby, and any one of the condition fields that are join fields and have not been
// requested, we need to map them here.
outer:
for _, condition := range source.Value().Conditions {
fields := condition.Fields[:] // copy slice
for {
// alias fields are guaranteed to be resolved
// because they refer to existing fields
if fields[0] == request.AliasFieldName {
continue outer
}
numFields := len(fields)
// <2 fields: Direct field on the root type: {age: DESC}
// 2 fields: Single depth related type: {author: {age: DESC}}
// >2 fields: Multi depth related type: {author: {friends: {age: DESC}}}
if numFields == 2 {
joinField := fields[0]
// ensure the child select is resolved for this order join
innerSelect, err := resolveChildOrder(
ctx,
store,
collectionRepository,
rootSelectType,
descName,
joinField,
mapping,
currentExistingFields,
)
if err != nil {
return err
}
// make sure the actual target field inside the join field
// is included in the select
targetFieldName := fields[1]
targetField := &Field{
Index: innerSelect.FirstIndexOfName(targetFieldName),
Name: targetFieldName,
}
innerSelect.Fields = append(innerSelect.Fields, targetField)
continue outer
} else if numFields > 2 {
joinField := fields[0]
// ensure the child select is resolved for this order join
innerSelect, err := resolveChildOrder(
ctx,
store,
collectionRepository,
rootSelectType,
descName,
joinField,
mapping,
existingFields,
)
if err != nil {
return err
}
mapping = innerSelect.DocumentMapping
currentExistingFields = &innerSelect.Fields
fields = fields[1:] // chop off the front item, and loop again on inner
} else { // <= 1
targetFieldName := fields[0]
*existingFields = append(*existingFields, &Field{
Index: mapping.FirstIndexOfName(targetFieldName),
Name: targetFieldName,
})
// nothing todo, continue the outer for loop
continue outer
}
}
}
return nil
}
// given a type join field, ensure its mapping exists
// and add a coorsponding select field(s)
func resolveChildOrder(
ctx context.Context,
store client.TxnStore,
collectionRepository *description.CollectionRepository,
rootSelectType SelectionType,
descName string,
orderChildField string,
mapping *core.DocumentMapping,
existingFields *[]Requestable,
) (*Select, error) {
childFieldIndexes := mapping.IndexesByName[orderChildField]
// Check if the join field is already mapped, if not then map it.
if len(childFieldIndexes) == 0 {
index := mapping.GetNextIndex()
mapping.Add(index, orderChildField)
// Resolve the inner child fields and get it's mapping.
dummyJoinFieldSelect := request.Select{
Field: request.Field{
Name: orderChildField,
},
}
innerSelect, err := toSelect(ctx, store, collectionRepository, rootSelectType, index, &dummyJoinFieldSelect, descName)
if err != nil {
return nil, err
}
*existingFields = append(*existingFields, innerSelect)
mapping.SetChildAt(index, innerSelect.DocumentMapping)
return innerSelect, nil
} else {
for _, field := range *existingFields {
fieldSelect, ok := field.(*Select)
if !ok {
continue
}
if fieldSelect.Field.Name == orderChildField {
return fieldSelect, nil
}
}
}
return nil, ErrMissingSelect
}
// resolveGroupByDependencies remaps the groupBy fields to their internal field names,
// maps the synthetic GROUP field if no inner group was requested, and ensures that
// every groupBy field is fetched even when it is not part of the selection set.
//
// This mirrors how [resolveOrderDependencies] adds order fields that were missed due
// to not being rendered.
func resolveGroupByDependencies(
definition client.CollectionVersion,
selectRequest *request.Select,
mapping *core.DocumentMapping,
fields []Requestable,
) ([]Requestable, error) {
if !selectRequest.GroupBy.HasValue() {
return fields, nil
}
groupByFields := selectRequest.GroupBy.Value().Fields
// Remap all object (relation) field names to use their internal foreign-key field
// id, as that is the scalar value actually stored on - and fetched from - the document.
for index, groupByField := range groupByFields {
fieldDesc, ok := definition.GetFieldByName(groupByField)
if ok && fieldDesc.Kind.IsObject() {
if fieldDesc.Kind.IsArray() {
return nil, NewErrInvalidFieldToGroupBy(groupByField)
}
groupByFields[index] = request.ToFieldID(groupByField)
}
}
selectRequest.GroupBy = immutable.Some(
request.GroupBy{
Fields: groupByFields,
},
)
// If there is a groupBy, and no inner group has been requested, we need to map the property here
if _, isGroupFieldMapped := mapping.IndexesByName[request.GroupFieldName]; !isGroupFieldMapped {
index := mapping.GetNextIndex()
mapping.Add(index, request.GroupFieldName)
}
// Ensure every groupBy field is fetched, even when it is not part of the selection
// set. The field is added as a hidden dependency (it is given no render key) so that
// its value is available for group-key computation without being returned in the response.
for _, groupByField := range groupByFields {
alreadyRequested := false
for _, existingField := range fields {
if existingField.GetName() == groupByField {
alreadyRequested = true
break
}
}
if alreadyRequested {
continue
}
fieldIndexes := mapping.IndexesByName[groupByField]
if len(fieldIndexes) == 0 {
// Should be unreachable for a valid groupBy field as all base fields are
// mapped by getTopLevelInfo, but guard against an out-of-range panic.
continue
}
fields = append(fields, &Field{
Index: fieldIndexes[0],
Name: groupByField,
})
}
return fields, nil
}
// resolveAggregates figures out which fields the given aggregates are targeting
// and converts the aggregateRequest into an Aggregate, appending it onto the given
// fields slice.
//
// If an aggregate targets a field that doesn't yet exist, it will create it and
// append the new target field as well as the aggregate. The mapping will also be
// updated with any new fields/aggregates.
func resolveAggregates(
ctx context.Context,
collectionRepository *description.CollectionRepository,
rootSelectType SelectionType,
aggregates []*aggregateRequest,
inputFields []Requestable,
mapping *core.DocumentMapping,
collectionName string,
def client.CollectionVersion,
store client.TxnStore,
) ([]Requestable, error) {
var collectionShortID uint32
if def.CollectionID != "" {
var err error
collectionShortID, err = id.GetShortCollectionID(ctx, def.CollectionID)
if err != nil {
return nil, err
}
}
fields := inputFields
dependenciesByParentId := map[int][]int{}
for _, aggregate := range aggregates {
aggregateTargets := make([]AggregateTarget, len(aggregate.targets))
for i, target := range aggregate.targets {
var host Requestable
var hostTarget *Targetable
var childTarget OptionalChildTarget
// If the host has not been requested the child mapping may not yet exist and
// we must create it before we can convert the filter.
childIsMapped := len(mapping.IndexesByName[target.hostExternalName]) != 0
var hasHost bool
var convertedFilter *Filter
if childIsMapped {
fieldDesc, isField := def.GetFieldByName(target.hostExternalName)
if isField && !fieldDesc.Kind.IsObject() {
var order *OrderBy
if target.order.HasValue() && len(target.order.Value().Conditions) > 0 {
// For inline arrays the order element will consist of just a direction
order = &OrderBy{
Conditions: []OrderCondition{
{
Direction: SortDirection(target.order.Value().Conditions[0].Direction),
},
},
}
}
fieldShortID, err := id.GetShortFieldID(ctx, collectionShortID, fieldDesc.FieldID)
if err != nil {
return nil, err
}
// If the hostExternalName matches a non-object field
// we don't have to search for it and can just construct the
// targeting info here.
hasHost = true
host = &Targetable{
Field: Field{
Index: int(fieldShortID),
Name: target.hostExternalName,
},
Filter: ToFilter(target.filter.Value(), mapping),
Limit: target.limit,
OrderBy: order,
}
} else {
childObjectIndex := mapping.FirstIndexOfName(target.hostExternalName)
childMapping := mapping.ChildMappings[childObjectIndex]
convertedFilter = ToFilter(target.filter.Value(), childMapping)
orderBy, err := toOrderBy(target.order, childMapping)
if err != nil {
return nil, err
}
host, hasHost = tryGetTarget(
target.hostExternalName,
convertedFilter,
target.limit,
orderBy,
fields,
)
}
}
if !hasHost {
// If a matching host is not found, we need to construct and add it.
index := mapping.GetNextIndex()
hostSelectRequest := &request.Select{
Field: request.Field{
Name: target.hostExternalName,
},
}
if collectionName == topLevelCollectionName {
collectionName = ""
}
childCollectionName, err := getCollectionName(
ctx,
collectionRepository,
rootSelectType,
hostSelectRequest,
collectionName,
)
if err != nil {
return nil, err
}
mapAggregateNestedTargets(target, hostSelectRequest)
childMapping, _, err := getTopLevelInfo(ctx, store, rootSelectType, hostSelectRequest, childCollectionName)
if err != nil {
return nil, err
}
removeJSONSubFields(childMapping, hostSelectRequest)
childFields, _, err := getRequestables(
ctx,
collectionRepository,
rootSelectType,
hostSelectRequest,
childMapping,
childCollectionName,
store,
)
if err != nil {
return nil, err
}
err = resolveOrderDependencies(
ctx, store, collectionRepository, rootSelectType, childCollectionName, target.order, childMapping, &childFields)
if err != nil {
return nil, err
}
childMapping = childMapping.CloneWithoutRender()
mapping.SetChildAt(index, childMapping)
filterDependencies, err := resolveFilterDependencies(
ctx,
store,
collectionRepository,
rootSelectType,
childCollectionName,
target.filter,
mapping.ChildMappings[index],
childFields,
)
if err != nil {
return nil, err
}
childFields = append(childFields, filterDependencies...)
// If the child was not mapped, the filter will not have been converted yet
// so we must do that now.
convertedFilter = ToFilter(target.filter.Value(), mapping.ChildMappings[index])
orderBy, err := toOrderBy(target.order, childMapping)
if err != nil {
return nil, err
}
var dummyJoin Requestable
dummyJoinSelect := &Select{
Targetable: Targetable{
Field: Field{
Index: index,
Name: target.hostExternalName,
},
Filter: convertedFilter,
Limit: target.limit,
OrderBy: orderBy,
},
CollectionName: childCollectionName,
DocumentMapping: childMapping,
Fields: childFields,
}
hostTarget = &dummyJoinSelect.Targetable
if rootSelectType == CommitSelection {
dummyJoinCommit := &CommitSelect{
Select: *dummyJoinSelect,
Depth: immutable.Some(uint64(0)),
}
index := childMapping.FirstIndexOfName(request.CidFieldName)
dummyJoinCommit.Fields = append(dummyJoinCommit.Fields, &Field{
Index: index,
Name: request.CidFieldName,
})
dummyJoin = dummyJoinCommit
} else {
dummyJoin = dummyJoinSelect
}
fields = append(fields, dummyJoin)
mapping.Add(index, target.hostExternalName)
host = dummyJoin
} else {
var isTargetable bool
hostTarget, isTargetable = host.AsTargetable()
if !isTargetable {
// If the host is not targetable, such as when it is an inline-array field,
// we don't need to worry about preserving the targetable information and
// can just take the field properties.
hostTarget = &Targetable{
Field: Field{
Index: host.GetIndex(),
Name: host.GetName(),
},
}
}
}
if target.childExternalName != "" {
hostSelect, isHostSelectable := host.AsSelect()
if !isHostSelectable {
// I believe this is dead code as the gql library should always catch this error first
return nil, client.NewErrUnhandledType("host", host)
}
if len(hostSelect.IndexesByName[target.childExternalName]) == 0 {
// I believe this is dead code as the gql library should always catch this error first
return nil, ErrUnableToIdAggregateChild
}
// ensure target aggregate field is included in the type join
hostSelect.Fields = append(hostSelect.Fields, &Field{
Index: hostSelect.DocumentMapping.FirstIndexOfName(target.childExternalName),
Name: target.childExternalName,
})
childTarget = OptionalChildTarget{
// If there are multiple children of the same name there is no way
// for us (or the consumer) to identify which one they are hoping for
// so we take the first.
Index: hostSelect.IndexesByName[target.childExternalName][0],
Name: target.childExternalName,
HasValue: true,
}
}
aggregateTargets[i] = AggregateTarget{
Targetable: *hostTarget,
ChildTarget: childTarget,
}
}
newAggregate := Aggregate{
Field: aggregate.field,
DocumentMapping: mapping,
AggregateTargets: aggregateTargets,
}
fields = append(fields, &newAggregate)
dependenciesByParentId[aggregate.field.Index] = aggregate.dependencyIndexes
}
// Once aggregates have been resolved we pair up their dependencies
for aggregateId, dependencyIds := range dependenciesByParentId {
aggregate := fieldAt(fields, aggregateId).(*Aggregate)
for _, dependencyId := range dependencyIds {
aggregate.Dependencies = append(aggregate.Dependencies, fieldAt(fields, dependencyId).(*Aggregate))
}
}
return fields, nil
}
// removeJSONSubFields ensures that selections of
// JSON objects are not interpreted as joins.
//
// This can happen when an aggregate contains a filter
// on a JSON object, but we can't tell if it is a relation
// until the child mapping is created.
func removeJSONSubFields(
mapping *core.DocumentMapping,
hostSelectRequest *request.Select,
) {
var fields []request.Selection
for _, field := range hostSelectRequest.Fields {
switch f := field.(type) {
case *request.Select:
_, isMapped := mapping.IndexesByName[f.Name]
if !isMapped {
fields = append(fields, field)
}
default:
fields = append(fields, field)
}
}
hostSelectRequest.Fields = fields
}
func mapAggregateNestedTargets(
target *aggregateRequestTarget,
hostSelectRequest *request.Select,
) {
if target.order.HasValue() {
for _, cond := range target.order.Value().Conditions {
if len(cond.Fields) > 1 {
hostSelectRequest.Fields = append(hostSelectRequest.Fields, &request.Select{
Field: request.Field{
Name: cond.Fields[0],
},
})
}
}
}
if target.filter.HasValue() {
for topKey, topCond := range target.filter.Value().Conditions {
switch cond := topCond.(type) {
case map[string]any:
for _, innerCond := range cond {
if _, isMap := innerCond.(map[string]any); isMap {
hostSelectRequest.Fields = append(hostSelectRequest.Fields, &request.Select{
Field: request.Field{
Name: topKey,
},
})
break
}
}
}
}
}
}
func fieldAt(fields []Requestable, index int) Requestable {
for _, f := range fields {
if f.GetIndex() == index {
return f
}
}
return nil
}
// aggregateDependencies maps aggregate names to the names of any aggregates
// that they may be dependent on.
var aggregateDependencies = map[string][]string{
request.AverageFieldName: {
request.CountFieldName,
request.SumFieldName,
},
}
// appendUnderlyingAggregates scans the given inputAggregates for any composite aggregates
// (e.g. average), and appends any missing dependencies to the collection and mapping.
//
// It will try and make use of existing aggregates that match the targeting parameters
// before creating new ones. It will also adjust the target filters if required (e.g.
// average skips nil items).
func appendUnderlyingAggregates(
inputAggregates []*aggregateRequest,
mapping *core.DocumentMapping,
) []*aggregateRequest {
aggregates := inputAggregates
// Loop through the aggregates slice, including items that may have been appended
// to the slice whilst looping.
for i := 0; i < len(aggregates); i++ {
aggregate := aggregates[i]
dependencies, hasDependencies := aggregateDependencies[aggregate.field.Name]
// If the aggregate has no dependencies, then we don't need to do anything and we continue.
if !hasDependencies {
continue
}
for _, target := range aggregate.targets {
if target.childExternalName != "" {
if _, isAggregate := request.Aggregates[target.childExternalName]; isAggregate {
continue
}
}
// Append a not-nil filter if the target is not an aggregate.
// If the target has no childExternalName we assume it is an inline-array (and thus not an aggregate).
// Aggregate-targets are excluded here as they are assumed to always have a value and
// amending the filter introduces significant complexity for both machine and developer.
appendNotNilFilter(target, target.childExternalName)
}
for _, dependencyName := range dependencies {
var newAggregate *aggregateRequest
aggregates, newAggregate = appendIfNotExists(
dependencyName,
aggregate.targets,
aggregates,
mapping,
)
aggregate.dependencyIndexes = append(aggregate.dependencyIndexes, newAggregate.field.Index)
}
}
return aggregates
}
// appendIfNotExists attempts to match the given name and targets against existing
// aggregates, if a match is not found, it will append a new aggregate.
func appendIfNotExists(
name string,
targets []*aggregateRequestTarget,
aggregates []*aggregateRequest,
mapping *core.DocumentMapping,
) ([]*aggregateRequest, *aggregateRequest) {
field, exists := tryGetMatchingAggregate(name, targets, aggregates)
if exists {
// If a match is found, there is nothing to do so we return the aggregates slice unchanged.
return aggregates, field
}
// If a match is not found, create, map and append the
// dependency to the aggregates collection.
index := mapping.GetNextIndex()
field = &aggregateRequest{
field: Field{
Index: index,
Name: name,
},
targets: targets,
}
mapping.Add(index, field.field.Name)
return append(aggregates, field), field
}
// getRequestables returns a converted slice of consumer-requested Requestables
// and aggregateRequests from the given selectRequest.Fields slice. It also mutates the
// consumed mapping data.
func getRequestables(
ctx context.Context,
collectionRepository *description.CollectionRepository,
rootSelectType SelectionType,
selectRequest *request.Select,
mapping *core.DocumentMapping,
collectionName string,
store client.TxnStore,
) (fields []Requestable, aggregates []*aggregateRequest, err error) {
for _, field := range selectRequest.Fields {
switch f := field.(type) {
case *request.Field:
// We can map all fields to the first (and only index)
// as they support no value modifiers (such as filters/limits/etc).
// All fields should have already been mapped by getTopLevelInfo
index := mapping.FirstIndexOfName(f.Name)
fields = append(fields, &Field{
Index: index,
Name: f.Name,
})
mapping.RenderKeys = append(mapping.RenderKeys, core.RenderKey{
Index: index,
Key: getRenderKey(f),
})
case *request.Select:
index := mapping.GetNextIndex()
innerSelect, err := toSelect(ctx, store, collectionRepository, rootSelectType, index, f, collectionName)
if err != nil {
return nil, nil, err
}
fields = append(fields, innerSelect)
mapping.SetChildAt(index, innerSelect.DocumentMapping)
mapping.RenderKeys = append(mapping.RenderKeys, core.RenderKey{
Index: index,
Key: getRenderKey(&f.Field),
})
mapping.Add(index, f.Name)
case *request.CommitSelect:
index := mapping.GetNextIndex()
innerSelect, err := toCommitSelect(ctx, store, collectionRepository, f, index)
if err != nil {
return nil, nil, err
}
fields = append(fields, innerSelect)
mapping.SetChildAt(index, innerSelect.DocumentMapping)
mapping.RenderKeys = append(mapping.RenderKeys, core.RenderKey{
Index: index,
Key: getRenderKey(&f.Field),
})
mapping.Add(index, f.Name)
case *request.Aggregate:
index := mapping.GetNextIndex()
aggregateRequest, err := getAggregateRequests(index, f)
if err != nil {
return nil, nil, err
}
aggregates = append(aggregates, &aggregateRequest)
mapping.RenderKeys = append(mapping.RenderKeys, core.RenderKey{
Index: index,
Key: getRenderKey(&f.Field),
})
mapping.Add(index, f.Name)
case *request.Similarity:
index := mapping.GetNextIndex()
fields = append(fields, &Similarity{
Field: Field{
Index: index,
Name: f.Name,
},
Vector: f.Vector,
SimilarityTarget: Targetable{
Field: Field{
Index: mapping.FirstIndexOfName(f.Target),
Name: f.Target,
},
},
})
mapping.RenderKeys = append(mapping.RenderKeys, core.RenderKey{
Index: index,
Key: getRenderKey(&f.Field),
})
mapping.Add(index, f.Name)
default:
return nil, nil, client.NewErrUnhandledType("field", field)
}
}
return
}
func getRenderKey(field *request.Field) string {
if field.Alias.HasValue() {
return field.Alias.Value()
}
return field.Name
}
func getAggregateRequests(index int, aggregate *request.Aggregate) (aggregateRequest, error) {
aggregateTargets, err := getAggregateSources(aggregate)
if err != nil {
return aggregateRequest{}, err
}
if len(aggregateTargets) == 0 {
return aggregateRequest{}, ErrAggregateTargetMissing
}