This repository was archived by the owner on Jul 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathCompileSelect.cs
More file actions
3559 lines (3010 loc) · 169 KB
/
CompileSelect.cs
File metadata and controls
3559 lines (3010 loc) · 169 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using GraphView.GraphViewDBPortal;
namespace GraphView
{
partial class WSelectQueryBlock
{
internal override GraphViewExecutionOperator Compile(QueryCompilationContext context, GraphViewCommand command)
{
List<WTableReferenceWithAlias> nonVertexTableReferences = null;
MatchGraph graphPattern = this.ConstructGraph2(out nonVertexTableReferences);
// Vertex and edge aliases from the graph pattern, plus non-vertex table references.
List<string> vertexAndEdgeAliases = new List<string>();
foreach (ConnectedComponent subGraph in graphPattern.ConnectedSubGraphs) {
vertexAndEdgeAliases.AddRange(subGraph.Nodes.Keys);
vertexAndEdgeAliases.AddRange(subGraph.Edges.Keys);
}
foreach (WTableReferenceWithAlias nonVertexTableReference in nonVertexTableReferences) {
vertexAndEdgeAliases.Add(nonVertexTableReference.Alias.Value);
}
// Normalizes the search condition into conjunctive predicates
BooleanExpressionNormalizeVisitor booleanNormalize = new BooleanExpressionNormalizeVisitor();
List<WBooleanExpression> conjunctivePredicates =
this.WhereClause != null && this.WhereClause.SearchCondition != null ?
booleanNormalize.Invoke(this.WhereClause.SearchCondition) :
new List<WBooleanExpression>();
// A list of predicates and their accessed table references
// Predicates in this list are those that cannot be assigned to the match graph
List<Tuple<WBooleanExpression, HashSet<string>>>
predicatesAccessedTableReferences = new List<Tuple<WBooleanExpression, HashSet<string>>>();
AccessedTableColumnVisitor columnVisitor = new AccessedTableColumnVisitor();
GraphviewRuntimeFunctionCountVisitor runtimeFunctionCountVisitor = new GraphviewRuntimeFunctionCountVisitor();
foreach (WBooleanExpression predicate in conjunctivePredicates)
{
bool isOnlyTargetTableReferenced;
bool useGraphViewRuntimeFunction = runtimeFunctionCountVisitor.Invoke(predicate) > 0;
Dictionary<string, HashSet<string>> tableColumnReferences = columnVisitor.Invoke(predicate,
vertexAndEdgeAliases, out isOnlyTargetTableReferenced);
if (useGraphViewRuntimeFunction
|| !isOnlyTargetTableReferenced
|| !this.TryAttachPredicate(graphPattern, predicate, tableColumnReferences))
{
// Attach cross-table predicate's referencing properties for later runtime evaluation
this.AttachProperties(graphPattern, tableColumnReferences);
predicatesAccessedTableReferences.Add(
new Tuple<WBooleanExpression, HashSet<string>>(predicate,
new HashSet<string>(tableColumnReferences.Keys)));
}
}
foreach (WSelectElement selectElement in SelectElements)
{
bool isOnlyTargetTableReferenced;
Dictionary<string, HashSet<string>> tableColumnReferences = columnVisitor.Invoke(selectElement,
vertexAndEdgeAliases, out isOnlyTargetTableReferenced);
// Attach referencing properties for later runtime evaluation or selection
this.AttachProperties(graphPattern, tableColumnReferences);
}
foreach (WTableReferenceWithAlias nonVertexTableReference in nonVertexTableReferences)
{
bool isOnlyTargetTableReferenced;
Dictionary<string, HashSet<string>> tableColumnReferences = columnVisitor.Invoke(
nonVertexTableReference, vertexAndEdgeAliases, out isOnlyTargetTableReferenced);
// Attach referencing properties for later runtime evaluation
this.AttachProperties(graphPattern, tableColumnReferences);
}
ConstructTraversalOrder(graphPattern);
ConstructJsonQueries(command, graphPattern);
return this.ConstructOperator2(command, graphPattern, context, nonVertexTableReferences,
predicatesAccessedTableReferences);
}
/// <summary>
/// If a predicate is a cross-table one, return false
/// Otherwise, attach the predicate to the corresponding node or edge and return true
/// </summary>
/// <param name="graphPattern"></param>
/// <param name="predicate"></param>
/// <param name="tableColumnReferences"></param>
private bool TryAttachPredicate(MatchGraph graphPattern, WBooleanExpression predicate, Dictionary<string, HashSet<string>> tableColumnReferences)
{
// Attach fail if it is a cross-table predicate
if (tableColumnReferences.Count > 1)
return false;
MatchEdge edge;
MatchNode node;
bool attachFlag = false;
foreach (var tableColumnReference in tableColumnReferences)
{
var tableName = tableColumnReference.Key;
var properties = tableColumnReference.Value;
if (graphPattern.TryGetEdge(tableName, out edge))
{
if (edge.Predicates == null)
edge.Predicates = new List<WBooleanExpression>();
edge.Predicates.Add(predicate);
// Attach edge's propeties for later runtime evaluation
AttachProperties(graphPattern, new Dictionary<string, HashSet<string>> {{tableName, properties}});
attachFlag = true;
}
else if (graphPattern.TryGetNode(tableName, out node))
{
if (node.Predicates == null)
node.Predicates = new List<WBooleanExpression>();
node.Predicates.Add(predicate);
AttachProperties(graphPattern, new Dictionary<string, HashSet<string>> { {tableName, properties}} );
attachFlag = true;
}
}
return attachFlag;
}
/// <summary>
/// Attach referencing properties to corresponding nodes and edges
/// for later runtime evaluation or selection.
/// </summary>
/// <param name="graphPattern"></param>
/// <param name="tableColumnReferences"></param>
private void AttachProperties(MatchGraph graphPattern, Dictionary<string, HashSet<string>> tableColumnReferences)
{
MatchEdge edge;
MatchNode node;
foreach (var tableColumnReference in tableColumnReferences)
{
var tableName = tableColumnReference.Key;
var properties = tableColumnReference.Value;
if (graphPattern.TryGetEdge(tableName, out edge))
{
if (edge.Properties == null)
edge.Properties = new List<string>();
foreach (var property in properties)
{
if (!edge.Properties.Contains(property))
edge.Properties.Add(property);
}
}
else if (graphPattern.TryGetNode(tableName, out node))
{
if (node.Properties == null)
node.Properties = new HashSet<string>();
foreach (var property in properties) {
node.Properties.Add(property);
}
}
}
}
internal static bool CanBePushedToServer(GraphViewCommand command, MatchEdge matchEdge)
{
// For Compatible & Hybrid, we can't push edge predicates to server side
if (command.Connection.GraphType != GraphType.GraphAPIOnly) {
Debug.Assert(command.Connection.EdgeSpillThreshold == 1);
return false;
}
if (IsTraversalThroughPhysicalReverseEdge(matchEdge) && !command.Connection.UseReverseEdges) {
return false;
}
return matchEdge != null && matchEdge.EdgeType != WEdgeType.BothEdge;
}
internal static MatchEdge GetPushedToServerEdge(GraphViewCommand command,
Tuple<MatchNode, MatchEdge, List<MatchEdge>, List<MatchEdge>, List<MatchEdge>> tuple)
{
MatchNode currentNode = tuple.Item1;
MatchEdge traversalEdge = tuple.Item3.Count > 0 ? tuple.Item3[0] : null;
bool hasNoBackwardingOrForwardingEdges = tuple.Item4.Count == 0 && tuple.Item5.Count == 0;
MatchEdge pushedToServerEdge = null;
if (hasNoBackwardingOrForwardingEdges)
{
if (traversalEdge != null)
{
pushedToServerEdge = CanBePushedToServer(command, traversalEdge)
? traversalEdge
: null;
}
else if (currentNode.DanglingEdges.Count == 1)
{
pushedToServerEdge = CanBePushedToServer(command, currentNode.DanglingEdges[0])
? currentNode.DanglingEdges[0]
: null;
}
}
return pushedToServerEdge;
}
internal static void ConstructJsonQueries(GraphViewCommand command, MatchGraph graphPattern)
{
foreach (ConnectedComponent subGraph in graphPattern.ConnectedSubGraphs)
{
HashSet<string> processedNodes = new HashSet<string>();
List<Tuple<MatchNode, MatchEdge, List<MatchEdge>, List<MatchEdge>, List<MatchEdge>>> traversalOrder =
subGraph.TraversalOrder;
bool isFirstNodeInTheComponent = true;
foreach (Tuple<MatchNode, MatchEdge, List<MatchEdge>, List<MatchEdge>, List<MatchEdge>> tuple in traversalOrder)
{
MatchNode currentNode = tuple.Item1;
MatchEdge traversalEdge = tuple.Item3.Count > 0 ? tuple.Item3[0] : null;
bool hasNoBackwardingOrForwardingEdges = tuple.Item4.Count == 0 && tuple.Item5.Count == 0;
if (!processedNodes.Contains(currentNode.NodeAlias))
{
MatchEdge pushedToServerEdge = GetPushedToServerEdge(command, tuple);
//
// For the g.E() case
//
if (hasNoBackwardingOrForwardingEdges && traversalEdge == null && currentNode.DanglingEdges.Count == 1)
{
MatchEdge danglingEdge = currentNode.DanglingEdges[0];
if (isFirstNodeInTheComponent && danglingEdge.EdgeType == WEdgeType.OutEdge &&
(currentNode.Predicates == null || !currentNode.Predicates.Any()))
{
ConstructJsonQueryOnEdge(command, currentNode, danglingEdge);
isFirstNodeInTheComponent = false;
currentNode.IsDummyNode = true;
processedNodes.Add(currentNode.NodeAlias);
continue;
}
}
string partitionKey = command.Connection.RealPartitionKey;
ConstructJsonQueryOnNode(command, currentNode, pushedToServerEdge, partitionKey);
//ConstructJsonQueryOnNodeViaExternalAPI(currentNode, null);
processedNodes.Add(currentNode.NodeAlias);
isFirstNodeInTheComponent = false;
}
}
}
}
internal static void ConstructJsonQueryOnNode(GraphViewCommand command, MatchNode node, MatchEdge edge, string partitionKey)
{
string nodeAlias = node.NodeAlias;
string edgeAlias = null;
List<string> nodeProperties = new List<string> { nodeAlias };
List<string> edgeProperties = new List<string>();
bool isReverseAdj = edge != null && IsTraversalThroughPhysicalReverseEdge(edge);
bool isStartVertexTheOriginVertex = edge != null && !edge.IsReversed;
var jsonQuery = new JsonQuery
{
NodeAlias = nodeAlias
};
//
// SELECT N_0 FROM Node N_0
//
jsonQuery.AddSelectElement(nodeAlias);
jsonQuery.FlatProperties.Add(partitionKey);
nodeProperties.AddRange(node.Properties);
if (edge != null)
{
edgeAlias = edge.EdgeAlias;
edgeProperties.Add(edge.EdgeAlias);
edgeProperties.Add(isReverseAdj.ToString());
edgeProperties.Add(isStartVertexTheOriginVertex.ToString());
//
// SELECT N_0, E_0 FROM Node N_0 ...
//
jsonQuery.EdgeAlias = edgeAlias;
jsonQuery.AddSelectElement(edgeAlias);
edgeProperties.AddRange(edge.Properties);
}
//
// Now we don't try to use a JOIN clause to fetch the edges along with the vertex unless in GraphAPI only graph
// Thus, `edgeCondition` is always null
//
if (command.Connection.GraphType != GraphType.GraphAPIOnly) {
Debug.Assert(edge == null);
}
WBooleanExpression edgeCondition = null;
if (edge != null)
{
// pairs in this dict will be used in JOIN clause
jsonQuery.JoinDictionary.Add(edgeAlias, $"{nodeAlias}.{(isReverseAdj ? DocumentDBKeywords.KW_VERTEX_REV_EDGE : DocumentDBKeywords.KW_VERTEX_EDGE)}");
foreach (WBooleanExpression predicate in edge.Predicates) {
edgeCondition = WBooleanBinaryExpression.Conjunction(edgeCondition, predicate);
}
}
if (edgeCondition != null)
{
edgeCondition = new WBooleanBinaryExpression
{
BooleanExpressionType = BooleanBinaryExpressionType.Or,
FirstExpr = new WBooleanParenthesisExpression
{
Expression = edgeCondition
},
SecondExpr = new WBooleanComparisonExpression
{
ComparisonType = BooleanComparisonType.Equals,
FirstExpr = new WColumnReferenceExpression(nodeAlias, isReverseAdj
? DocumentDBKeywords.KW_VERTEX_REVEDGE_SPILLED
: DocumentDBKeywords.KW_VERTEX_EDGE_SPILLED),
SecondExpr = new WValueExpression("true")
}
};
jsonQuery.FlatProperties.Add(isReverseAdj ? DocumentDBKeywords.KW_VERTEX_REVEDGE_SPILLED: DocumentDBKeywords.KW_VERTEX_EDGE_SPILLED);
}
// Most important variable of a JsonQuery object
jsonQuery.RawWhereClause = new WBooleanComparisonExpression
{
ComparisonType = BooleanComparisonType.Equals,
FirstExpr = new WColumnReferenceExpression(nodeAlias, DocumentDBKeywords.KW_EDGEDOC_IDENTIFIER),
SecondExpr = new WValueExpression("null")
};
// Note: this move below protects that column name from replacing.(DocDB ToString)
jsonQuery.FlatProperties.Add(DocumentDBKeywords.KW_EDGEDOC_IDENTIFIER);
WBooleanExpression nodeCondition = null;
foreach (WBooleanExpression predicate in node.Predicates)
{
nodeCondition = WBooleanBinaryExpression.Conjunction(nodeCondition, predicate);
}
if (nodeCondition != null)
{
jsonQuery.WhereConjunction(nodeCondition, BooleanBinaryExpressionType.And);
}
if (edgeCondition != null)
{
jsonQuery.WhereConjunction(edgeCondition, BooleanBinaryExpressionType.And);
}
jsonQuery.NodeProperties = nodeProperties;
jsonQuery.EdgeProperties = edgeProperties;
node.AttachedJsonQuery = jsonQuery;
}
internal static void ConstructJsonQueryOnEdge(GraphViewCommand command, MatchNode node, MatchEdge edge)
{
string nodeAlias = node.NodeAlias;
string edgeAlias = edge.EdgeAlias;
List<string> nodeProperties = new List<string> { nodeAlias };
List<string> edgeProperties = new List<string> { edgeAlias };
nodeProperties.AddRange(node.Properties);
edgeProperties.AddRange(edge.Properties);
var jsonQuery = new JsonQuery
{
NodeAlias = nodeAlias,
EdgeAlias = edgeAlias
};
//
// SELECT N_0, E_0 FROM Node N_0 Join E_0 IN N_0._edge
//
jsonQuery.AddSelectElement(nodeAlias);
jsonQuery.AddSelectElement(edgeAlias);
jsonQuery.JoinDictionary.Add(edgeAlias, $"{nodeAlias}.{DocumentDBKeywords.KW_VERTEX_EDGE}");
WBooleanExpression tempEdgeCondition = null;
foreach (WBooleanExpression predicate in edge.Predicates)
{
tempEdgeCondition = WBooleanBinaryExpression.Conjunction(tempEdgeCondition, predicate);
}
// Where condition constructing
//
// WHERE ((N_0._isEdgeDoc = true AND N_0._is_reverse = false) OR N_0._edgeSpilled = false)
// AND (edgeConditionString)
//
jsonQuery.RawWhereClause = new WBooleanComparisonExpression
{
ComparisonType = BooleanComparisonType.Equals,
FirstExpr = new WColumnReferenceExpression(nodeAlias, DocumentDBKeywords.KW_EDGEDOC_IDENTIFIER),
SecondExpr = new WValueExpression("true", false)
};
// Note: this move below protects that column name from replacing.(DocDB ToString)
jsonQuery.FlatProperties.Add(DocumentDBKeywords.KW_EDGEDOC_IDENTIFIER);
jsonQuery.WhereConjunction(new WBooleanComparisonExpression
{
ComparisonType = BooleanComparisonType.Equals,
FirstExpr = new WColumnReferenceExpression(nodeAlias, DocumentDBKeywords.KW_EDGEDOC_ISREVERSE),
SecondExpr = new WValueExpression("false", false)
}, BooleanBinaryExpressionType.And);
jsonQuery.FlatProperties.Add(DocumentDBKeywords.KW_EDGEDOC_ISREVERSE);
jsonQuery.WhereConjunction(new WBooleanComparisonExpression
{
ComparisonType = BooleanComparisonType.Equals,
FirstExpr = new WColumnReferenceExpression(nodeAlias, DocumentDBKeywords.KW_VERTEX_EDGE_SPILLED),
SecondExpr = new WValueExpression("false", false)
}, BooleanBinaryExpressionType.Or);
jsonQuery.FlatProperties.Add(DocumentDBKeywords.KW_VERTEX_EDGE_SPILLED);
if (tempEdgeCondition != null)
{
jsonQuery.WhereConjunction(tempEdgeCondition, BooleanBinaryExpressionType.And);
}
jsonQuery.NodeProperties = nodeProperties;
jsonQuery.EdgeProperties = edgeProperties;
edge.AttachedJsonQuery = jsonQuery;
}
private MatchGraph ConstructGraph2(out List<WTableReferenceWithAlias> nonVertexTableReferences)
{
nonVertexTableReferences = new List<WTableReferenceWithAlias>();
Dictionary<string, MatchPath> pathDictionary = new Dictionary<string, MatchPath>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, MatchEdge> reversedEdgeDict = new Dictionary<string, MatchEdge>();
UnionFind unionFind = new UnionFind();
Dictionary<string, MatchNode> vertexTableCollection = new Dictionary<string, MatchNode>(StringComparer.OrdinalIgnoreCase);
List<ConnectedComponent> connectedSubGraphs = new List<ConnectedComponent>();
Dictionary<string, ConnectedComponent> subGraphMap = new Dictionary<string, ConnectedComponent>(StringComparer.OrdinalIgnoreCase);
Dictionary<string, string> parent = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
unionFind.Parent = parent;
// Goes through the FROM clause and extracts vertex table references and non-vertex table references
if (this.FromClause != null)
{
List<WNamedTableReference> vertexTableList = new List<WNamedTableReference>();
TableClassifyVisitor tcVisitor = new TableClassifyVisitor();
tcVisitor.Invoke(FromClause, vertexTableList, nonVertexTableReferences);
foreach (WNamedTableReference vertexTableRef in vertexTableList)
{
vertexTableCollection.GetOrCreate(vertexTableRef.Alias.Value);
if (!parent.ContainsKey(vertexTableRef.Alias.Value))
parent[vertexTableRef.Alias.Value] = vertexTableRef.Alias.Value;
}
}
// Consturct nodes and edges of a match graph defined by the SelectQueryBlock
if (this.MatchClause != null)
{
if (this.MatchClause.Paths.Count > 0)
{
foreach (WMatchPath path in this.MatchClause.Paths)
{
int index = 0;
MatchEdge edgeToSrcNode = null;
for (int count = path.PathEdgeList.Count; index < count; ++index)
{
WSchemaObjectName currentNodeTableRef = path.PathEdgeList[index].Item1;
WEdgeColumnReferenceExpression currentEdgeColumnRef = path.PathEdgeList[index].Item2;
string currentNodeExposedName = currentNodeTableRef.BaseIdentifier.Value;
WSchemaObjectName nextNodeTableRef = index != count - 1
? path.PathEdgeList[index + 1].Item1
: path.Tail;
// Consturct the source node of a path in MatchClause.Paths
MatchNode srcNode = vertexTableCollection.GetOrCreate(currentNodeExposedName);
if (srcNode.NodeAlias == null)
{
srcNode.NodeAlias = currentNodeExposedName;
srcNode.Neighbors = new List<MatchEdge>();
srcNode.ReverseNeighbors = new List<MatchEdge>();
srcNode.DanglingEdges = new List<MatchEdge>();
srcNode.Predicates = new List<WBooleanExpression>();
srcNode.Properties = new HashSet<string>();
}
// Consturct the edge of a path in MatchClause.Paths
string edgeAlias = currentEdgeColumnRef.Alias;
MatchEdge edgeFromSrcNode;
if (currentEdgeColumnRef.MinLength == 1 && currentEdgeColumnRef.MaxLength == 1)
{
edgeFromSrcNode = new MatchEdge
{
SourceNode = srcNode,
EdgeColumn = currentEdgeColumnRef,
EdgeAlias = edgeAlias,
Predicates = new List<WBooleanExpression>(),
BindNodeTableObjName =
new WSchemaObjectName(
),
IsReversed = false,
EdgeType = currentEdgeColumnRef.EdgeType,
Properties = new List<string>(GraphViewReservedProperties.ReservedEdgeProperties),
};
}
else
{
MatchPath matchPath = new MatchPath
{
SourceNode = srcNode,
EdgeColumn = currentEdgeColumnRef,
EdgeAlias = edgeAlias,
Predicates = new List<WBooleanExpression>(),
BindNodeTableObjName =
new WSchemaObjectName(
),
MinLength = currentEdgeColumnRef.MinLength,
MaxLength = currentEdgeColumnRef.MaxLength,
ReferencePathInfo = false,
AttributeValueDict = currentEdgeColumnRef.AttributeValueDict,
IsReversed = false,
EdgeType = currentEdgeColumnRef.EdgeType,
Properties = new List<string>(GraphViewReservedProperties.ReservedEdgeProperties),
};
pathDictionary[edgeAlias] = matchPath;
edgeFromSrcNode = matchPath;
}
if (edgeToSrcNode != null)
{
edgeToSrcNode.SinkNode = srcNode;
if (!(edgeToSrcNode is MatchPath))
{
// Construct reverse edge
MatchEdge reverseEdge = new MatchEdge
{
SourceNode = edgeToSrcNode.SinkNode,
SinkNode = edgeToSrcNode.SourceNode,
EdgeColumn = edgeToSrcNode.EdgeColumn,
EdgeAlias = edgeToSrcNode.EdgeAlias,
Predicates = edgeToSrcNode.Predicates,
BindNodeTableObjName =
new WSchemaObjectName(
),
IsReversed = true,
EdgeType = edgeToSrcNode.EdgeType,
Properties = new List<string>(GraphViewReservedProperties.ReservedEdgeProperties),
};
srcNode.ReverseNeighbors.Add(reverseEdge);
reversedEdgeDict[edgeToSrcNode.EdgeAlias] = reverseEdge;
}
}
edgeToSrcNode = edgeFromSrcNode;
if (!parent.ContainsKey(currentNodeExposedName))
parent[currentNodeExposedName] = currentNodeExposedName;
string nextNodeExposedName = nextNodeTableRef != null ? nextNodeTableRef.BaseIdentifier.Value : null;
if (nextNodeExposedName != null)
{
if (!parent.ContainsKey(nextNodeExposedName))
parent[nextNodeExposedName] = nextNodeExposedName;
unionFind.Union(currentNodeExposedName, nextNodeExposedName);
srcNode.Neighbors.Add(edgeFromSrcNode);
}
// Dangling edge without SinkNode
else
{
srcNode.DanglingEdges.Add(edgeFromSrcNode);
srcNode.Properties.Add(GremlinKeyword.Star);
}
}
if (path.Tail == null) continue;
// Consturct destination node of a path in MatchClause.Paths
string tailExposedName = path.Tail.BaseIdentifier.Value;
MatchNode destNode = vertexTableCollection.GetOrCreate(tailExposedName);
if (destNode.NodeAlias == null)
{
destNode.NodeAlias = tailExposedName;
destNode.Neighbors = new List<MatchEdge>();
destNode.ReverseNeighbors = new List<MatchEdge>();
destNode.DanglingEdges = new List<MatchEdge>();
destNode.Predicates = new List<WBooleanExpression>();
destNode.Properties = new HashSet<string>();
}
if (edgeToSrcNode != null)
{
edgeToSrcNode.SinkNode = destNode;
if (!(edgeToSrcNode is MatchPath))
{
// Construct reverse edge
MatchEdge reverseEdge = new MatchEdge
{
SourceNode = edgeToSrcNode.SinkNode,
SinkNode = edgeToSrcNode.SourceNode,
EdgeColumn = edgeToSrcNode.EdgeColumn,
EdgeAlias = edgeToSrcNode.EdgeAlias,
Predicates = edgeToSrcNode.Predicates,
BindNodeTableObjName =
new WSchemaObjectName(
),
IsReversed = true,
EdgeType = edgeToSrcNode.EdgeType,
Properties = new List<string>(GraphViewReservedProperties.ReservedEdgeProperties),
};
destNode.ReverseNeighbors.Add(reverseEdge);
reversedEdgeDict[edgeToSrcNode.EdgeAlias] = reverseEdge;
}
}
}
}
}
// Use union find algorithmn to define which subgraph does a node belong to and put it into where it belongs to.
foreach (var node in vertexTableCollection)
{
string root;
root = unionFind.Find(node.Key); // put them into the same graph
MatchNode patternNode = node.Value;
if (patternNode.NodeAlias == null)
{
patternNode.NodeAlias = node.Key;
patternNode.Neighbors = new List<MatchEdge>();
patternNode.ReverseNeighbors = new List<MatchEdge>();
patternNode.DanglingEdges = new List<MatchEdge>();
patternNode.Predicates = new List<WBooleanExpression>();
patternNode.Properties = new HashSet<string>();
}
if (!subGraphMap.ContainsKey(root))
{
ConnectedComponent subGraph = new ConnectedComponent();
subGraph.Nodes[node.Key] = node.Value;
foreach (MatchEdge edge in node.Value.Neighbors) {
subGraph.Edges[edge.EdgeAlias] = edge;
}
foreach (MatchEdge edge in node.Value.DanglingEdges) {
edge.IsDanglingEdge = true;
subGraph.Edges[edge.EdgeAlias] = edge;
}
subGraphMap[root] = subGraph;
connectedSubGraphs.Add(subGraph);
subGraph.IsTailNode[node.Value] = false;
}
else
{
ConnectedComponent subGraph = subGraphMap[root];
subGraph.Nodes[node.Key] = node.Value;
foreach (MatchEdge edge in node.Value.Neighbors) {
subGraph.Edges[edge.EdgeAlias] = edge;
}
foreach (MatchEdge edge in node.Value.DanglingEdges) {
edge.IsDanglingEdge = true;
subGraph.Edges[edge.EdgeAlias] = edge;
}
subGraph.IsTailNode[node.Value] = false;
}
}
// Combine all subgraphs into a complete match graph and return it
MatchGraph graphPattern = new MatchGraph
{
ConnectedSubGraphs = connectedSubGraphs,
ReversedEdgeDict = reversedEdgeDict,
};
return graphPattern;
}
private static void ConstructTraversalOrder(MatchGraph graphPattern)
{
DocDbGraphOptimizer graphOptimizer = new DocDbGraphOptimizer(graphPattern);
foreach (ConnectedComponent subGraph in graphPattern.ConnectedSubGraphs) {
subGraph.TraversalOrder = graphOptimizer.GetOptimizedTraversalOrder(subGraph);
}
}
/// <summary>
/// If using node._reverse_edge, return true.
/// If using node._edge, return false
/// </summary>
/// <param name="edge"></param>
/// <returns></returns>
internal static bool IsTraversalThroughPhysicalReverseEdge(MatchEdge edge)
{
if ((edge.EdgeType == WEdgeType.OutEdge && edge.IsReversed)
|| edge.EdgeType == WEdgeType.InEdge && !edge.IsReversed)
return true;
return false;
}
/// <summary>
/// Return adjacency list's type as the parameter of adjacency list decoder
/// Item1 indicates whether to cross apply forward adjacency list
/// Item2 indicates whether to cross apply backward adjacency list
/// </summary>
/// <param name="context"></param>
/// <param name="edge"></param>
/// <returns></returns>
private Tuple<bool, bool> GetAdjDecoderCrossApplyTypeParameter(MatchEdge edge)
{
if (edge.EdgeType == WEdgeType.BothEdge)
return new Tuple<bool, bool>(true, true);
if (IsTraversalThroughPhysicalReverseEdge(edge))
return new Tuple<bool, bool>(false, true);
else
return new Tuple<bool, bool>(true, false);
}
/// <summary>
/// Return the edge's traversal column reference
/// </summary>
/// <param name="edge"></param>
/// <returns></returns>
private static WColumnReferenceExpression GetAdjacencyListTraversalColumn(MatchEdge edge)
{
if (edge.EdgeType == WEdgeType.BothEdge)
return new WColumnReferenceExpression(edge.EdgeAlias, GremlinKeyword.EdgeOtherV);
return new WColumnReferenceExpression(edge.EdgeAlias,
IsTraversalThroughPhysicalReverseEdge(edge) ? GremlinKeyword.EdgeSourceV : GremlinKeyword.EdgeSinkV);
}
/// <summary>
/// Return traversal type
/// </summary>
/// <param name="context"></param>
/// <param name="edge"></param>
/// <returns></returns>
private TraversalOperator.TraversalTypeEnum GetTraversalType(MatchEdge edge)
{
if (edge.EdgeType == WEdgeType.BothEdge) {
return TraversalOperator.TraversalTypeEnum.Other;
}
return IsTraversalThroughPhysicalReverseEdge(edge)
? TraversalOperator.TraversalTypeEnum.Source
: TraversalOperator.TraversalTypeEnum.Sink;
}
/// <summary>
/// Generate a local context for edge's predicate evaluation
/// </summary>
/// <param name="edgeTableAlias"></param>
/// <param name="projectedFields"></param>
/// <returns></returns>
internal QueryCompilationContext GenerateLocalContextForAdjacentListDecoder(string edgeTableAlias, List<string> projectedFields)
{
var localContext = new QueryCompilationContext();
var localIndex = 0;
foreach (var projectedField in projectedFields)
{
var columnReference = new WColumnReferenceExpression(edgeTableAlias, projectedField);
localContext.RawRecordLayout.Add(columnReference, localIndex++);
}
return localContext;
}
/// <summary>
/// Check whether all the tabls referenced by the cross-table predicate have been processed
/// If so, embed the predicate in a filter operator and append it to the operator list
/// </summary>
/// <param name="context"></param>
/// <param name="connection"></param>
/// <param name="tableReferences"></param>
/// <param name="remainingPredicatesAndTheirTableReferences"></param>
/// <param name="childrenProcessor"></param>
private static void CheckRemainingPredicatesAndAppendFilterOp(QueryCompilationContext context, GraphViewCommand command,
HashSet<string> tableReferences,
List<Tuple<WBooleanExpression, HashSet<string>>> remainingPredicatesAndTheirTableReferences,
List<GraphViewExecutionOperator> childrenProcessor)
{
List<int> toBeRemovedIndexes = new List<int>();
//
// Predicates are appended in the order they are encountered in the WHERE clause
//
for (int i = 0; i < remainingPredicatesAndTheirTableReferences.Count; i++)
{
WBooleanExpression predicate = remainingPredicatesAndTheirTableReferences[i].Item1;
HashSet<string> tableRefs = remainingPredicatesAndTheirTableReferences[i].Item2;
if (tableReferences.IsSupersetOf(tableRefs))
{
// Enable batch mode
childrenProcessor.Add(
new FilterInBatchOperator(
childrenProcessor.Count != 0
? childrenProcessor.Last()
: context.OuterContextOp,
predicate.CompileToBatchFunction(context, command)));
toBeRemovedIndexes.Add(i);
context.CurrentExecutionOperator = childrenProcessor.Last();
}
}
for (int i = toBeRemovedIndexes.Count - 1; i >= 0; i--)
{
int toBeRemovedIndex = toBeRemovedIndexes[i];
remainingPredicatesAndTheirTableReferences.RemoveAt(toBeRemovedIndex);
}
}
/// <summary>
/// Generate AdjacencyListDecoder and update context's layout for edges
/// </summary>
/// <param name="command"></param>
/// <param name="context"></param>
/// <param name="operatorChain"></param>
/// <param name="edges"></param>
/// <param name="predicatesAccessedTableReferences"></param>
/// <param name="isMatchingEdges"></param>
private void CrossApplyEdges(
GraphViewCommand command,
QueryCompilationContext context,
List<GraphViewExecutionOperator> operatorChain,
IList<MatchEdge> edges,
List<Tuple<WBooleanExpression, HashSet<string>>> predicatesAccessedTableReferences,
bool isMatchingEdges = false)
{
HashSet<string> tableReferences = context.TableReferences;
foreach (MatchEdge edge in edges)
{
Tuple<bool, bool> crossApplyTypeTuple = this.GetAdjDecoderCrossApplyTypeParameter(edge);
QueryCompilationContext localEdgeContext = this.GenerateLocalContextForAdjacentListDecoder(edge.EdgeAlias, edge.Properties);
WBooleanExpression edgePredicates = edge.RetrievePredicatesExpression();
operatorChain.Add(new AdjacencyListDecoder(
operatorChain.Last(),
context.LocateColumnReference(edge.SourceNode.NodeAlias, GremlinKeyword.Star),
crossApplyTypeTuple.Item1, crossApplyTypeTuple.Item2, !edge.IsReversed,
edgePredicates != null ? edgePredicates.CompileToFunction(localEdgeContext, command) : null,
edge.Properties, command, context.RawRecordLayout.Count + edge.Properties.Count));
context.CurrentExecutionOperator = operatorChain.Last();
// Update edge's context info
tableReferences.Add(edge.EdgeAlias);
this.UpdateEdgeLayout(edge.EdgeAlias, edge.Properties, context);
if (isMatchingEdges)
{
WColumnReferenceExpression sinkNodeIdColumnReference = new WColumnReferenceExpression(edge.SinkNode.NodeAlias, GremlinKeyword.NodeID);
//
// Add "edge.traversalColumn = sinkNode.id" filter
//
WColumnReferenceExpression edgeSinkColumnReference = GetAdjacencyListTraversalColumn(edge);
WBooleanComparisonExpression edgeJoinPredicate = new WBooleanComparisonExpression
{
ComparisonType = BooleanComparisonType.Equals,
FirstExpr = edgeSinkColumnReference,
SecondExpr = sinkNodeIdColumnReference
};
operatorChain.Add(new FilterOperator(operatorChain.Last(),
edgeJoinPredicate.CompileToFunction(context, command)));
context.CurrentExecutionOperator = operatorChain.Last();
}
CheckRemainingPredicatesAndAppendFilterOp(context, command,
new HashSet<string>(tableReferences),
predicatesAccessedTableReferences,
operatorChain);
}
}
/// <summary>
/// Generate matching indexes for backwardMatchingEdges
/// </summary>
/// <param name="context"></param>
/// <param name="backwardMatchingEdges"></param>
/// <returns></returns>
private List<Tuple<int, int>> GenerateMatchingIndexesForBackforwadMatchingEdges(QueryCompilationContext context, List<MatchEdge> backwardMatchingEdges)
{
if (backwardMatchingEdges.Count == 0) return null;
var localContext = new QueryCompilationContext();
var node = backwardMatchingEdges[0].SourceNode;
UpdateNodeLayout(node.NodeAlias, node.Properties, localContext);
var matchingIndexes = new List<Tuple<int, int>>();
foreach (var backwardMatchingEdge in backwardMatchingEdges)
{
// backwardEdges.SinkNode.id = backwardEdges.traversalColumn
var sourceMatchIndex =
context.RawRecordLayout[new WColumnReferenceExpression(backwardMatchingEdge.SinkNode.NodeAlias, "id")];
UpdateEdgeLayout(backwardMatchingEdge.EdgeAlias, backwardMatchingEdge.Properties, localContext);
var edgeTraversalColumn = GetAdjacencyListTraversalColumn(backwardMatchingEdge);
matchingIndexes.Add(new Tuple<int, int>(sourceMatchIndex, localContext.LocateColumnReference(edgeTraversalColumn)));
}
return matchingIndexes;
}
/// <summary>
/// Update the raw record layout when new properties are added
/// </summary>
/// <param name="tableName"></param>
/// <param name="properties"></param>
/// <param name="rawRecordLayout"></param>
private void UpdateRawRecordLayout(string tableName, List<string> properties,
Dictionary<WColumnReferenceExpression, int> rawRecordLayout)
{
var nextLayoutIndex = rawRecordLayout.Count;
foreach (var property in properties)
{
var columnReference = new WColumnReferenceExpression(tableName, property);
if (!rawRecordLayout.ContainsKey(columnReference))
rawRecordLayout.Add(columnReference, nextLayoutIndex++);
}
}
private void UpdateNodeLayout(string nodeAlias, HashSet<string> properties, QueryCompilationContext context)
{
foreach (string propertyName in properties)
{
ColumnGraphType columnGraphType = GraphViewReservedProperties.IsNodeReservedProperty(propertyName)
? GraphViewReservedProperties.ReservedNodePropertiesColumnGraphTypes[propertyName]
: ColumnGraphType.Value;
context.AddField(nodeAlias, propertyName, columnGraphType);
}
}
private void UpdateEdgeLayout(string edgeAlias, List<string> properties, QueryCompilationContext context)
{
// Update context's record layout
context.AddField(edgeAlias, GremlinKeyword.EdgeSourceV, ColumnGraphType.EdgeSource);
context.AddField(edgeAlias, GremlinKeyword.EdgeSinkV, ColumnGraphType.EdgeSink);
context.AddField(edgeAlias, GremlinKeyword.EdgeOtherV, ColumnGraphType.Value);
context.AddField(edgeAlias, GremlinKeyword.EdgeID, ColumnGraphType.EdgeId);
context.AddField(edgeAlias, GremlinKeyword.Star, ColumnGraphType.EdgeObject);
for (var i = GraphViewReservedProperties.ReservedEdgeProperties.Count; i < properties.Count; i++)
{
context.AddField(edgeAlias, properties[i], ColumnGraphType.Value);
}
}
private GraphViewExecutionOperator ConstructOperator2(GraphViewCommand command, MatchGraph graphPattern,
QueryCompilationContext context, List<WTableReferenceWithAlias> nonVertexTableReferences,
List<Tuple<WBooleanExpression, HashSet<string>>> predicatesAccessedTableReferences)
{
List<GraphViewExecutionOperator> operatorChain = new List<GraphViewExecutionOperator>();
HashSet<string> tableReferences = context.TableReferences;
if (context.OuterContextOp != null)
{
context.CurrentExecutionOperator = context.OuterContextOp;
CheckRemainingPredicatesAndAppendFilterOp(context, command,
new HashSet<string>(tableReferences), predicatesAccessedTableReferences,
operatorChain);
}
foreach (ConnectedComponent subGraph in graphPattern.ConnectedSubGraphs)
{
List<Tuple<MatchNode, MatchEdge, List<MatchEdge>, List<MatchEdge>, List<MatchEdge>>> traversalOrder =
subGraph.TraversalOrder;
HashSet<string> processedNodes = new HashSet<string>();
bool isFirstNodeInTheComponent = true;
foreach (Tuple<MatchNode, MatchEdge, List<MatchEdge>, List<MatchEdge>, List<MatchEdge>> tuple in traversalOrder)
{
MatchNode currentNode = tuple.Item1;
List<MatchEdge> traversalEdges = tuple.Item3;
List<MatchEdge> backwardMatchingEdges = tuple.Item4;
List<MatchEdge> forwardMatchingEdges = tuple.Item5;
if (isFirstNodeInTheComponent)
{
isFirstNodeInTheComponent = false;
GraphViewExecutionOperator startOp = currentNode.IsDummyNode
? (GraphViewExecutionOperator)(new FetchEdgeOperator(command,
currentNode.DanglingEdges[0].AttachedJsonQuery))
: new FetchNodeOperator(
command,
currentNode.AttachedJsonQuery);