-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathclient.go
442 lines (399 loc) · 14 KB
/
client.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
/*
* Copyright 2016 Dgraph Labs, Inc.
*
* 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 client
import (
"encoding/base64"
"fmt"
"time"
"github.com/dgraph-io/dgraph/protos"
"github.com/dgraph-io/dgraph/types"
"github.com/dgraph-io/dgraph/x"
geom "github.com/twpayne/go-geom"
"github.com/twpayne/go-geom/encoding/geojson"
)
type opType int
const (
// SET indicates a Set mutation.
SET opType = iota
// DEL indicates a Delete mutation.
DEL
)
// A Req represents a single request to the backend Dgraph instance. Each request may contain
// multiple set, delete and schema mutations, and a single GraphQL+- query. If the query contains
// GraphQL variables, then it must be set with SetQueryWithVariables rather than SetQuery.
type Req struct {
gr protos.Request
mark *x.WaterMark
line uint64
}
// Request returns the protos.Request backing the Req.
func (req *Req) Request() *protos.Request {
return &req.gr
}
func checkSchema(schema protos.SchemaUpdate) error {
typ := types.TypeID(schema.ValueType)
if typ == types.UidID && schema.Directive == protos.SchemaUpdate_INDEX {
// index on uid type
return x.Errorf("Index not allowed on predicate of type uid on predicate %s",
schema.Predicate)
} else if typ != types.UidID && schema.Directive == protos.SchemaUpdate_REVERSE {
// reverse on non-uid type
return x.Errorf("Cannot reverse for non-uid type on predicate %s", schema.Predicate)
}
return nil
}
// SetQuery sets the query in req to the given string.
// The query string is not checked until the request is
// run, when it is parsed and checked server-side.
func (req *Req) SetQuery(q string) {
req.gr.Query = q
}
// SetQueryWithVariables sets query q (which contains graphQL variables mapped
// in vars) as the query in req and sets vars as the corresponding query variables.
// Neither the query string nor the variables are checked until the request is run,
// when it is parsed and checked server-side.
func (req *Req) SetQueryWithVariables(q string, vars map[string]string) {
req.gr.Query = q
req.gr.Vars = vars
}
func (req *Req) addMutation(e Edge, op opType) {
if req.gr.Mutation == nil {
req.gr.Mutation = new(protos.Mutation)
}
if op == SET {
req.gr.Mutation.Set = append(req.gr.Mutation.Set, &e.nq)
} else if op == DEL {
req.gr.Mutation.Del = append(req.gr.Mutation.Del, &e.nq)
}
}
// Set adds edge e to the set mutation of request req, thus scheduling the edge to be added to the
// graph when the request is run. The edge must have a valid target (a Node or value), otherwise
// an error is returned. The edge is not checked agaist the schema until the request is
// run --- so setting a UID edge to a value, for example, doesn't result in an error until
// the request is run.
func (req *Req) Set(e Edge) error {
if err := e.validate(); err != nil {
return err
}
req.addMutation(e, SET)
return nil
}
// Delete adds edge e to the delete mutation of request req, thus scheduling the edge to be removed
// from the graph when the request is run. The edge must have a valid target (a Node or value),
// otherwise an error is returned. The edge need not represent
// an edge in the graph --- applying such a mutation simply has no effect.
func (req *Req) Delete(e Edge) error {
if err := e.validate(); err != nil {
return err
}
req.addMutation(e, DEL)
return nil
}
// AddSchema adds the single schema mutation s to the request.
func (req *Req) AddSchema(s protos.SchemaUpdate) error {
if req.gr.Mutation == nil {
req.gr.Mutation = new(protos.Mutation)
}
req.gr.Mutation.Schema = append(req.gr.Mutation.Schema, &s)
return nil
}
func (req *Req) size() int {
if req.gr.Mutation == nil {
return 0
}
return len(req.gr.Mutation.Set) + len(req.gr.Mutation.Del) + len(req.gr.Mutation.Schema)
}
func (req *Req) reset() {
req.gr.Query = ""
req.gr.Mutation.Set = req.gr.Mutation.Set[:0]
req.gr.Mutation.Del = req.gr.Mutation.Del[:0]
req.gr.Mutation.Schema = req.gr.Mutation.Schema[:0]
}
type nquadOp struct {
e Edge
op opType
}
// Node represents a single node in the graph.
type Node struct {
uid uint64
// We can do variables in mutations.
varName string
}
// String returns Node n as a string
func (n Node) String() string {
if n.uid != 0 {
return fmt.Sprintf("%#x", uint64(n.uid))
}
return n.varName
}
// ConnectTo creates an edge labelled pred from Node n to Node n1
func (n *Node) ConnectTo(pred string, n1 Node) Edge {
e := Edge{}
if len(n.varName) != 0 {
e.nq.SubjectVar = n.String()
} else {
e.nq.Subject = n.String()
}
e.nq.Predicate = pred
e.ConnectTo(n1)
return e
}
// Edge create an edge with source Node n and predicate pred, but without a target.
// The edge needs to be completed by calling Edge.ConnectTo() if the edge is a
// UID edge, or one of the Edge.SetValue...() functions if the edge is of a scalar type.
// The edge can't be committed to the store --- calling Req.Set() to add the edge to
// a request will result in an error --- until it is completed.
func (n *Node) Edge(pred string) Edge {
e := Edge{}
if len(n.varName) != 0 {
e.nq.SubjectVar = n.String()
} else {
e.nq.Subject = n.String()
}
e.nq.Predicate = pred
return e
}
// Delete is used to delete all outgoing edges for a node. It is equivalent to performing a S * *
// deletion.
func (n *Node) Delete() Edge {
e := Edge{}
if len(n.varName) != 0 {
e.nq.SubjectVar = n.String()
} else {
e.nq.Subject = n.String()
}
e.nq.Predicate = x.Star
e.nq.ObjectValue, _ = types.ObjectValue(types.DefaultID, x.Star)
return e
}
// An Edge represents an edge between a source node and a target (either a node or a value).
// Facets are stored in the edge. See Node.Edge(), Node.ConnectTo(), Edge.ConnecTo(),
// Edge.AddFacet and the Edge.SetValue...() functions to
// make a valid edge for a set or delete mutation.
type Edge struct {
nq protos.NQuad
}
// NewEdge creates an Edge from an NQuad.
func NewEdge(nq protos.NQuad) Edge {
return Edge{nq}
}
// ConnectTo adds Node n as the target of the edge. If the edge already has a known scalar type,
// for example if Edge.SetValue...() had been called on the edge, then an error is returned.
func (e *Edge) ConnectTo(n Node) error {
if e.nq.ObjectType > 0 {
return ErrValue
}
if len(n.varName) != 0 {
e.nq.ObjectVar = n.String()
} else {
e.nq.ObjectId = n.String()
}
return nil
}
// Delete is used to set the edge for deletion. If the edge is already connected to another node
// then an error is returned. This is equivalent to S P * deletion where an edge can be deleted
// without knowing giving the Value/Node it is connected to.
func (e *Edge) Delete() error {
if len(e.nq.ObjectId) > 0 {
return ErrConnected
}
e.nq.ObjectValue, _ = types.ObjectValue(types.DefaultID, x.Star)
return nil
}
func (e *Edge) validate() error {
// Edge should be connected to a value in which case ObjectType would be > 0.
// Or it needs to connect to a Node (ObjectId > 0) or it should be connected to a variable.
if e.nq.ObjectValue != nil || len(e.nq.ObjectId) > 0 || len(e.nq.ObjectVar) > 0 {
return nil
}
return ErrNotConnected
}
func validateStr(val string) error {
for idx, c := range val {
if c == '"' && (idx == 0 || val[idx-1] != '\\') {
return fmt.Errorf(`" must be preceded by a \ in object value`)
}
}
return nil
}
// SetValueString sets the value of Edge e as string val and sets the type of the edge to
// types.StringID. If the edge had previous been assigned another value (even of another type),
// the value and type are overwritten. If the edge has previously been connected to a node, the
// edge and type are left unchanged and ErrConnected is returned. The string must
// escape " with \, otherwise the edge and type are left unchanged and an error returned.
func (e *Edge) SetValueString(val string) error {
if len(e.nq.ObjectId) > 0 {
return ErrConnected
}
if err := validateStr(val); err != nil {
return err
}
v, err := types.ObjectValue(types.StringID, val)
if err != nil {
return err
}
e.nq.ObjectValue = v
e.nq.ObjectType = int32(types.StringID)
return nil
}
// SetValueInt sets the value of Edge e as int64 val and sets the type of the edge to types.IntID.
// If the edge had previous been assigned another value (even of another type), the value and type
// are overwritten. If the edge has previously been connected to a node, the edge and type are
// left unchanged and ErrConnected is returned.
func (e *Edge) SetValueInt(val int64) error {
if len(e.nq.ObjectId) > 0 {
return ErrConnected
}
v, err := types.ObjectValue(types.IntID, val)
if err != nil {
return err
}
e.nq.ObjectValue = v
e.nq.ObjectType = int32(types.IntID)
return nil
}
// SetValueFloat sets the value of Edge e as float64 val and sets the type of the edge to
// types.FloatID. If the edge had previous been assigned another value (even of another type),
// the value and type are overwritten. If the edge has previously been connected to a node, the
// edge and type are left unchanged and ErrConnected is returned.
func (e *Edge) SetValueFloat(val float64) error {
if len(e.nq.ObjectId) > 0 {
return ErrConnected
}
v, err := types.ObjectValue(types.FloatID, val)
if err != nil {
return err
}
e.nq.ObjectValue = v
e.nq.ObjectType = int32(types.FloatID)
return nil
}
// SetValueBool sets the value of Edge e as bool val and sets the type of the edge to types.BoolID.
// If the edge had previous been assigned another value (even of another type), the value and type
// are overwritten. If the edge has previously been connected to a node, the edge and type are
// left unchanged and ErrConnected is returned.
func (e *Edge) SetValueBool(val bool) error {
if len(e.nq.ObjectId) > 0 {
return ErrConnected
}
v, err := types.ObjectValue(types.BoolID, val)
if err != nil {
return err
}
e.nq.ObjectValue = v
e.nq.ObjectType = int32(types.BoolID)
return nil
}
// SetValuePassword sets the value of Edge e as password string val and sets the type of the edge
// to types.PasswordID. If the edge had previous been assigned another value (even of another
// type), the value and type are overwritten. If the edge has previously been connected to a
// node, the edge and type are left unchanged and ErrConnected is returned.
func (e *Edge) SetValuePassword(val string) error {
if len(e.nq.ObjectId) > 0 {
return ErrConnected
}
v, err := types.ObjectValue(types.PasswordID, val)
if err != nil {
return err
}
e.nq.ObjectValue = v
e.nq.ObjectType = int32(types.PasswordID)
return nil
}
// SetValueDatetime sets the value of Edge e as time.Time dateTime and sets the type of the edge
// to types.DateTimeID. If the edge had previous been assigned another value (even of another
// type), the value and type are overwritten. If the edge has previously been connected to a node,
// the edge and type are left unchanged and ErrConnected is returned.
func (e *Edge) SetValueDatetime(dateTime time.Time) error {
if len(e.nq.ObjectId) > 0 {
return ErrConnected
}
d, err := types.ObjectValue(types.DateTimeID, dateTime)
if err != nil {
return err
}
e.nq.ObjectValue = d
e.nq.ObjectType = int32(types.DateTimeID)
return nil
}
// SetValueGeoJson sets the value of Edge e as the GeoJSON object parsed from json string and sets
// the type of the edge to types.GeoID. If the edge had previous been assigned another value (even
// of another type), the value and type are overwritten. If the edge has previously been connected
// to a node, the edge and type are left unchanged and ErrConnected is returned. If the string
// fails to parse with geojson.Unmarshal() the edge is left unchanged and an error returned.
func (e *Edge) SetValueGeoJson(json string) error {
if len(e.nq.ObjectId) > 0 {
return ErrConnected
}
var g geom.T
// Parse the json
err := geojson.Unmarshal([]byte(json), &g)
if err != nil {
return err
}
geo, err := types.ObjectValue(types.GeoID, g)
if err != nil {
return err
}
e.nq.ObjectValue = geo
e.nq.ObjectType = int32(types.GeoID)
return nil
}
// SetValueDefault sets the value of Edge e as string val and sets the type of the edge to
// types.DefaultID. If the edge had previous been assigned another value (even of another
// type), the value and type are overwritten. If the edge has previously been connected to
// a node, the edge and type are left unchanged and ErrConnected is returned.
// The string must escape " with \, otherwise the edge and type are left unchanged and an error returned.
func (e *Edge) SetValueDefault(val string) error {
if len(e.nq.ObjectId) > 0 {
return ErrConnected
}
if err := validateStr(val); err != nil {
return err
}
v, err := types.ObjectValue(types.DefaultID, val)
if err != nil {
return err
}
e.nq.ObjectValue = v
e.nq.ObjectType = int32(types.StringID)
return nil
}
// SetValueBytes allows setting the value of an edge to raw bytes and sets the type of the edge
// to types.BinaryID. If the edge had previous been assigned another value (even of another type),
// the value and type are overwritten. If the edge has previously been connected to a node, the
// edge and type are left unchanged and ErrConnected is returned. the bytes are encoded as base64.
func (e *Edge) SetValueBytes(val []byte) error {
if len(e.nq.ObjectId) > 0 {
return ErrConnected
}
dst := make([]byte, base64.StdEncoding.EncodedLen(len(val)))
base64.StdEncoding.Encode(dst, val)
v, err := types.ObjectValue(types.BinaryID, []byte(dst))
if err != nil {
return err
}
e.nq.ObjectValue = v
e.nq.ObjectType = int32(types.BinaryID)
return nil
}
// AddFacet adds the key, value pair as facets on Edge e. No checking is done.
func (e *Edge) AddFacet(key, val string) {
e.nq.Facets = append(e.nq.Facets, &protos.Facet{
Key: key,
Val: val,
})
}