-
Notifications
You must be signed in to change notification settings - Fork 14
/
SoqlQueryListener.java
905 lines (747 loc) · 28.5 KB
/
SoqlQueryListener.java
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
/**
* Copyright (C) 2023 Czech Technical University in Prague
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.cvut.kbss.jopa.query.soql;
import cz.cvut.kbss.jopa.exception.SoqlException;
import cz.cvut.kbss.jopa.model.MetamodelImpl;
import cz.cvut.kbss.jopa.model.metamodel.Attribute;
import cz.cvut.kbss.jopa.model.metamodel.EntityType;
import cz.cvut.kbss.jopa.model.metamodel.IdentifiableEntityType;
import cz.cvut.kbss.jopa.model.metamodel.PluralAttribute;
import cz.cvut.kbss.jopa.model.metamodel.SingularAttribute;
import cz.cvut.kbss.jopa.model.metamodel.Type;
import cz.cvut.kbss.jopa.query.sparql.SparqlConstants;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
public class SoqlQueryListener implements SoqlListener {
private static final Logger LOG = LoggerFactory.getLogger(SoqlQueryListener.class);
private final MetamodelImpl metamodel;
private String soql;
private String sparql;
private String typeDef = SoqlConstants.SELECT;
// keeps pointer at created object of SoqlAttribute while processing other necessary rules
private SoqlAttribute attrPointer;
private final List<SoqlAttribute> attributes;
// keeps index of first object of SoqlAttribute after OR operator
private final Set<SoqlAttribute> objectOfNextOr;
private final List<SoqlOrderParameter> orderAttributes;
private final List<SoqlGroupParameter> groupAttributes;
private final Map<String, String> objectTypes;
private boolean isSelectedParamDistinct = false;
private boolean isSelectedParamCount = false;
private boolean isInObjectIdentifierExpression = false;
private String projectedVariable;
private String rootVariable = "?x";
public SoqlQueryListener(MetamodelImpl metamodel) {
this.metamodel = Objects.requireNonNull(metamodel);
this.attributes = new ArrayList<>();
this.objectOfNextOr = new HashSet<>();
this.orderAttributes = new ArrayList<>();
this.groupAttributes = new ArrayList<>();
this.objectTypes = new HashMap<>();
}
@Override
public void enterQuerySentence(SoqlParser.QuerySentenceContext ctx) {
}
@Override
public void exitQuerySentence(SoqlParser.QuerySentenceContext ctx) {
this.soql = ctx.getText();
buildSparqlQueryString();
}
@Override
public void enterSelectStatement(SoqlParser.SelectStatementContext ctx) {
}
@Override
public void exitSelectStatement(SoqlParser.SelectStatementContext ctx) {
}
@Override
public void enterParams(SoqlParser.ParamsContext ctx) {
}
@Override
public void exitParams(SoqlParser.ParamsContext ctx) {
}
@Override
public void enterParam(SoqlParser.ParamContext ctx) {
}
@Override
public void exitParam(SoqlParser.ParamContext ctx) {
}
@Override
public void enterJoinedParams(SoqlParser.JoinedParamsContext ctx) {
SoqlNode firstNode = linkContextNodes(ctx);
SoqlAttribute myAttr = new SoqlAttribute(firstNode);
pushNewAttribute(myAttr);
}
private void pushNewAttribute(SoqlAttribute myAttr) {
attributes.add(myAttr);
this.attrPointer = myAttr;
}
@Override
public void exitJoinedParams(SoqlParser.JoinedParamsContext ctx) {
}
@Override
public void enterParamComma(SoqlParser.ParamCommaContext ctx) {
}
@Override
public void exitParamComma(SoqlParser.ParamCommaContext ctx) {
}
@Override
public void enterDistinctParam(SoqlParser.DistinctParamContext ctx) {
}
@Override
public void exitDistinctParam(SoqlParser.DistinctParamContext ctx) {
}
@Override
public void enterSelectedParam(SoqlParser.SelectedParamContext ctx) {
}
@Override
public void exitSelectedParam(SoqlParser.SelectedParamContext ctx) {
if (!isSelectedParamCount) {
this.projectedVariable = ctx.getText();
}
}
@Override
public void enterCount(SoqlParser.CountContext ctx) {
isSelectedParamCount = true;
}
@Override
public void exitCount(SoqlParser.CountContext ctx) {
this.projectedVariable = ctx.getChild(2).getText();
}
@Override
public void enterObject(SoqlParser.ObjectContext ctx) {
}
@Override
public void exitObject(SoqlParser.ObjectContext ctx) {
}
@Override
public void enterObjWithAttr(SoqlParser.ObjWithAttrContext ctx) {
String owner = getOwnerFromParam(ctx);
String attribute = getAttributeFromParam(ctx);
// objectNode.attributeNode
SoqlNode objectNode = new AttributeNode(owner);
SoqlNode attributeNode = new AttributeNode(objectNode, attribute);
objectNode.setChild(attributeNode);
if (isIdentifier(objectNode, attributeNode)) {
this.isInObjectIdentifierExpression = true;
if (projectedVariable.equals(objectNode.getValue())) {
attrPointer.setProjected(true);
}
} else {
setIris(objectNode);
SoqlAttribute myAttr = new SoqlAttribute(objectNode);
pushNewAttribute(myAttr);
}
}
private boolean isIdentifier(SoqlNode objectNode, SoqlNode attributeNode) {
if (!objectTypes.containsKey(objectNode.getValue())) {
return false;
}
final String objectName = objectTypes.get(objectNode.getValue());
IdentifiableEntityType<?> entityType = getEntityType(objectName);
if (entityType == null) {
return false;
}
return entityType.getIdentifier().getName().equals(attributeNode.getValue());
}
@Override
public void exitObjWithAttr(SoqlParser.ObjWithAttrContext ctx) {
}
@Override
public void enterObjWithOutAttr(SoqlParser.ObjWithOutAttrContext ctx) {
}
@Override
public void exitObjWithOutAttr(SoqlParser.ObjWithOutAttrContext ctx) {
}
@Override
public void enterAttribute(SoqlParser.AttributeContext ctx) {
}
@Override
public void exitAttribute(SoqlParser.AttributeContext ctx) {
}
@Override
public void enterTypeDef(SoqlParser.TypeDefContext ctx) {
typeDef = ctx.getChild(0).getText();
}
@Override
public void exitTypeDef(SoqlParser.TypeDefContext ctx) {
}
@Override
public void enterDistinct(SoqlParser.DistinctContext ctx) {
if (SoqlConstants.DISTINCT.equals(ctx.getChild(0).getText())) {
isSelectedParamDistinct = true;
}
}
@Override
public void exitDistinct(SoqlParser.DistinctContext ctx) {
}
@Override
public void enterWhereClauseWrapper(SoqlParser.WhereClauseWrapperContext ctx) {
}
@Override
public void exitWhereClauseWrapper(SoqlParser.WhereClauseWrapperContext ctx) {
}
@Override
public void enterConditionalExpression(SoqlParser.ConditionalExpressionContext ctx) {
}
@Override
public void exitConditionalExpression(SoqlParser.ConditionalExpressionContext ctx) {
}
@Override
public void enterConditionalTerm(SoqlParser.ConditionalTermContext ctx) {
}
@Override
public void exitConditionalTerm(SoqlParser.ConditionalTermContext ctx) {
final ParserRuleContext parentCtx = ctx.getParent();
if (parentCtx.getChildCount() > 1 && !parentCtx.getChild(0).equals(ctx)) {
objectOfNextOr.add(attrPointer);
}
}
@Override
public void enterConditionalFactor(SoqlParser.ConditionalFactorContext ctx) {
}
@Override
public void exitConditionalFactor(SoqlParser.ConditionalFactorContext ctx) {
if (ctx.getChildCount() > 1) {
attrPointer.setNot(true);
}
}
@Override
public void enterSimpleConditionalExpression(SoqlParser.SimpleConditionalExpressionContext ctx) {
}
@Override
public void exitSimpleConditionalExpression(SoqlParser.SimpleConditionalExpressionContext ctx) {
}
@Override
public void enterInExpression(SoqlParser.InExpressionContext ctx) {
}
@Override
public void exitInExpression(SoqlParser.InExpressionContext ctx) {
assert ctx.getChildCount() > 2;
if (isInObjectIdentifierExpression) {
pushNewAttribute(createSyntheticAttributeForEntityId());
}
final ParseTree value = resolveInExpressionValue(ctx);
if (ctx.getChild(1).getText().equals(SoqlConstants.NOT)) {
attrPointer.setOperator(InOperator.notIn());
} else {
attrPointer.setOperator(InOperator.in());
}
attrPointer.setValue(value.getText());
this.isInObjectIdentifierExpression = false;
}
private SoqlAttribute createSyntheticAttributeForEntityId() {
return new SoqlAttribute(
attrPointer.getFirstNode().hasChild() ? attrPointer.getFirstNode().getChild() :
new AttributeNode(rootVariable.substring(1)));
}
private ParseTree resolveInExpressionValue(SoqlParser.InExpressionContext ctx) {
final ParseTree lastToken = ctx.getChild(ctx.getChildCount() - 1);
if (")".equals(lastToken.getText())) {
return ctx.getChild(ctx.getChildCount() - 2);
}
return lastToken;
}
@Override
public void enterInItem(SoqlParser.InItemContext ctx) {
}
@Override
public void exitInItem(SoqlParser.InItemContext ctx) {
}
@Override
public void enterLiteral(SoqlParser.LiteralContext ctx) {
}
@Override
public void exitLiteral(SoqlParser.LiteralContext ctx) {
}
@Override
public void enterLikeExpression(SoqlParser.LikeExpressionContext ctx) {
}
@Override
public void exitLikeExpression(SoqlParser.LikeExpressionContext ctx) {
if (ctx.getChildCount() > 2 && ctx.getChild(1).getText().equals(SoqlConstants.NOT)) {
attrPointer.setOperator(LikeOperator.notLike());
ParseTree whereClauseValue = ctx.getChild(3);
attrPointer.setValue(whereClauseValue.getText());
} else {
attrPointer.setOperator(LikeOperator.like());
ParseTree whereClauseValue = ctx.getChild(2);
attrPointer.setValue(whereClauseValue.getText());
}
this.isInObjectIdentifierExpression = false;
}
@Override
public void enterMemberOfExpression(SoqlParser.MemberOfExpressionContext ctx) {
}
@Override
public void exitMemberOfExpression(SoqlParser.MemberOfExpressionContext ctx) {
if (ctx.getChildCount() > 2 && ctx.getChild(1).getText().equals(SoqlConstants.NOT)) {
attrPointer.setNot(true);
}
attrPointer.setOperator(MemberOfOperator.memberOf());
ParseTree whereClauseValue = ctx.getChild(0);
attrPointer.setValue(whereClauseValue.getText());
this.isInObjectIdentifierExpression = false;
}
@Override
public void enterComparisonExpression(SoqlParser.ComparisonExpressionContext ctx) {
}
@Override
public void exitComparisonExpression(SoqlParser.ComparisonExpressionContext ctx) {
String operator = ctx.getChild(1).getText();
ParseTree whereClauseValue = ctx.getChild(2);
if (isInObjectIdentifierExpression) {
assert Objects.equals(operator, "=");
if (attrPointer.isProjected()) {
this.rootVariable = SoqlUtils.soqlVariableToSparqlVariable(whereClauseValue.getText());
}
if (attributes.size() > 1 && !attrPointer.getFirstNode().getChild().hasChild()) {
final String varName = whereClauseValue.getText();
attrPointer.getFirstNode().getChild().setValue(
varName.charAt(0) == SoqlConstants.VARIABLE_PREFIX ? varName.substring(1) : varName);
}
} else {
attrPointer.setOperator(new ComparisonOperator(operator));
attrPointer.setValue(whereClauseValue.getText());
}
this.isInObjectIdentifierExpression = false;
}
@Override
public void enterTables(SoqlParser.TablesContext ctx) {
}
@Override
public void exitTables(SoqlParser.TablesContext ctx) {
}
@Override
public void enterTable(SoqlParser.TableContext ctx) {
}
@Override
public void exitTable(SoqlParser.TableContext ctx) {
}
@Override
public void enterTableName(SoqlParser.TableNameContext ctx) {
}
@Override
public void exitTableName(SoqlParser.TableNameContext ctx) {
}
@Override
public void enterTableWithName(SoqlParser.TableWithNameContext ctx) {
String table = ctx.getChild(0).getChild(0).getText();
String objectName = ctx.getChild(1).getChild(0).getText();
objectTypes.put(objectName, table);
SoqlNode node = new AttributeNode(table);
setObjectIri(node);
SoqlAttribute myAttr = new SoqlAttribute(node);
pushNewAttribute(myAttr);
}
@Override
public void exitTableWithName(SoqlParser.TableWithNameContext ctx) {
}
@Override
public void enterWhereClauseValue(SoqlParser.WhereClauseValueContext ctx) {
}
@Override
public void exitWhereClauseValue(SoqlParser.WhereClauseValueContext ctx) {
}
@Override
public void enterWhereClauseParam(SoqlParser.WhereClauseParamContext ctx) {
}
@Override
public void exitWhereClauseParam(SoqlParser.WhereClauseParamContext ctx) {
}
@Override
public void enterStringExpression(SoqlParser.StringExpressionContext ctx) {
}
@Override
public void exitStringExpression(SoqlParser.StringExpressionContext ctx) {
}
@Override
public void enterFunctionsReturningStrings(SoqlParser.FunctionsReturningStringsContext ctx) {
}
@Override
public void exitFunctionsReturningStrings(SoqlParser.FunctionsReturningStringsContext ctx) {
final String functionName = ctx.getChild(0).getText();
final FunctionNode node = new FunctionNode(attrPointer.getFirstNode(), functionName);
attrPointer.setFirstNode(node);
}
@Override
public void enterSimpleArithmeticExpression(SoqlParser.SimpleArithmeticExpressionContext ctx) {
}
@Override
public void exitSimpleArithmeticExpression(SoqlParser.SimpleArithmeticExpressionContext ctx) {
}
@Override
public void enterArithmeticTerm(SoqlParser.ArithmeticTermContext ctx) {
}
@Override
public void exitArithmeticTerm(SoqlParser.ArithmeticTermContext ctx) {
}
@Override
public void enterArithmeticFactor(SoqlParser.ArithmeticFactorContext ctx) {
}
@Override
public void exitArithmeticFactor(SoqlParser.ArithmeticFactorContext ctx) {
}
@Override
public void enterArithmeticPrimary(SoqlParser.ArithmeticPrimaryContext ctx) {
}
@Override
public void exitArithmeticPrimary(SoqlParser.ArithmeticPrimaryContext ctx) {
}
@Override
public void enterFunctionsReturningNumerics(SoqlParser.FunctionsReturningNumericsContext ctx) {
}
@Override
public void exitFunctionsReturningNumerics(SoqlParser.FunctionsReturningNumericsContext ctx) {
final String functionName = ctx.getChild(0).getText();
final FunctionNode node = new FunctionNode(attrPointer.getFirstNode(), functionName);
attrPointer.setFirstNode(node);
}
@Override
public void enterOrderByClause(SoqlParser.OrderByClauseContext ctx) {
}
@Override
public void exitOrderByClause(SoqlParser.OrderByClauseContext ctx) {
}
@Override
public void enterOrderByFullFormComma(SoqlParser.OrderByFullFormCommaContext ctx) {
}
@Override
public void exitOrderByFullFormComma(SoqlParser.OrderByFullFormCommaContext ctx) {
}
@Override
public void enterOrderByFullForm(SoqlParser.OrderByFullFormContext ctx) {
}
@Override
public void exitOrderByFullForm(SoqlParser.OrderByFullFormContext ctx) {
}
@Override
public void enterOrderByParam(SoqlParser.OrderByParamContext ctx) {
SoqlNode firstNode = linkContextNodes(ctx);
String orderingBy = getOrderingBy(ctx.getParent());
SoqlOrderParameter orderParam = new SoqlOrderParameter(firstNode, orderingBy);
boolean attrSet = false;
for (SoqlAttribute attr : attributes) {
if (attr.getAsParam().equals(orderParam.getAsParam())) {
orderParam.setAttribute(attr);
attrSet = true;
}
}
if (!attrSet) {
SoqlAttribute myAttr = new SoqlAttribute(firstNode);
myAttr.setValue(orderParam.getAsValue(rootVariable));
myAttr.setOrderBy(true);
attributes.add(1, myAttr);
orderParam.setAttribute(myAttr);
}
orderAttributes.add(orderParam);
}
@Override
public void exitOrderByParam(SoqlParser.OrderByParamContext ctx) {
}
@Override
public void enterGroupByClause(SoqlParser.GroupByClauseContext ctx) {
}
@Override
public void exitGroupByClause(SoqlParser.GroupByClauseContext ctx) {
}
@Override
public void enterGroupByParamComma(SoqlParser.GroupByParamCommaContext ctx) {
}
@Override
public void exitGroupByParamComma(SoqlParser.GroupByParamCommaContext ctx) {
}
@Override
public void enterGroupByParam(SoqlParser.GroupByParamContext ctx) {
SoqlNode firstNode = linkContextNodes(ctx);
SoqlGroupParameter groupParam = new SoqlGroupParameter(firstNode);
boolean attrSet = false;
for (SoqlAttribute attr : attributes) {
if (attr.getAsParam().equals(groupParam.getAsParam())) {
groupParam.setAttribute(attr);
attrSet = true;
}
}
if (!attrSet) {
SoqlAttribute myAttr = new SoqlAttribute(firstNode);
myAttr.setValue(groupParam.getAsValue(rootVariable));
myAttr.setGroupBy(true);
attributes.add(1, myAttr);
groupParam.setAttribute(myAttr);
}
groupAttributes.add(groupParam);
}
private SoqlNode linkContextNodes(ParserRuleContext ctx) {
SoqlNode firstNode = new AttributeNode(getOwnerFromParam(ctx));
SoqlNode currentNode = firstNode;
for (int i = 2; i < ctx.getChildCount(); i += 2) {
SoqlNode prevNode = currentNode;
currentNode = new AttributeNode(prevNode, ctx.getChild(i).getText());
prevNode.setChild(currentNode);
}
setIris(firstNode);
if (currentNode.getIri().isEmpty()) {
currentNode.getParent().setChild(null);
this.isInObjectIdentifierExpression = true;
}
return firstNode;
}
@Override
public void exitGroupByParam(SoqlParser.GroupByParamContext ctx) {
}
@Override
public void enterInputParameter(SoqlParser.InputParameterContext ctx) {
}
@Override
public void exitInputParameter(SoqlParser.InputParameterContext ctx) {
}
@Override
public void visitTerminal(TerminalNode terminalNode) {
}
@Override
public void visitErrorNode(ErrorNode errorNode) {
}
@Override
public void enterEveryRule(ParserRuleContext parserRuleContext) {
}
@Override
public void exitEveryRule(ParserRuleContext parserRuleContext) {
}
//Methods to help parse tree
private String getOwnerFromParam(ParserRuleContext ctx) {
return ctx.getChild(0).getChild(0).getText();
}
private String getAttributeFromParam(ParserRuleContext ctx) {
return ctx.getChild(2).getChild(0).getText();
}
private String getOrderingBy(ParserRuleContext ctx) {
return ctx.getChildCount() > 1 ? ctx.getChild(1).getText() : "";
}
private void setObjectIri(SoqlNode node) {
IdentifiableEntityType<?> entityType = getEntityType(node.getValue());
if (entityType == null) {
return;
}
node.setIri(entityType.getIRI().toString());
if (node.hasChild()) {
setAllNodesIris(entityType, node.getChild());
}
}
private IdentifiableEntityType<?> getEntityType(String name) {
for (EntityType<?> type : metamodel.getEntities()) {
IdentifiableEntityType<?> entityType = (IdentifiableEntityType<?>) type;
if (entityType.getName().equals(name)) {
return entityType;
}
}
return null;
}
private void setAllNodesIris(EntityType<?> entityType, SoqlNode node) {
final String nodeName = node.getValue();
if (entityType.getIdentifier().getName().equals(nodeName)) {
return;
}
final Attribute<?, ?> abstractAttribute = entityType.getAttribute(node.getValue());
if (abstractAttribute == null) {
if (entityType.getTypes() != null && entityType.getTypes().getName().equals(node.getValue())) {
node.setIri(SparqlConstants.RDF_TYPE_SHORTCUT);
return;
} else {
throw new SoqlException("No matching attribute with name '" + node.getValue() + "' found on entity type '" + entityType.getName() + "'.");
}
}
//not implemented case of 3 or more fragments (chained SoqlNodes)
node.setIri(abstractAttribute.getIRI().toString());
if (node.hasChild()) {
final Type<?> type = resolveBindableType(abstractAttribute);
if (type.getPersistenceType() != Type.PersistenceType.ENTITY) {
return;
}
setAllNodesIris((EntityType<?>) type, node.getChild());
}
}
private static Type<?> resolveBindableType(Attribute<?, ?> att) {
if (att.isCollection()) {
return ((PluralAttribute<?, ?, ?>) att).getElementType();
} else {
return ((SingularAttribute<?, ?>) att).getType();
}
}
private void setIris(SoqlNode firstNode) {
if (!objectTypes.containsKey(firstNode.getValue())) {
return;
}
String objectName = objectTypes.get(firstNode.getValue());
IdentifiableEntityType<?> entityType = getEntityType(objectName);
if (entityType == null) {
return;
}
if (firstNode.hasChild()) {
setAllNodesIris(entityType, firstNode.getChild());
}
}
public String getSparqlQuery() {
assert sparql != null;
return sparql;
}
//Methods to build new Query
private void buildSparqlQueryString() {
if (attributes.isEmpty()) {
return;
}
StringBuilder newQueryBuilder = new StringBuilder(typeDef);
if (isSelectedParamCount) {
newQueryBuilder.append(getCountPart());
} else {
if (isSelectedParamDistinct) {
newQueryBuilder.append(' ').append(SoqlConstants.DISTINCT);
}
newQueryBuilder.append(' ').append(rootVariable).append(' ');
}
newQueryBuilder.append("WHERE { ");
newQueryBuilder.append(processSupremeAttributes());
if (!objectOfNextOr.isEmpty()) {
newQueryBuilder.append("{ ");
}
newQueryBuilder.append(processAttributes());
if (!objectOfNextOr.isEmpty()) {
newQueryBuilder.append("} ");
}
newQueryBuilder.append('}');
if (!groupAttributes.isEmpty()) {
newQueryBuilder.append(' ').append(buildGrouping());
}
if (!orderAttributes.isEmpty()) {
newQueryBuilder.append(' ').append(buildOrdering());
}
sparql = newQueryBuilder.toString();
LOG.trace("Translated SOQL query '{}' to SPARQL '{}'.", soql, sparql);
}
private StringBuilder getCountPart() {
StringBuilder countPart = new StringBuilder(" (COUNT(");
if (isSelectedParamDistinct) {
countPart.append(SoqlConstants.DISTINCT).append(' ');
}
countPart.append(rootVariable).append(") AS ?count) ");
return countPart;
}
private StringBuilder processSupremeAttributes() {
StringBuilder attributesPart = new StringBuilder();
final Iterator<SoqlAttribute> it = attributes.iterator();
while (it.hasNext()) {
final SoqlAttribute current = it.next();
if (current.isInstanceOf() || current.isOrderBy() || current.isGroupBy()) {
attributesPart.append(processAttribute(current));
it.remove();
}
}
return attributesPart;
}
private StringBuilder processAttributes() {
StringBuilder attributesPart = new StringBuilder();
ArrayList<SoqlAttribute> toFilter = new ArrayList<>();
ArrayList<SoqlAttribute> toInvFilter = new ArrayList<>();
for (SoqlAttribute myAttr : attributes) {
if (objectOfNextOr.contains(myAttr)) {
StringBuilder orPart = new StringBuilder();
orPart.append(processAllFilters(toFilter, toInvFilter));
toFilter.clear();
toInvFilter.clear();
orPart.append("} UNION { ");
attributesPart.append(orPart);
}
if (myAttr.isNot()) {
toInvFilter.add(myAttr);
} else {
if (myAttr.requiresFilter()) {
toFilter.add(myAttr);
}
final String bgp = processAttribute(myAttr);
if (attributesPart.indexOf(bgp) == -1) {
attributesPart.append(bgp);
}
}
}
attributesPart.append(processAllFilters(toFilter, toInvFilter));
return attributesPart;
}
private StringBuilder processAllFilters(ArrayList<SoqlAttribute> toFilter, ArrayList<SoqlAttribute> toInvFilter) {
StringBuilder part = new StringBuilder();
if (!toFilter.isEmpty()) {
part.append(processFilter(toFilter));
}
if (!toInvFilter.isEmpty()) {
part.append(processInvFilter(toInvFilter));
}
return part;
}
private String processFilter(ArrayList<SoqlAttribute> toFilter) {
StringBuilder buildFilter = new StringBuilder();
if (toFilter.isEmpty()) {
return "";
}
buildFilter.append("FILTER (");
buildFilter.append(toFilter.stream().map(SoqlAttribute::getFilterExpressions).flatMap(Collection::stream)
.collect(Collectors.joining(" && ")));
buildFilter.append(") ");
return buildFilter.toString();
}
private String processInvFilter(ArrayList<SoqlAttribute> toInvFilter) {
StringBuilder buildInvFilter = new StringBuilder();
ArrayList<SoqlAttribute> toFilter = new ArrayList<>();
if (toInvFilter.isEmpty()) {
return "";
}
buildInvFilter.append("FILTER NOT EXISTS { ");
for (SoqlAttribute attr : toInvFilter) {
buildInvFilter.append(processAttribute(attr));
if (attr.requiresFilter()) {
toFilter.add(attr);
}
}
buildInvFilter.append(processFilter(toFilter)).append("} ");
return buildInvFilter.toString();
}
private String processAttribute(SoqlAttribute attr) {
return attr.getBasicGraphPattern(rootVariable);
}
private String buildOrdering() {
StringBuilder sb = new StringBuilder(SoqlConstants.ORDER_BY);
for (SoqlOrderParameter orderParam : orderAttributes) {
sb.append(' ').append(orderParam.getOrderByPart());
}
return sb.toString();
}
private String buildGrouping() {
StringBuilder sb = new StringBuilder(SoqlConstants.GROUP_BY);
for (SoqlGroupParameter groupParam : groupAttributes) {
sb.append(' ').append(groupParam.getGroupByPart());
}
return sb.toString();
}
}