-
-
Notifications
You must be signed in to change notification settings - Fork 171
/
qcode.go
1294 lines (1090 loc) · 25.4 KB
/
qcode.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
//go:generate stringer -linecomment -type=QType,MType,SelType,FieldType,SkipType,PagingType,AggregrateOp,ValType,ExpOp -output=./gen_string.go
package qcode
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/dosco/graphjin/core/v3/internal/graph"
"github.com/dosco/graphjin/core/v3/internal/sdata"
"github.com/dosco/graphjin/core/v3/internal/util"
)
const (
maxSelectors = 100
singularSuffixCamel = "ByID"
singularSuffixSnake = "_by_id"
)
type QType int8
const (
QTUnknown QType = iota // Unknown
QTQuery // Query
QTSubscription // Subcription
QTMutation // Mutation
QTInsert // Insert
QTUpdate // Update
QTDelete // Delete
QTUpsert // Upsert
)
type SelType int8
const (
SelTypeNone SelType = iota
SelTypeUnion
SelTypeMember
)
type SkipType int8
const (
SkipTypeNone SkipType = iota
SkipTypeDrop
SkipTypeNulled
SkipTypeUserNeeded
SkipTypeBlocked
SkipTypeRemote
)
type ColKey struct {
Name string
Base bool
}
type QCode struct {
Type QType
SType QType
Name string
ActionVar string
ActionVal json.RawMessage
Vars []Var
Selects []Select
Consts []Constraint
Roots []int32
rootsA [5]int32
Mutates []Mutate
MUnions map[string][]int32
Schema *sdata.DBSchema
Remotes int32
Cache Cache
Typename bool
Query []byte
Fragments []Fragment
actionArg graph.Arg
}
type Fragment struct {
Name string
Value []byte
}
type Select struct {
Field
Type SelType
Singular bool
Typename bool
Table string
Schema string
Fields []Field
BCols []Column
IArgs []Arg
Where Filter
OrderBy []OrderBy
DistinctOn []sdata.DBColumn
GroupCols bool
Paging Paging
Children []int32
Ti sdata.DBTable
Rel sdata.DBRel
Joins []Join
order Order
through string
tc TConfig
}
type Validation struct {
Source string
Type string
}
type Script struct {
Source string
Name string
}
type TableInfo struct {
sdata.DBTable
}
type FieldType int8
const (
FieldTypeTable FieldType = iota
FieldTypeCol
FieldTypeFunc
)
type Field struct {
ID int32
ParentID int32
Type FieldType
Col sdata.DBColumn
Func sdata.DBFunction
FieldName string
FieldFilter Filter
Args []Arg
SkipRender SkipType
}
type Column struct {
Col sdata.DBColumn
FieldFilter Filter
FieldName string
}
type Function struct {
Name string
// Col sdata.DBColumn
Func sdata.DBFunction
Args []Arg
Agg bool
}
type Filter struct {
*Exp
}
type Exp struct {
Op ExpOp
Joins []Join
Order
OrderBy bool
Left struct {
ID int32
Table string
Col sdata.DBColumn
ColName string
}
Right struct {
ValType ValType
Val string
ID int32
Table string
Col sdata.DBColumn
ColName string
ListType ValType
ListVal []string
Path []string
}
Children []*Exp
childrenA [5]*Exp
}
type Join struct {
Filter *Exp
Rel sdata.DBRel
Local bool
}
type ArgType int8
const (
ArgTypeVal ArgType = iota
ArgTypeVar
ArgTypeCol
)
type Arg struct {
Type ArgType
DType string
Name string
Val string
Col sdata.DBColumn
}
type OrderBy struct {
KeyVar string
Key string
Col sdata.DBColumn
Var string
Order Order
}
type PagingType int8
const (
PTOffset PagingType = iota
PTForward
PTBackward
)
type Paging struct {
Type PagingType
LimitVar string
Limit int32
OffsetVar string
Offset int32
Cursor bool
NoLimit bool
}
type Cache struct {
Header string
}
type Var struct {
Name string
Val json.RawMessage
}
type ExpOp int8
const (
OpNop ExpOp = iota
OpAnd
OpOr
OpNot
OpEquals
OpNotEquals
OpGreaterOrEquals
OpLesserOrEquals
OpGreaterThan
OpLesserThan
OpIn
OpNotIn
OpLike
OpNotLike
OpILike
OpNotILike
OpSimilar
OpNotSimilar
OpRegex
OpNotRegex
OpIRegex
OpNotIRegex
OpContains
OpContainedIn
OpHasInCommon
OpHasKey
OpHasKeyAny
OpHasKeyAll
OpIsNull
OpIsNotNull
OpTsQuery
OpFalse
OpNotDistinct
OpDistinct
OpEqualsTrue
OpNotEqualsTrue
OpSelectExists
)
type ValType int8
const (
ValStr ValType = iota + 1
ValNum
ValBool
ValList
ValObj
ValVar
)
type AggregrateOp int8
const (
AgCount AggregrateOp = iota + 1
AgSum
AgAvg
AgMax
AgMin
)
type Order int8
const (
OrderNone Order = iota
OrderAsc
OrderDesc
OrderAscNullsFirst
OrderAscNullsLast
OrderDescNullsFirst
OrderDescNullsLast
)
func (o Order) String() string {
return []string{"None", "ASC", "DESC", "ASC NULLS FIRST", "ASC NULLS LAST", "DESC NULLLS FIRST", "DESC NULLS LAST"}[o]
}
type Compiler struct {
c Config
s *sdata.DBSchema
tr map[string]trval
}
func NewCompiler(s *sdata.DBSchema, c Config) (*Compiler, error) {
if c.DBSchema == "" {
c.DBSchema = "public"
}
c.defTrv.query.block = c.DefaultBlock
c.defTrv.insert.block = c.DefaultBlock
c.defTrv.update.block = c.DefaultBlock
c.defTrv.upsert.block = c.DefaultBlock
c.defTrv.delete.block = c.DefaultBlock
return &Compiler{c: c, s: s, tr: make(map[string]trval)}, nil
}
func (co *Compiler) Compile(
query []byte,
vmap map[string]json.RawMessage,
role, namespace string,
) (qc *QCode, err error) {
var op graph.Operation
op, err = graph.Parse(query)
if err != nil {
return
}
qc = &QCode{
Name: op.Name,
SType: QTQuery,
Schema: co.s,
Query: op.Query,
Fragments: make([]Fragment, len(op.Frags)),
Vars: make([]Var, len(op.VarDef)),
}
for i, f := range op.Frags {
qc.Fragments[i] = Fragment{Name: f.Name, Value: f.Value}
}
var buf bytes.Buffer
for i, v := range op.VarDef {
graphNodeToJSON(v.Val, &buf)
qc.Vars[i] = Var{Name: v.Name, Val: buf.Bytes()}
buf.Reset()
}
qc.Roots = qc.rootsA[:0]
qc.Type = GetQType(op.Type)
if err = co.compileQuery(qc, &op, role); err != nil {
return
}
if qc.Type == QTMutation {
if err = co.compileMutation(qc, vmap, role); err != nil {
return
}
}
return
}
func (co *Compiler) compileQuery(qc *QCode, op *graph.Operation, role string) error {
var id int32
if len(op.Fields) == 0 {
return errors.New("invalid graphql no query found")
}
if op.Type == graph.OpMutate {
if err := co.setMutationType(qc, op, role); err != nil {
return err
}
}
if err := co.compileOpDirectives(qc, op.Directives); err != nil {
return err
}
qc.Selects = make([]Select, 0, 5)
st := util.NewStackInt32()
if len(op.Fields) == 0 {
return errors.New("empty query")
}
for _, f := range op.Fields {
if f.ParentID == -1 {
if f.Name == "__typename" && op.Name != "" {
qc.Typename = true
}
val := f.ID | (-1 << 16)
st.Push(val)
}
}
for {
if st.Len() == 0 {
break
}
if id >= maxSelectors {
return fmt.Errorf("selector limit reached (%d)", maxSelectors)
}
val := st.Pop()
fid := val & 0xFFFF
parentID := (val >> 16) & 0xFFFF
field := op.Fields[fid]
// A keyword is a cursor field at the top-level
// For example posts_cursor in the root
if field.Type == graph.FieldKeyword {
continue
}
if field.ParentID == -1 {
parentID = -1
}
s1 := Select{
Field: Field{ID: id, ParentID: parentID, Type: FieldTypeTable},
}
sel := &s1
name := co.ParseName(field.Name)
if field.Alias != "" {
sel.FieldName = field.Alias
} else {
sel.FieldName = field.Name
}
sel.Children = make([]int32, 0, 5)
if err := co.compileSelectorDirectives(qc, sel, field.Directives, role); err != nil {
return err
}
if err := co.addRelInfo(name, op, qc, sel, field); err != nil {
return err
}
tr, err := co.setSelectorRoleConfig(role, name, qc, sel)
if err != nil {
return err
}
co.setLimit(tr, qc, sel)
if err := co.compileSelectArgs(sel, field.Args, role); err != nil {
return err
}
if err := co.compileFields(st, op, qc, sel, field, tr, role); err != nil {
return err
}
// Order is important AddFilters must come after compileArgs
if userNeeded := addFilters(qc, &sel.Where, tr); userNeeded && role == "anon" {
sel.SkipRender = SkipTypeUserNeeded
}
// If an actual cursor is available
if sel.Paging.Cursor {
// Set tie-breaker order column for the cursor direction
// this column needs to be the last in the order series.
if err := co.orderByIDCol(sel); err != nil {
return err
}
// Set filter chain needed to make the cursor work
if sel.Paging.Type != PTOffset {
co.addSeekPredicate(sel)
}
}
// Compute and set the relevant where clause required to join
// this table with its parent
co.setRelFilters(qc, sel)
if err := co.validateSelect(sel); err != nil {
return err
}
qc.Selects = append(qc.Selects, s1)
id++
}
if id == 0 {
return errors.New("invalid query: no selectors found")
}
return nil
}
func (co *Compiler) addRelInfo(
name string,
op *graph.Operation,
qc *QCode,
sel *Select,
field graph.Field,
) error {
var psel *Select
var childF, parentF graph.Field
var err error
childF = field
if sel.ParentID == -1 {
qc.Roots = append(qc.Roots, sel.ID)
} else {
psel = &qc.Selects[sel.ParentID]
psel.Children = append(psel.Children, sel.ID)
parentF = op.Fields[field.ParentID]
}
switch field.Type {
case graph.FieldUnion:
sel.Type = SelTypeUnion
if psel == nil {
return fmt.Errorf("union types are only valid with polymorphic relationships")
}
case graph.FieldMember:
// TODO: Fix this
// if sel.Table != sel.Table {
// return fmt.Errorf("inline fragment: 'on %s' should be 'on %s'", sel.Table, sel.Table)
// }
sel.Type = SelTypeMember
sel.Singular = psel.Singular
childF = parentF
parentF = op.Fields[int(parentF.ParentID)]
}
if sel.Rel.Type == sdata.RelSkip {
sel.Rel.Type = sdata.RelNone
} else if sel.ParentID != -1 {
parentName := co.ParseName(parentF.Name)
childName := co.ParseName(childF.Name)
path, err := co.FindPath(childName, parentName, sel.through)
if err != nil {
return graphError(err, childName, parentName, sel.through)
}
sel.Rel = sdata.PathToRel(path[0])
// for _, p := range path {
// rel := sdata.PathToRel(p)
// fmt.Println(childF.Name, parentF.Name,
// "--->>>", rel.Left.Col.Table, rel.Left.Col.Name,
// "|", rel.Right.Col.Table, rel.Right.Col.Name)
// }
rpath := path[1:]
for i := len(rpath) - 1; i >= 0; i-- {
p := rpath[i]
rel := sdata.PathToRel(p)
var pid int32
if i == len(rpath)-1 {
pid = sel.ParentID
} else {
pid = -1
}
sel.Joins = append(sel.Joins, Join{
Rel: rel,
Filter: buildFilter(rel, pid),
})
}
}
if sel.ParentID == -1 ||
sel.Rel.Type == sdata.RelPolymorphic ||
sel.Rel.Type == sdata.RelNone {
schema := co.c.DBSchema
if sel.Schema != "" {
schema = sel.Schema
}
if sel.Ti, err = co.Find(schema, name); err != nil {
return err
}
} else {
sel.Ti = sel.Rel.Left.Ti
}
if sel.Ti.Blocked {
return fmt.Errorf("table: '%t' (%s) blocked", sel.Ti.Blocked, name)
}
sel.Table = sel.Ti.Name
sel.tc = co.getTConfig(sel.Ti.Schema, sel.Ti.Name)
if sel.Rel.Type == sdata.RelRemote {
sel.Table = name
qc.Remotes++
return nil
}
co.setSingular(name, sel)
return nil
}
func (co *Compiler) setRelFilters(qc *QCode, sel *Select) {
rel := sel.Rel
pid := sel.ParentID
if len(sel.Joins) != 0 {
pid = -1
}
switch rel.Type {
case sdata.RelOneToOne, sdata.RelOneToMany:
addAndFilter(&sel.Where, buildFilter(rel, pid))
case sdata.RelEmbedded:
addAndFilter(&sel.Where, buildFilter(rel, pid))
case sdata.RelPolymorphic:
pid = qc.Selects[sel.ParentID].ParentID
ex := newExpOp(OpAnd)
ex1 := newExpOp(OpEquals)
ex1.Left.Table = sel.Ti.Name
ex1.Left.Col = rel.Right.Col
ex1.Right.ID = pid
ex1.Right.Col = rel.Left.Col
ex2 := newExpOp(OpEquals)
ex2.Left.ID = pid
ex2.Left.Col.Table = rel.Left.Col.Table
ex2.Left.Col.Name = rel.Left.Col.FKeyCol
ex2.Right.ValType = ValStr
ex2.Right.Val = sel.Ti.Name
ex.Children = []*Exp{ex1, ex2}
addAndFilter(&sel.Where, ex)
case sdata.RelRecursive:
rcte := "__rcte_" + rel.Right.Ti.Name
ex := newExpOp(OpAnd)
ex1 := newExpOp(OpIsNotNull)
ex2 := newExp()
ex3 := newExp()
v, _ := sel.GetInternalArg("find")
switch v.Val {
case "parents", "parent":
ex1.Left.Table = rcte
ex1.Left.Col = rel.Left.Col
switch {
case !rel.Left.Col.Array && rel.Right.Col.Array:
ex2.Op = OpNotIn
ex2.Left.Table = rcte
ex2.Left.Col = rel.Left.Col
ex2.Right.Table = rcte
ex2.Right.Col = rel.Right.Col
ex3.Op = OpIn
ex3.Left.Table = rcte
ex3.Left.Col = rel.Left.Col
ex3.Right.Col = rel.Right.Col
case rel.Left.Col.Array && !rel.Right.Col.Array:
ex2.Op = OpNotIn
ex2.Left.Table = rcte
ex2.Left.Col = rel.Right.Col
ex2.Right.Table = rcte
ex2.Right.Col = rel.Left.Col
ex3.Op = OpIn
ex3.Left.Col = rel.Right.Col
ex3.Right.Table = rcte
ex3.Right.Col = rel.Left.Col
default:
ex2.Op = OpNotEquals
ex2.Left.Table = rcte
ex2.Left.Col = rel.Left.Col
ex2.Right.Table = rcte
ex2.Right.Col = rel.Right.Col
ex3.Op = OpEquals
ex3.Left.Col = rel.Right.Col
ex3.Right.Table = rcte
ex3.Right.Col = rel.Left.Col
}
default:
ex1.Left.Col = rel.Left.Col
switch {
case !rel.Left.Col.Array && rel.Right.Col.Array:
ex2.Op = OpNotIn
ex2.Left.Col = rel.Left.Col
ex2.Right.Col = rel.Right.Col
ex3.Op = OpIn
ex3.Left.Col = rel.Left.Col
ex3.Right.Table = rcte
ex3.Right.Col = rel.Right.Col
case rel.Left.Col.Array && !rel.Right.Col.Array:
ex2.Op = OpNotIn
ex2.Left.Col = rel.Right.Col
ex2.Right.Col = rel.Left.Col
ex3.Op = OpIn
ex3.Left.Table = rcte
ex3.Left.Col = rel.Right.Col
ex3.Right.Col = rel.Left.Col
default:
ex2.Op = OpNotEquals
ex2.Left.Col = rel.Left.Col
ex2.Right.Col = rel.Right.Col
ex3.Op = OpEquals
ex3.Left.Col = rel.Left.Col
ex3.Right.Table = rcte
ex3.Right.Col = rel.Right.Col
}
}
ex.Children = []*Exp{ex1, ex2, ex3}
addAndFilter(&sel.Where, ex)
}
}
func (co *Compiler) Find(schema, name string) (sdata.DBTable, error) {
if co.c.EnableCamelcase {
name = strings.TrimSuffix(name, singularSuffixSnake)
} else {
name = strings.TrimSuffix(name, singularSuffixCamel)
}
return co.s.Find(schema, name)
}
func (co *Compiler) FindPath(from, to, through string) ([]sdata.TPath, error) {
if co.c.EnableCamelcase {
from = strings.TrimSuffix(from, singularSuffixSnake)
to = strings.TrimSuffix(to, singularSuffixSnake)
} else {
from = strings.TrimSuffix(from, singularSuffixCamel)
to = strings.TrimSuffix(to, singularSuffixCamel)
}
return co.s.FindPath(from, to, through)
}
func buildFilter(rel sdata.DBRel, pid int32) *Exp {
switch rel.Type {
case sdata.RelOneToOne, sdata.RelOneToMany:
ex := newExp()
switch {
case !rel.Left.Col.Array && rel.Right.Col.Array:
ex.Op = OpIn
ex.Left.Col = rel.Left.Col
ex.Right.ID = pid
ex.Right.Col = rel.Right.Col
case rel.Left.Col.Array && !rel.Right.Col.Array:
ex.Op = OpIn
ex.Left.ID = pid
ex.Left.Col = rel.Right.Col
ex.Right.Col = rel.Left.Col
default:
ex.Op = OpEquals
ex.Left.Col = rel.Left.Col
ex.Right.ID = pid
ex.Right.Col = rel.Right.Col
}
return ex
case sdata.RelEmbedded:
ex := newExpOp(OpEquals)
ex.Left.Col = rel.Right.Col
ex.Right.ID = pid
ex.Right.Col = rel.Right.Col
return ex
default:
return nil
}
}
func (co *Compiler) setSingular(fieldName string, sel *Select) {
if sel.Singular {
return
}
if len(sel.Joins) != 0 {
return
}
if (sel.Rel.Type == sdata.RelOneToMany && !sel.Rel.Right.Col.Array) ||
sel.Rel.Type == sdata.RelPolymorphic {
sel.Singular = true
return
}
}
func (co *Compiler) setSelectorRoleConfig(role, fieldName string, qc *QCode, sel *Select) (trval, error) {
tr := co.getRole(role, sel.Ti.Schema, sel.Ti.Name, fieldName)
if tr.isBlocked(qc.SType) {
if qc.SType != QTQuery {
return tr, fmt.Errorf("%s blocked: %s (role: %s)", qc.SType, fieldName, role)
}
sel.SkipRender = SkipTypeBlocked
}
return tr, nil
}
func (co *Compiler) setLimit(tr trval, qc *QCode, sel *Select) {
if sel.Paging.Limit != 0 {
return
}
// Use limit from table role config
if l := tr.limit(qc.Type); l != 0 {
sel.Paging.Limit = l
// Else use default limit from config
} else if co.c.DefaultLimit != 0 {
sel.Paging.Limit = int32(co.c.DefaultLimit)
// Else just go with 20
} else {
sel.Paging.Limit = 20
}
}
// This
// (A, B, C) >= (X, Y, Z)
//
// Becomes
// (A > X)
// OR ((A = X) AND (B > Y))
// OR ((A = X) AND (B = Y) AND (C > Z))
// OR ((A = X) AND (B = Y) AND (C = Z)
func (co *Compiler) addSeekPredicate(sel *Select) {
var or, and *Exp
obLen := len(sel.OrderBy)
if obLen != 0 {
ob := sel.OrderBy[0]
or = newExpOp(OpOr)
isnull := newExpOp(OpIsNull)
isnull.Left.Table = "__cur"
isnull.Left.Col = ob.Col
if ob.Key != "" {
isnull.Left.ColName = ob.Col.Name + "_" + ob.Key
}
or.Children = []*Exp{isnull}
}
for i := 0; i < obLen; i++ {
if i != 0 {
and = newExpOp(OpAnd)
}
for n, ob := range sel.OrderBy {
if n > i {
break
}
f := newExp()
f.Left.Col = ob.Col
f.Right.Table = "__cur"
f.Right.Col = ob.Col
if ob.Key != "" {
f.Right.ColName = ob.Col.Name + "_" + ob.Key
}
switch {
case i > 0 && n != i:
f.Op = OpEquals
case ob.Order == OrderDesc ||
ob.Order == OrderDescNullsFirst || ob.Order == OrderDescNullsLast:
f.Op = OpLesserThan
case ob.Order == OrderAsc ||
ob.Order == OrderAscNullsLast || ob.Order == OrderAscNullsFirst:
f.Op = OpGreaterThan
default:
f.Op = OpGreaterThan
}
// could be null needs to be handled
if !ob.Col.NotNull {
isnull1 := newExpOp(OpIsNull)
isnull1.Left.Table = "__cur"
isnull1.Left.Col = ob.Col
isnull2 := newExpOp(OpIsNull)
isnull2.Left.Col = ob.Col
if ob.Key != "" {
isnull1.Left.ColName = ob.Col.Name + "_" + ob.Key
}
or1 := newExpOp(OpOr)
or1.Children = append(or.Children, isnull1, isnull2, f)
// now that f is added to the above or1 we can set f to or1
f = or1
}
if and != nil {
and.Children = append(and.Children, f)
} else {
or.Children = append(or.Children, f)
}
}
if and != nil {
or.Children = append(or.Children, and)
}
}
addAndFilter(&sel.Where, or)
}
func (co *Compiler) validateSelect(sel *Select) error {
if sel.Rel.Type == sdata.RelRecursive {
v, ok := sel.GetInternalArg("find")
if !ok {
return fmt.Errorf("argument 'find' needed for recursive queries")
}
if v.Val != "parents" && v.Val != "children" {
return fmt.Errorf("valid values for 'find' are 'parents' and 'children'")
}
}
return nil
}
func addFilters(qc *QCode, where *Filter, trv trval) bool {
if fil, userNeeded := trv.filter(qc.SType); fil != nil {
switch fil.Op {
case OpNop:
case OpFalse:
where.Exp = fil
default:
addAndFilter(where, fil)
}
return userNeeded
}
return false
}
func (co *Compiler) setMutationType(qc *QCode, op *graph.Operation, role string) error {
var err error
setActionVar := func(arg graph.Arg) error {
v := arg.Val
if v.Type != graph.NodeVar && v.Type != graph.NodeObj &&
(v.Type != graph.NodeList || len(v.Children) == 0 && v.Children[0].Type != graph.NodeObj) {
return argErr(arg, "variable, an object or a list of objects")
}
qc.ActionVar = arg.Val.Val
qc.actionArg = arg
return nil
}
args := op.Fields[0].Args
for _, arg := range args {