-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathmutation_rewriter.go
2302 lines (2045 loc) · 74.9 KB
/
mutation_rewriter.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 2019 Dgraph Labs, Inc. and Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package resolve
import (
"context"
"encoding/json"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
dgoapi "github.com/dgraph-io/dgo/v200/protos/api"
"github.com/dgraph-io/dgraph/gql"
"github.com/dgraph-io/dgraph/graphql/schema"
"github.com/dgraph-io/dgraph/x"
"github.com/pkg/errors"
)
const (
MutationQueryVar = "x"
MutationQueryVarUID = "uid(x)"
updateMutationCondition = `gt(len(x), 0)`
)
// Enum passed on to rewriteObject function.
type MutationType int
const (
// Add Mutation
Add MutationType = iota
// Add Mutation with Upsert
AddWithUpsert
// Update Mutation used for to setting new nodes, edges.
UpdateWithSet
// Update Mutation used for removing edges.
UpdateWithRemove
)
type Rewriter struct {
// VarGen is the VariableGenerator used accross RewriteQueries and Rewrite functions
// for Mutation. It generates unique variable names for DQL queries and mutations.
VarGen *VariableGenerator
// XidMetadata stores data like seenUIDs and variableObjMap to be used across Rewrite
// and RewriteQueries functions for Mutations.
XidMetadata *xidMetadata
// idExistence stores a map of variable names to UIDs. It is a map of nodes which
// were found after executing queries generated by RewriteQueries function. This is
// used in case of Add and Update Mutations.
idExistence map[string]string
}
type AddRewriter struct {
frags [][]*mutationFragment
Rewriter
}
type UpdateRewriter struct {
setFrags []*mutationFragment
delFrags []*mutationFragment
Rewriter
}
type deleteRewriter struct {
Rewriter
}
// A mutationFragment is a partially built Dgraph mutation. Given a GraphQL
// mutation input, we traverse the input data and build a Dgraph mutation. That
// mutation might require queries (e.g. to check types), conditions (to guard the
// upsert mutation to only run in the right conditions), post mutation checks (
// so we can investigate the mutation result and know what guarded mutations
// actually ran.
//
// In the case of XIDs a mutation might result in two fragments - one for the case
// of add a new object for the XID and another for link to an existing XID, depending
// on what condition evaluates to true in the upsert.
type mutationFragment struct {
queries []*gql.GraphQuery
conditions []string
fragment interface{}
deletes []interface{}
check resultChecker
newNodes map[string]schema.Type
err error
}
// xidMetadata is used to handle cases where we get multiple objects which have same xid value in a
// single mutation
type xidMetadata struct {
// variableObjMap stores the mapping of xidVariable -> the input object which contains that xid
variableObjMap map[string]map[string]interface{}
// seenAtTopLevel tells whether the xidVariable has been previously seen at top level or not
seenAtTopLevel map[string]bool
// seenUIDs tells whether the UID is previously been seen during DFS traversal
seenUIDs map[string]bool
}
// A mutationBuilder can build a json mutation []byte from a mutationFragment
type mutationBuilder func(frag *mutationFragment) ([]byte, error)
// A resultChecker checks an upsert (query) result and returns an error if the
// result indicates that the upsert didn't succeed.
type resultChecker func(map[string]interface{}) error
// A VariableGenerator generates unique variable names.
type VariableGenerator struct {
counter int
xidVarNameMap map[string]string
}
func NewVariableGenerator() *VariableGenerator {
return &VariableGenerator{
counter: 0,
xidVarNameMap: make(map[string]string),
}
}
// Next gets the Next variable name for the given type and xid.
// So, if two objects of the same type have same value for xid field,
// then they will get same variable name.
func (v *VariableGenerator) Next(typ schema.Type, xidName, xidVal string, auth bool) string {
// return previously allocated variable name for repeating xidVal
var key string
if xidName == "" || xidVal == "" {
key = typ.Name()
} else {
key = typ.FieldOriginatedFrom(xidName) + xidName + xidVal
}
if varName, ok := v.xidVarNameMap[key]; ok {
return varName
}
// create new variable name
v.counter++
var varName string
if auth {
varName = fmt.Sprintf("%sAuth%v", typ.Name(), v.counter)
} else {
varName = fmt.Sprintf("%s%v", typ.Name(), v.counter)
}
// save it, if it was created for xidVal
if xidName != "" && xidVal != "" {
v.xidVarNameMap[key] = varName
}
return varName
}
// NewAddRewriter returns new MutationRewriter for add & update mutations.
func NewAddRewriter() MutationRewriter {
return &AddRewriter{}
}
// NewUpdateRewriter returns new MutationRewriter for add & update mutations.
func NewUpdateRewriter() MutationRewriter {
return &UpdateRewriter{}
}
// NewDeleteRewriter returns new MutationRewriter for delete mutations..
func NewDeleteRewriter() MutationRewriter {
return &deleteRewriter{}
}
// NewXidMetadata returns a new empty *xidMetadata for storing the metadata.
func NewXidMetadata() *xidMetadata {
return &xidMetadata{
variableObjMap: make(map[string]map[string]interface{}),
seenAtTopLevel: make(map[string]bool),
seenUIDs: make(map[string]bool),
}
}
// isDuplicateXid returns true if:
// 1. we are at top level and this xid has already been seen at top level, OR
// 2. we are in a deep mutation and:
// a. this newXidObj has a field which is inverse of srcField and that
// invField is not of List type, OR
// b. newXidObj has some values other than xid and isn't equal to existingXidObject
// It is used in places where we don't want to allow duplicates.
func (xidMetadata *xidMetadata) isDuplicateXid(atTopLevel bool, xidVar string,
newXidObj map[string]interface{}, srcField schema.FieldDefinition) bool {
if atTopLevel && xidMetadata.seenAtTopLevel[xidVar] {
return true
}
if srcField != nil {
invField := srcField.Inverse()
if invField != nil && invField.Type().ListType() == nil {
return true
}
}
// We return an error if both occurrences of xid contain more than one values
// and are not equal.
// XID should be defined with all its values at one of the places and references with its
// XID from other places.
if len(newXidObj) > 1 && len(xidMetadata.variableObjMap[xidVar]) > 1 &&
!reflect.DeepEqual(xidMetadata.variableObjMap[xidVar], newXidObj) {
return true
}
return false
}
// RewriteQueries takes a GraphQL schema.Mutation add and creates queries to find out if
// referenced nodes by XID and UID exist or not.
// m must have a single argument called 'input' that carries the mutation data.
//
// For example, a GraphQL add mutation to add an object of type Author,
// with GraphQL input object (where country code is @id)
//
// {
// name: "A.N. Author",
// country: { code: "ind", name: "India" },
// posts: [ { title: "A Post", text: "Some text" }]
// friends: [ { id: "0x123" } ]
// }
//
// The following queries would be generated
// query {
// Country2(func: eq(Country.code, "ind")) @filter(type: Country) {
// uid
// }
// Person3(func: uid(0x123)) @filter(type: Person) {
// uid
// }
// }
//
// This query will be executed and depending on the result it would be decided whether
// to create a new country as part of this mutation or link it to an existing country.
// If it is found out that there is an existing country, no modifications are made to
// the country's attributes and its children. Mutations of the country's children are
// simply ignored.
// If it is found out that the Person with id 0x123 does not exist, the corresponding
// mutation will fail.
func (arw *AddRewriter) RewriteQueries(
ctx context.Context,
m schema.Mutation) ([]*gql.GraphQuery, error) {
arw.VarGen = NewVariableGenerator()
arw.XidMetadata = NewXidMetadata()
mutatedType := m.MutatedType()
val, _ := m.ArgValue(schema.InputArgName).([]interface{})
var ret []*gql.GraphQuery
var retErrors error
for _, i := range val {
obj := i.(map[string]interface{})
queries, errs := existenceQueries(ctx, mutatedType, nil, arw.VarGen, obj, arw.XidMetadata)
if len(errs) > 0 {
var gqlErrors x.GqlErrorList
for _, err := range errs {
gqlErrors = append(gqlErrors, schema.AsGQLErrors(err)...)
}
retErrors = schema.AppendGQLErrs(retErrors, schema.GQLWrapf(gqlErrors,
"failed to rewrite mutation payload"))
}
ret = append(ret, queries...)
}
return ret, retErrors
}
// RewriteQueries creates and rewrites set and remove update patches queries.
// The GraphQL updates look like:
//
// input UpdateAuthorInput {
// filter: AuthorFilter!
// set: PatchAuthor
// remove: PatchAuthor
// }
//
// which gets rewritten in to a DQL queries to check if
// - referenced UIDs and XIDs in set and remove exist or not.
//
// Depending on the result of these executed queries, it is then decided whether to
// create new nodes or link to existing ones.
//
// Note that queries rewritten using RewriteQueries don't include UIDs or XIDs referenced
// as part of filter argument.
//
// See AddRewriter for how the rewritten queries look like.
func (urw *UpdateRewriter) RewriteQueries(
ctx context.Context,
m schema.Mutation) ([]*gql.GraphQuery, error) {
mutatedType := m.MutatedType()
urw.VarGen = NewVariableGenerator()
urw.XidMetadata = NewXidMetadata()
inp := m.ArgValue(schema.InputArgName).(map[string]interface{})
setArg := inp["set"]
delArg := inp["remove"]
var ret []*gql.GraphQuery
var retErrors error
// Write existence queries for set
if setArg != nil {
obj := setArg.(map[string]interface{})
queries, errs := existenceQueries(ctx, mutatedType, nil, urw.VarGen, obj, urw.XidMetadata)
if len(errs) > 0 {
var gqlErrors x.GqlErrorList
for _, err := range errs {
gqlErrors = append(gqlErrors, schema.AsGQLErrors(err)...)
}
retErrors = schema.AppendGQLErrs(retErrors, schema.GQLWrapf(gqlErrors,
"failed to rewrite mutation payload"))
}
ret = append(ret, queries...)
}
// Write existence queries for remove
if delArg != nil {
obj := delArg.(map[string]interface{})
queries, errs := existenceQueries(ctx, mutatedType, nil, urw.VarGen, obj, urw.XidMetadata)
if len(errs) > 0 {
var gqlErrors x.GqlErrorList
for _, err := range errs {
gqlErrors = append(gqlErrors, schema.AsGQLErrors(err)...)
}
retErrors = schema.AppendGQLErrs(retErrors, schema.GQLWrapf(gqlErrors,
"failed to rewrite mutation payload"))
}
ret = append(ret, queries...)
}
return ret, retErrors
}
// Rewrite takes a GraphQL schema.Mutation add and builds a Dgraph upsert mutation.
// m must have a single argument called 'input' that carries the mutation data.
// The arguments also consist of idExistence map which is a map from
// Variable Name --> UID . This map is used to know which referenced nodes exists and
// whether to link the newly created node to existing node or create a new one.
//
// That argument could have been passed in the mutation like:
//
// addPost(input: { title: "...", ... })
//
// or be passed in a GraphQL variable like:
//
// addPost(input: $newPost)
//
// Either way, the data needs to have type information added and have some rewriting
// done - for example, rewriting field names from the GraphQL view to what's stored
// in Dgraph, and rewriting ID fields from their names to uid.
//
// For example, a GraphQL add mutation to add an object of type Author,
// with GraphQL input object (where country code is @id) :
//
// {
// name: "A.N. Author",
// country: { code: "ind", name: "India" },
// posts: [ { title: "A Post", text: "Some text" }]
// friends: [ { id: "0x123" } ]
// }
// and idExistence
// {
// "Country2": "0x234",
// "Person3": "0x123"
// }
//
// becomes an unconditional mutation.
//
// {
// "uid":"_:Author1",
// "dgraph.type":["Author"],
// "Author.name":"A.N. Author",
// "Author.country": {
// "uid":"0x234"
// },
// "Author.posts": [ {
// "uid":"_:Post3"
// "dgraph.type":["Post"],
// "Post.text":"Some text",
// "Post.title":"A Post",
// } ],
// "Author.friends":[ {"uid":"0x123"} ],
// }
func (arw *AddRewriter) Rewrite(
ctx context.Context,
m schema.Mutation,
idExistence map[string]string) ([]*UpsertMutation, error) {
mutationType := Add
mutatedType := m.MutatedType()
val, _ := m.ArgValue(schema.InputArgName).([]interface{})
varGen := arw.VarGen
xidMetadata := arw.XidMetadata
// ret stores a slice of Upsert Mutations. These are used in executing upsert queries in graphql/resolve/mutation.go
var ret []*UpsertMutation
// fragments stores a slice of mutationFragments. This is used in constructing mutationsAll which is returned back to the caller
// of this function as UpsertMutation.mutation
var fragments []*mutationFragment
// upsertQuery stores a list of queries of the form
// State1 as addState(func: uid(0x11)) @filter(type(State)) {
// uid
// }
// These are formed while doing Upserts with Add Mutations. These also contain
// any related auth queries. These are prepended to other queries formed during rewriteObject.
var upsertQuery []*gql.GraphQuery
var retErrors error
// Parse upsert parameter from addMutation input.
// If upsert is set to True, this add mutation will be carried as an Upsert Mutation.
upsert := false
upsertVal := m.ArgValue(schema.UpsertArgName)
if upsertVal != nil {
upsert = upsertVal.(bool)
}
if upsert {
mutationType = AddWithUpsert
}
for _, i := range val {
obj := i.(map[string]interface{})
fragment, upsertVar, errs := rewriteObject(ctx, mutatedType, nil, "", varGen, obj, xidMetadata, idExistence, mutationType)
if len(errs) > 0 {
var gqlErrors x.GqlErrorList
for _, err := range errs {
gqlErrors = append(gqlErrors, schema.AsGQLErrors(err)...)
}
retErrors = schema.AppendGQLErrs(retErrors, schema.GQLWrapf(gqlErrors,
"failed to rewrite mutation payload"))
}
// TODO: Do RBAC authorization along with RewriteQueries. This will save some time and queries need
// not be executed in case RBAC is Negative.
// upsertVar is non-empty in case this is an upsert Mutation and the XID at
// top level exists. upsertVar in this case contains variable name of the node
// which is going to be updated. Eg. State3 .
if upsertVar != "" {
// Add auth queries for upsert mutation.
customClaims, err := m.GetAuthMeta().ExtractCustomClaims(ctx)
if err != nil {
return ret, err
}
authRw := &authRewriter{
authVariables: customClaims.AuthVariables,
varGen: varGen,
selector: updateAuthSelector,
parentVarName: m.MutatedType().Name() + "Root",
}
authRw.hasAuthRules = hasAuthRules(m.QueryField(), authRw)
// Get upsert query of the form,
// State1 as addState(func: uid(0x11)) @filter(type(State)) {
// uid
// }
upsertQuery = append(upsertQuery, RewriteUpsertQueryFromMutation(m, authRw, upsertVar, idExistence[upsertVar])...)
// Add upsert condition to ensure that the upsert takes place only when the node
// exists and has proper auth permission.
// Example condition: cond: "@if(gt(len(State1), 0))"
fragment.conditions = append(fragment.conditions, fmt.Sprintf("gt(len(%s), 0)", upsertVar))
}
if fragment != nil {
fragments = append(fragments, fragment)
arw.frags = append(arw.frags, []*mutationFragment{fragment})
}
}
mutationsAll := []*dgoapi.Mutation{}
queries := &gql.GraphQuery{}
queries.Children = upsertQuery
buildMutations := func(mutationsAll []*dgoapi.Mutation, queries *gql.GraphQuery,
frag []*mutationFragment) []*dgoapi.Mutation {
mutations, _ := mutationsFromFragments(
frag,
func(frag *mutationFragment) ([]byte, error) {
return json.Marshal(frag.fragment)
},
func(frag *mutationFragment) ([]byte, error) {
if len(frag.deletes) > 0 {
return json.Marshal(frag.deletes)
}
return nil, nil
})
mutationsAll = append(mutationsAll, mutations...)
qry := queryFromFragments(frag)
if qry != nil {
queries.Children = append(queries.Children, qry.Children...)
}
return mutationsAll
}
mutationsAll = buildMutations(mutationsAll, queries, fragments)
if len(queries.Children) == 0 {
queries = nil
}
// newNodes is map from variable name to node type. This is used for applying auth on newly added nodes.
// This is collated from newNodes of each fragment.
// Example
// newNodes["Project3"] = schema.Type(Project)
newNodes := make(map[string]schema.Type)
for _, frag := range fragments {
copyTypeMap(frag.newNodes, newNodes)
}
if len(mutationsAll) > 0 {
ret = append(ret, &UpsertMutation{
Query: []*gql.GraphQuery{queries},
Mutations: mutationsAll,
NewNodes: newNodes,
})
}
return ret, retErrors
}
// Rewrite rewrites set and remove update patches into dql upsert mutations.
// The GraphQL updates look like:
//
// input UpdateAuthorInput {
// filter: AuthorFilter!
// set: PatchAuthor
// remove: PatchAuthor
// }
//
// which gets rewritten in to a Dgraph upsert mutation
// - filter becomes the query
// - set becomes the Dgraph set mutation
// - remove becomes the Dgraph delete mutation
//
// The semantics is the same as the Dgraph mutation semantics.
// - Any values in set become the new values for those predicates (or add to the existing
// values for lists)
// - Any nulls in set are ignored.
// - Explicit values in remove mean delete this if it is the actual value
// - Nulls in remove become like delete * for the corresponding predicate.
//
// See AddRewriter for how the set and remove fragments get created.
func (urw *UpdateRewriter) Rewrite(
ctx context.Context,
m schema.Mutation,
idExistence map[string]string) ([]*UpsertMutation, error) {
mutatedType := m.MutatedType()
varGen := urw.VarGen
xidMetadata := urw.XidMetadata
inp := m.ArgValue(schema.InputArgName).(map[string]interface{})
setArg := inp["set"]
delArg := inp["remove"]
// ret stores a slice of Upsert Mutations. These are used in executing upsert queries in graphql/resolve/mutation.go
var ret []*UpsertMutation
// fragments stores a slice of mutationFragments. This is used in constructing mutationsAll which is returned back to the caller
// of this function as UpsertMutation.mutation
var setFrag, delFrag []*mutationFragment
var retErrors error
customClaims, err := m.GetAuthMeta().ExtractCustomClaims(ctx)
if err != nil {
return ret, err
}
authRw := &authRewriter{
authVariables: customClaims.AuthVariables,
varGen: varGen,
selector: updateAuthSelector,
parentVarName: m.MutatedType().Name() + "Root",
}
authRw.hasAuthRules = hasAuthRules(m.QueryField(), authRw)
upsertQuery := RewriteUpsertQueryFromMutation(m, authRw, MutationQueryVar, "")
srcUID := MutationQueryVarUID
if setArg == nil && delArg == nil {
return ret, nil
}
if setArg != nil {
obj := setArg.(map[string]interface{})
fragment, _, errs := rewriteObject(ctx, mutatedType, nil, srcUID, varGen, obj, xidMetadata, idExistence, UpdateWithSet)
if len(errs) > 0 {
var gqlErrors x.GqlErrorList
for _, err := range errs {
gqlErrors = append(gqlErrors, schema.AsGQLErrors(err)...)
}
retErrors = schema.AppendGQLErrs(retErrors, schema.GQLWrapf(gqlErrors,
"failed to rewrite mutation payload"))
}
if fragment != nil {
setFrag = append(setFrag, fragment)
urw.setFrags = append(urw.setFrags, fragment)
}
}
if delArg != nil {
obj := delArg.(map[string]interface{})
// Set additional deletes to false
fragment, _, errs := rewriteObject(ctx, mutatedType, nil, srcUID, varGen, obj, xidMetadata, idExistence, UpdateWithRemove)
if len(errs) > 0 {
var gqlErrors x.GqlErrorList
for _, err := range errs {
gqlErrors = append(gqlErrors, schema.AsGQLErrors(err)...)
}
retErrors = schema.AppendGQLErrs(retErrors, schema.GQLWrapf(gqlErrors,
"failed to rewrite mutation payload"))
}
if fragment != nil {
delFrag = append(delFrag, fragment)
urw.delFrags = append(urw.delFrags, fragment)
}
}
buildMutation := func(setFrag, delFrag []*mutationFragment) *UpsertMutation {
var mutSet, mutDel []*dgoapi.Mutation
queries := upsertQuery
if setArg != nil {
addUpdateCondition(setFrag)
var errSet error
mutSet, errSet = mutationsFromFragments(
setFrag,
func(frag *mutationFragment) ([]byte, error) {
return json.Marshal(frag.fragment)
},
func(frag *mutationFragment) ([]byte, error) {
if len(frag.deletes) > 0 {
return json.Marshal(frag.deletes)
}
return nil, nil
})
retErrors = schema.AppendGQLErrs(retErrors, errSet)
q1 := queryFromFragments(setFrag)
if q1 != nil {
queries = append(queries, q1.Children...)
}
}
if delArg != nil {
addUpdateCondition(delFrag)
var errDel error
mutDel, errDel = mutationsFromFragments(
delFrag,
func(frag *mutationFragment) ([]byte, error) {
return nil, nil
},
func(frag *mutationFragment) ([]byte, error) {
return json.Marshal(frag.fragment)
})
retErrors = schema.AppendGQLErrs(retErrors, errDel)
q2 := queryFromFragments(delFrag)
if q2 != nil {
queries = append(queries, q2.Children...)
}
}
newNodes := make(map[string]schema.Type)
if urw.setFrags != nil {
copyTypeMap(urw.setFrags[0].newNodes, newNodes)
}
if urw.delFrags != nil {
copyTypeMap(urw.delFrags[0].newNodes, newNodes)
}
return &UpsertMutation{
Query: queries,
Mutations: append(mutSet, mutDel...),
NewNodes: newNodes,
}
}
mutations := buildMutation(setFrag, delFrag)
ret = append(ret, mutations)
return ret, retErrors
}
// FromMutationResult rewrites the query part of a GraphQL add mutation into a Dgraph query.
func (arw *AddRewriter) FromMutationResult(
ctx context.Context,
mutation schema.Mutation,
assigned map[string]string,
result map[string]interface{}) ([]*gql.GraphQuery, error) {
var errs error
for _, frag := range arw.frags {
err := checkResult(frag, result)
errs = schema.AppendGQLErrs(errs, err)
}
// Find any newly added/updated rootUIDs.
uids, err := convertIDsWithErr(arw.MutatedRootUIDs(mutation, assigned, result))
errs = schema.AppendGQLErrs(errs, err)
// Find out if its an upsert with Add mutation.
upsert := false
upsertVal := mutation.ArgValue(schema.UpsertArgName)
if upsertVal != nil {
upsert = upsertVal.(bool)
}
// This error is only relevant in case this is not an Upsert with Add Mutation.
// During upsert with Add mutation, it may happen that no new nodes are created and
// everything is perfectly alright.
if len(uids) == 0 && errs == nil && !upsert {
errs = schema.AsGQLErrors(errors.Errorf("no new node was created"))
}
customClaims, err := mutation.GetAuthMeta().ExtractCustomClaims(ctx)
if err != nil {
return nil, err
}
authRw := &authRewriter{
authVariables: customClaims.AuthVariables,
varGen: NewVariableGenerator(),
selector: queryAuthSelector,
parentVarName: mutation.MutatedType().Name() + "Root",
}
authRw.hasAuthRules = hasAuthRules(mutation.QueryField(), authRw)
return rewriteAsQueryByIds(mutation.QueryField(), uids, authRw), errs
}
// FromMutationResult rewrites the query part of a GraphQL update mutation into a Dgraph query.
func (urw *UpdateRewriter) FromMutationResult(
ctx context.Context,
mutation schema.Mutation,
assigned map[string]string,
result map[string]interface{}) ([]*gql.GraphQuery, error) {
err := checkResult(urw.setFrags, result)
if err != nil {
return nil, err
}
err = checkResult(urw.delFrags, result)
if err != nil {
return nil, err
}
uids, err := convertIDsWithErr(urw.MutatedRootUIDs(mutation, assigned, result))
if err != nil {
return nil, err
}
customClaims, err := mutation.GetAuthMeta().ExtractCustomClaims(ctx)
if err != nil {
return nil, err
}
authRw := &authRewriter{
authVariables: customClaims.AuthVariables,
varGen: NewVariableGenerator(),
selector: queryAuthSelector,
parentVarName: mutation.MutatedType().Name() + "Root",
}
authRw.hasAuthRules = hasAuthRules(mutation.QueryField(), authRw)
return rewriteAsQueryByIds(mutation.QueryField(), uids, authRw), nil
}
func (arw *AddRewriter) MutatedRootUIDs(
mutation schema.Mutation,
assigned map[string]string,
result map[string]interface{}) []string {
var rootUIDs []string // This stores a list of added or updated rootUIDs.
// Add any newly added rootUIDs.
for _, frag := range arw.frags {
blankNodeName := strings.TrimPrefix(frag[0].
fragment.(map[string]interface{})["uid"].(string), "_:")
uid, ok := assigned[blankNodeName]
if ok {
rootUIDs = append(rootUIDs, uid)
}
}
// Extract and add any updated rootUIDs. This is done for upsert With Add Mutation.
// In this case, it may happen that no new node is created, but there may still
// be some updated nodes. We get these nodes over here and add to uid list.
rootUIDs = append(rootUIDs, extractMutated(result, mutation.Name())...)
return rootUIDs
}
func (urw *UpdateRewriter) MutatedRootUIDs(
mutation schema.Mutation,
assigned map[string]string,
result map[string]interface{}) []string {
return extractMutated(result, mutation.Name())
}
func convertIDsWithErr(uidSlice []string) ([]uint64, error) {
var errs error
uids := make([]uint64, 0, len(uidSlice))
if len(uidSlice) > 0 {
for _, id := range uidSlice {
uid, err := strconv.ParseUint(id, 0, 64)
if err != nil {
errs = schema.AppendGQLErrs(errs, schema.GQLWrapf(err,
"received %s as a uid from Dgraph, but couldn't parse it as uint64", id))
continue
}
uids = append(uids, uid)
}
}
return uids, errs
}
func extractMutated(result map[string]interface{}, mutatedField string) []string {
var mutated []string
if val, ok := result[mutatedField].([]interface{}); ok {
for _, v := range val {
if obj, vok := v.(map[string]interface{}); vok {
if uid, uok := obj["uid"].(string); uok {
mutated = append(mutated, uid)
}
}
}
}
return mutated
}
func addUpdateCondition(frags []*mutationFragment) {
for _, frag := range frags {
frag.conditions = append(frag.conditions, updateMutationCondition)
}
}
// checkResult checks if any mutationFragment in frags was successful in result.
// If any one of the frags (which correspond to conditional mutations) succeeded,
// then the mutation ran through ok. Otherwise return an error showing why
// at least one of the mutations failed.
func checkResult(frags []*mutationFragment, result map[string]interface{}) error {
if len(frags) == 0 {
return nil
}
if result == nil {
return nil
}
var err error
for _, frag := range frags {
err = frag.check(result)
if err == nil {
return nil
}
}
return err
}
func extractMutationFilter(m schema.Mutation) map[string]interface{} {
var filter map[string]interface{}
mutationType := m.MutationType()
if mutationType == schema.UpdateMutation {
input, ok := m.ArgValue("input").(map[string]interface{})
if ok {
filter, _ = input["filter"].(map[string]interface{})
}
} else if mutationType == schema.DeleteMutation {
filter, _ = m.ArgValue("filter").(map[string]interface{})
}
return filter
}
func RewriteUpsertQueryFromMutation(
m schema.Mutation,
authRw *authRewriter,
mutationQueryVar string,
nodeID string) []*gql.GraphQuery {
// The query needs to assign the results to a variable, so that the mutation can use them.
dgQuery := []*gql.GraphQuery{{
Var: mutationQueryVar,
Attr: m.Name(),
}}
rbac := authRw.evaluateStaticRules(m.MutatedType())
if rbac == schema.Negative {
dgQuery[0].Attr = m.ResponseName() + "()"
return dgQuery
}
// For interface, empty delete mutation should be returned if Auth rules are
// not satisfied even for a single implementing type
if m.MutatedType().IsInterface() {
implementingTypesHasFailedRules := false
implementingTypes := m.MutatedType().ImplementingTypes()
for _, typ := range implementingTypes {
if authRw.evaluateStaticRules(typ) != schema.Negative {
implementingTypesHasFailedRules = true
}
}
if !implementingTypesHasFailedRules {
dgQuery[0].Attr = m.ResponseName() + "()"
return dgQuery
}
}
// Add uid child to the upsert query, so that we can get the list of nodes upserted.
dgQuery[0].Children = append(dgQuery[0].Children, &gql.GraphQuery{
Attr: "uid",
})
// TODO - Cache this instead of this being a loop to find the IDField.
// nodeID is contains upsertVar in case this is an upsert with Add Mutation.
// In all other cases nodeID is set to empty.
// If it is set to empty, this is either a delete or update mutation.
// In that case, we extract the IDs on which to apply this mutation using
// extractMutationFilter.
if nodeID == "" {
filter := extractMutationFilter(m)
if ids := idFilter(filter, m.MutatedType().IDField()); ids != nil {
addUIDFunc(dgQuery[0], ids)
} else {
addTypeFunc(dgQuery[0], m.MutatedType().DgraphName())
}
_ = addFilter(dgQuery[0], m.MutatedType(), filter)
} else {
// It means this is called from upsert with Add mutation.
// nodeID will be uid of the node to be upserted. We add UID func
// and type filter to generate query like
// State3 as addState(func: uid(0x13)) @filter(type(State)) {
// uid
// }
uid, err := strconv.ParseUint(nodeID, 0, 64)
if err != nil {
dgQuery[0].Attr = m.ResponseName() + "()"
return dgQuery
}
addUIDFunc(dgQuery[0], []uint64{uid})
addTypeFilter(dgQuery[0], m.MutatedType())
}
dgQuery = authRw.addAuthQueries(m.MutatedType(), dgQuery, rbac)
return dgQuery
}
// removeNodeReference removes any reference we know about (via @hasInverse) into a node.
func removeNodeReference(m schema.Mutation, authRw *authRewriter,
qry *gql.GraphQuery) []interface{} {
var deletes []interface{}
for _, fld := range m.MutatedType().Fields() {
invField := fld.Inverse()
if invField == nil {
// This field be a reverse edge, in that case we need to delete the incoming connections
// to this node via its forward edges.
invField = fld.ForwardEdge()
if invField == nil {
continue
}
}
varName := authRw.varGen.Next(fld.Type(), "", "", false)
qry.Children = append(qry.Children,
&gql.GraphQuery{
Var: varName,
Attr: invField.Type().DgraphPredicate(fld.Name()),
})
delFldName := fld.Type().DgraphPredicate(invField.Name())
del := map[string]interface{}{"uid": MutationQueryVarUID}
if invField.Type().ListType() == nil {
deletes = append(deletes, map[string]interface{}{
"uid": fmt.Sprintf("uid(%s)", varName),
delFldName: del})
} else {
deletes = append(deletes, map[string]interface{}{
"uid": fmt.Sprintf("uid(%s)", varName),
delFldName: []interface{}{del}})
}