-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
464 lines (429 loc) · 11.1 KB
/
query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
package humus
import (
"errors"
"strconv"
"strings"
)
//UID represents the primary UID class used in communication with DGraph.
//This is used in code generation and for type safety.
type UID string
//Int returns an int64 representation of the UID that is of the form
//0xvalue. Returns -1 on error.
func (u UID) Int() int64 {
if len(u) < 2 {
return -1
}
val, err := strconv.ParseInt(string(u[2:]), 16, 64)
if err != nil {
return -1
}
return val
}
//IntString returns a string representation of the integer form of the
//uid u.
func (u UID) IntString() string {
val, err := strconv.ParseInt(string(u), 16, 64)
if err != nil {
return ""
}
return strconv.FormatInt(val, 10)
}
func stringFromInt(id int64) string {
return "0x" + strconv.FormatInt(id, 16)
}
//ParseUid parses a uid from an int64.
func ParseUid(id int64) UID {
return UID(stringFromInt(id))
}
const (
// syntax tokens
tokenLB = "{" // Left Brace
tokenRB = "}" // Right Brace
tokenLP = "(" // Left parenthesis
tokenRP = ")" // Right parenthesis
tokenColumn = ":"
tokenComma = ","
tokenSpace = " "
tokenFilter = "@filter"
)
//Queries represents multiple queries at once.
type Queries struct {
q []*GeneratedQuery
varCounter func() int
currentVar int
vars map[string]string
}
//Satisfy the Query interface.
func (q *Queries) Process() (string, error) {
return q.create()
}
func (q *Queries) names() []string {
c := len(q.q)
for _, v := range q.q {
if v.variable.varQuery {
c--
}
}
ret := make([]string, c)
count := 0
for _, v := range q.q {
if v.variable.varQuery {
continue
}
ret[count] = "q" + strconv.Itoa(v.index)
count++
}
return ret
}
func (q *Queries) NewQuery(f Fields) *GeneratedQuery {
newq := &GeneratedQuery{
modifiers: make(map[Predicate]*mapElement),
fields: f,
varMap: q.vars,
}
newq.varFunc = q.varCounter
q.q = append(q.q, newq)
return newq
}
//create the byte representation.
func (q *Queries) create() (string, error) {
var final strings.Builder
final.Grow(512)
//The query variable information. Named per default.
//TODO: Right now it breaks if no queries have vars.
final.WriteString("query t")
//The global variable counter. It exists in a closure, it's just easy.
final.WriteString("(")
for k, qu := range q.q {
qu.mapVariables(qu)
str := qu.variables()
if str == "" {
continue
}
//TODO: Make it more like a strings.Join to avoid all these error-prone additions.
if len(q.q) > 1 && k > 0 {
final.WriteByte(',')
}
final.WriteString(str)
}
final.WriteByte(')')
count := 0
for _, qu := range q.q {
final.WriteByte('{')
if !qu.variable.varQuery {
qu.index = count
count++
}
_, err := qu.create(&final)
if err != nil {
return "", err
}
final.WriteByte('}')
}
return final.String(), nil
}
func (q *Queries) queryVars() map[string]string {
return q.vars
}
//GeneratedQuery is the root object of queries that are constructed.
//It is constructed using a set of Fields that are either autogenerated or
//manually specified. From its list of modifiers(orderby, pagination etc)
//it automatically and efficiently builds up a query ready for sending to Dgraph.
type GeneratedQuery struct {
//The root function.
//Since all queries have a graph function this is an embedded struct.
//(It is embedded for convenient access as well as unnecessary pointer traversal).
function
//Builder for GraphQL variables.
varBuilder strings.Builder
//Which directives to apply on this query, such as @cascade.
directives []Directive
//The list of fields used in this query.
fields Fields
//The overall language for this query.
language Language
//List of modifiers, i.e. order, pagination etc.
modifiers map[Predicate]*mapElement
//Map for dealing with GraphQL variables. It is inherited in multi-query layout.
varMap map[string]string
//function for getting next query value in multi-query. It is also used
//to define whether it is a single query.
varFunc func() int
//varCounter is used for single queries, to keep track of the next GraphQL variable to be assigned.
varCounter int
//For multiple queries. Used to keep track of the query name.
index int
//top level variable name
variable struct {
varName string
varQuery bool
}
//Whether to allow untagged language.
strictLanguage bool
}
//NewQuery returns a new singular generation query for use
//in building a single query.
func NewQuery(f Fields) *GeneratedQuery {
return &GeneratedQuery{
varMap: make(map[string]string),
modifiers: make(map[Predicate]*mapElement),
fields: f,
}
}
//NewQueries returns a QueryList used for building
//multiple queries at once.
func NewQueries() *Queries {
qu := new(Queries)
qu.q = make([]*GeneratedQuery, 0, 2)
qu.currentVar = -1
qu.varCounter = func() int {
qu.currentVar++
return qu.currentVar
}
qu.vars = make(map[string]string)
return qu
}
func (q *GeneratedQuery) Process() (string, error) {
return q.create(nil)
}
//MutationType defines whether a mutation sets or deletes values.
type MutationType string
const (
MutateDelete MutationType = "delete"
MutateSet MutationType = "set"
)
//Default name for query.
var defaultName = []string{"q0"}
func (q *GeneratedQuery) single() bool {
return q.varFunc == nil
}
func (q *GeneratedQuery) names() []string {
if q.variable.varQuery {
return nil
}
if q.single() {
return defaultName
}
return []string{"q" + strconv.Itoa(q.index)}
}
func (q *GeneratedQuery) create(sb *strings.Builder) (string, error) {
//t := time.Now()
//sb == nil implies this is a solo query. This means we need to map the GraphQL
//variables beforehand as it is otherwise calculated in the Queries calculation in Queries.create()
if sb == nil {
sb = new(strings.Builder)
q.mapVariables(q)
sb.Grow(256)
}
if err := q.function.check(q); err != nil {
return "", err
}
//Top level modifiers.
val, ok := q.modifiers[""]
//Single query.
if q.single() && q.variable.varQuery {
return "", errors.New("singular query with var set is invalid")
}
if q.single() {
vars := q.variables()
if vars == "" {
sb.WriteString("query{")
} else {
sb.WriteString("query t(")
sb.WriteString(vars)
sb.WriteString("){")
}
}
//Write query header.
if q.variable.varQuery {
if q.variable.varName != "" {
sb.WriteString(q.variable.varName)
sb.WriteString(" as ")
}
sb.WriteString("var")
} else {
sb.WriteByte('q')
if q.index != 0 {
sb.WriteString(strconv.Itoa(q.index))
} else {
sb.WriteByte('0')
}
}
sb.WriteString(tokenLP + "func" + tokenColumn + tokenSpace)
err := q.function.create(q, sb)
if err != nil {
return "", err
}
if ok {
//Two passes. Before and after parenthesis. That's just how it be.
val.m.sort()
err := val.m.runTopLevel(q, 0, modifierFunction, sb)
if err != nil {
return "", err
}
} else {
sb.WriteByte(')')
}
for _, v := range q.directives {
sb.WriteByte('@')
sb.WriteString(string(v))
}
sb.WriteByte('{')
var parentBuf = make([]byte, 0, 64)
for _, field := range q.fields.Get() {
if len(field.Name) > 64 {
//This code should pretty much never execute as a predicate is rarely this large.
parentBuf = make([]byte, 2*len(field.Name))
}
parentBuf = parentBuf[:len(field.Name)]
copy(parentBuf, field.Name)
//parentBuf = append(parentBuf, field.Name...)
err := field.create(q, parentBuf, sb)
if err != nil {
return "", err
}
}
if ok {
err = val.m.runVariables(q, 0, modifierFunction, sb)
if err != nil {
return "", err
}
}
//Add default uid to top level field and close query.
sb.WriteString(" uid" + tokenRB)
if q.single() {
sb.WriteByte('}')
}
return sb.String(), nil
}
func (q *GeneratedQuery) queryVars() map[string]string {
return q.varMap
}
//Directive adds a top level directive.
func (q *GeneratedQuery) Directive(dir Directive) *GeneratedQuery {
for _, v := range q.directives {
if v == dir {
return q
}
}
q.directives = append(q.directives, dir)
return q
}
/*
At allows you to run modifiers at a path. Modifiers include
pagination, sorting, filters among others.
*/
func (q *GeneratedQuery) At(path Predicate, op Operation) *GeneratedQuery {
val, ok := q.modifiers[path]
if !ok {
val = new(mapElement)
val.q = q
q.modifiers[path] = val
}
var m = (*modifierCreator)(val)
if op != nil {
op(m)
}
return q
}
/*
Facets sets @facets for the edge specified by path along with all values as specified by op.
This can be used to fetch facets, store facets in query variables or something in that manner.
For instance, generating a line in the fashion of @facets(value as friendsSince)
will store the facet value 'friendsSince' into the value variable 'value'.
*/
func (q *GeneratedQuery) Facets(path Predicate, op Operation) *GeneratedQuery {
val, ok := q.modifiers[path]
if !ok {
val = new(mapElement)
val.q = q
q.modifiers[path] = val
}
var f = (*facetCreator)(val)
if op != nil {
op(f)
}
f.f.active = true
return q
}
/*
GroupBy allows you to groupBy at a leaf field. Using op specify a list of variables and operations
to be written as aggregation at this level. onWhich specifies what predicate to actually group on.
*/
func (q *GeneratedQuery) GroupBy(path Predicate, onWhich Predicate, op Operation) *GeneratedQuery {
val, ok := q.modifiers[path]
if !ok {
val = new(mapElement)
val.q = q
q.modifiers[path] = val
}
var g = (*groupCreator)(val)
if op != nil {
op(g)
}
g.g.p = onWhich
return q
}
//Language sets the language for the query to apply to all fields.
//If strict do not allow untagged language.
func (q *GeneratedQuery) Language(l Language, strict bool) *GeneratedQuery {
q.language = l
q.strictLanguage = strict
return q
}
//Returns all the query variables for this query in create form.
func (q *GeneratedQuery) variables() string {
return q.varBuilder.String()
}
//Var sets q as a var query with the variable name name.
//if name is empty it is just a basic var query.
func (q *GeneratedQuery) Var(name string) *GeneratedQuery {
q.variable.varQuery = true
q.variable.varName = name
return q
}
func (q *GeneratedQuery) registerVariable(typ varType, value string) string {
if q.varBuilder.Len() != 0 {
q.varBuilder.WriteByte(',')
} else {
q.varBuilder.Grow(32)
}
var val int
if q.varFunc != nil {
val = q.varFunc()
} else {
val = q.varCounter
q.varCounter++
}
key := "$" + strconv.Itoa(val)
q.varBuilder.WriteString(key)
q.varBuilder.WriteByte(':')
q.varBuilder.WriteString(string(typ))
q.varMap[key] = value
return key
}
//Static create a static query from the generated version.
//Since this is performed at init, panic if the query
//creation does not work.
func (q *GeneratedQuery) Static() StaticQuery {
str, err := q.create(nil)
if err != nil {
panic(err)
}
return StaticQuery{
Query: str,
vars: nil,
}
}
//Function sets the function type for this function. It is used alongside
//variables. variables are automatically mapped to GraphQL variables as a way
//of avoiding SQL injections.
func (q *GeneratedQuery) Function(ft FunctionType) *GeneratedQuery {
q.function = function{typ: ft}
return q
}
//Values simple performs the same as Value but for a variadic number of arguments.
func (q *GeneratedQuery) Values(v ...interface{}) *GeneratedQuery {
q.function.values(v)
return q
}