/
ASTDeferredIVResolution.java
1279 lines (1046 loc) · 51.2 KB
/
ASTDeferredIVResolution.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
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
package com.bigdata.rdf.sparql.ast.eval;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.log4j.Logger;
import org.openrdf.model.Literal;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.query.Binding;
import org.openrdf.query.BindingSet;
import org.openrdf.query.Dataset;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.algebra.StatementPattern.Scope;
import org.openrdf.query.algebra.evaluation.QueryBindingSet;
import org.openrdf.query.impl.DatasetImpl;
import org.openrdf.query.impl.MapBindingSet;
import com.bigdata.bop.BOp;
import com.bigdata.bop.BOpBase;
import com.bigdata.bop.Constant;
import com.bigdata.bop.IBindingSet;
import com.bigdata.bop.IConstant;
import com.bigdata.bop.IValueExpression;
import com.bigdata.bop.IVariable;
import com.bigdata.rdf.internal.DTE;
import com.bigdata.rdf.internal.IV;
import com.bigdata.rdf.internal.VTE;
import com.bigdata.rdf.internal.constraints.IVValueExpression;
import com.bigdata.rdf.internal.impl.AbstractIV;
import com.bigdata.rdf.internal.impl.TermId;
import com.bigdata.rdf.model.BigdataStatement;
import com.bigdata.rdf.model.BigdataURI;
import com.bigdata.rdf.model.BigdataValue;
import com.bigdata.rdf.model.BigdataValueFactory;
import com.bigdata.rdf.sail.sparql.ast.ASTDatasetClause;
import com.bigdata.rdf.sail.sparql.ast.ASTIRI;
import com.bigdata.rdf.sail.sparql.ast.ASTQueryContainer;
import com.bigdata.rdf.sparql.ast.ASTContainer;
import com.bigdata.rdf.sparql.ast.ASTContainer.Annotations;
import com.bigdata.rdf.sparql.ast.AbstractFromToGraphManagement;
import com.bigdata.rdf.sparql.ast.AbstractGraphDataUpdate;
import com.bigdata.rdf.sparql.ast.AbstractOneGraphManagement;
import com.bigdata.rdf.sparql.ast.BindingsClause;
import com.bigdata.rdf.sparql.ast.ConstantNode;
import com.bigdata.rdf.sparql.ast.DatasetNode;
import com.bigdata.rdf.sparql.ast.DeleteInsertGraph;
import com.bigdata.rdf.sparql.ast.FilterNode;
import com.bigdata.rdf.sparql.ast.FunctionNode;
import com.bigdata.rdf.sparql.ast.GroupByNode;
import com.bigdata.rdf.sparql.ast.GroupNodeBase;
import com.bigdata.rdf.sparql.ast.HavingNode;
import com.bigdata.rdf.sparql.ast.IDataSetNode;
import com.bigdata.rdf.sparql.ast.IGroupMemberNode;
import com.bigdata.rdf.sparql.ast.NamedSubqueriesNode;
import com.bigdata.rdf.sparql.ast.NamedSubqueryRoot;
import com.bigdata.rdf.sparql.ast.PathNode;
import com.bigdata.rdf.sparql.ast.PathNode.PathAlternative;
import com.bigdata.rdf.sparql.ast.ProjectionNode;
import com.bigdata.rdf.sparql.ast.QuadsDataOrNamedSolutionSet;
import com.bigdata.rdf.sparql.ast.QuadsOperationInTriplesModeException;
import com.bigdata.rdf.sparql.ast.QueryBase;
import com.bigdata.rdf.sparql.ast.QueryNodeBase;
import com.bigdata.rdf.sparql.ast.QueryNodeWithBindingSet;
import com.bigdata.rdf.sparql.ast.QueryRoot;
import com.bigdata.rdf.sparql.ast.StatementPatternNode;
import com.bigdata.rdf.sparql.ast.SubqueryFunctionNodeBase;
import com.bigdata.rdf.sparql.ast.TermNode;
import com.bigdata.rdf.sparql.ast.Update;
import com.bigdata.rdf.sparql.ast.UpdateRoot;
import com.bigdata.rdf.sparql.ast.ValueExpressionNode;
import com.bigdata.rdf.sparql.ast.optimizers.ASTSetValueExpressionsOptimizer;
import com.bigdata.rdf.sparql.ast.service.ServiceNode;
import com.bigdata.rdf.spo.ISPO;
import com.bigdata.rdf.store.AbstractTripleStore;
import com.bigdata.rdf.store.BD;
import com.bigdata.relation.accesspath.IAccessPath;
/**
* This class provides batch resolution of internal values, which were left
* unresolved during query/update preparation. Values, which are processed: any
* BOp arguments, ValueExpressions, and specific values stored in annotations
* (for example, SERVICE_REF in ServiceNode).
* <p>
* Class performs efficient batch resolution of RDF Values against the database
* during query preparation. This efficiency is important on a cluster and when
* a SPARQL query or update contains a large number of RDF Values.
*
* @author igor.kim
*
* @see https://jira.blazegraph.com/browse/BLZG-1176
*/
@SuppressWarnings( { "rawtypes", "unchecked" } )
public class ASTDeferredIVResolution {
private final static Logger log = Logger
.getLogger(ASTDeferredIVResolution.class);
/**
* Anonymous instances of Handler interface are used as a deferred code,
* which should be run after particular IV is available in batch resolution results
*/
private interface Handler {
void handle(IV newIV);
}
// /**
// * The target triple store.
// */
// private final AbstractTripleStore store;
/**
* The value factory for that target triple store.
*/
private final BigdataValueFactory vf;
/**
* Deferred handlers, linked to particular BigdataValue resolution
*/
private final Map<BigdataValue, List<Handler>> deferred = new LinkedHashMap<>();
/**
* Deferred handlers, NOT linked to particular BigdataValue resolution, used
* to provide sets of resolved default and named graphs into DataSetSummary
* constructor
*/
private final List<Runnable> deferredRunnables = new ArrayList<>();
/**
* IVs of graphs, which will be later passed to
* {@link #resolveDataset(AST2BOpContext, Map)}.
*
* No need for synchronization or keeping order of values.
*/
private final Map<Value, IV> resolvedValues = new HashMap<>();
private ASTDeferredIVResolution(AbstractTripleStore store) {
if (store == null)
throw new IllegalArgumentException();
// this.store = store;
this.vf = store.getValueFactory();
}
static class DeferredResolutionResult {
BindingSet bindingSet;
Dataset dataset;
public DeferredResolutionResult(final BindingSet bindingSet, final Dataset dataset) {
this.bindingSet = bindingSet;
this.dataset = dataset;
}
}
/**
* Do deferred resolution of IVs, which were left unresolved while preparing
* the query
*
* @param store
* - triple store, which will be used for values resolution
* @param ast
* - AST model of the query, which should be resolved
* @throws MalformedQueryException
*/
public static DeferredResolutionResult resolveQuery(final AbstractTripleStore store, final ASTContainer ast) throws MalformedQueryException {
return resolveQuery(store, ast, null, null, null /* context unknown */);
}
/**
* Do deferred resolution of IVs, which were left unresolved while preparing
* the query
*
* @param store
* - triple store, which will be used for values resolution
* @param ast
* - AST model of the query, which should be resolved
* @param bs
* - binding set, which should be resolved
* @param dataset
* @throws MalformedQueryException
*/
public static DeferredResolutionResult resolveQuery(
final AbstractTripleStore store, final ASTContainer ast,
final BindingSet bs, final Dataset dataset, final AST2BOpContext ctxIn) throws MalformedQueryException {
// whenever a context is provided, use that one, otherwise construct it
final AST2BOpContext ctx = ctxIn==null ? new AST2BOpContext(ast, store) : ctxIn;
final ASTDeferredIVResolution termsResolver = new ASTDeferredIVResolution(store);
// process provided binding set
final BindingSet resolvedBindingset = termsResolver.handleBindingSet(store, bs);
// process provided dataset
final Dataset resolvedDataset = termsResolver.handleDataset(store, dataset);
/*
* Prevent running IV resolution more than once.
* Property RESOLVED is set after resolution completed,
* so subsequent repetitive calls to query evaluate
* (for example with different bindings) would not result
* in running resolution again.
*/
if (Boolean.TRUE.equals(ast.getProperty(Annotations.RESOLVED))) {
/*
* Resolve binding set or dataset if there are any values to be processed
*/
if (!termsResolver.deferred.isEmpty()) {
termsResolver.resolveIVs(store);
}
// fast path for pre-resolved query.
return new DeferredResolutionResult(resolvedBindingset, resolvedDataset);
}
final long beginNanos = System.nanoTime();
final QueryRoot queryRoot = (QueryRoot)ast.getProperty(Annotations.ORIGINAL_AST);
/*
* Handle dataset declaration
*
* Note: Filters can be attached in order to impose ACLs on the
* query. This has to be done at the application layer at this
* point, but it might be possible to extend the grammar for this.
* The SPARQL end point would have to be protected from external
* access if this were done. Perhaps the better way to do this is to
* have the NanoSparqlServer impose the ACL filters. There also
* needs to be an authenticated identity to make this work and that
* could be done via an integration within the NanoSparqlServer web
* application container.
*
* Note: This handles VIRTUAL GRAPH resolution.
*/
final Map<IDataSetNode, List<ASTDatasetClause>> dcLists = new LinkedHashMap<>();
{
final ASTQueryContainer qc = (ASTQueryContainer) ast.getProperty(Annotations.PARSE_TREE);
if (qc != null && qc.getOperation() != null) {
final List<ASTDatasetClause> dcList = new ArrayList<>();
dcList.addAll(qc.getOperation().getDatasetClauseList());
dcLists.put(queryRoot, dcList);
}
}
/*
* I think here we could set the value expressions and do last- minute
* validation.
*/
final ASTSetValueExpressionsOptimizer opt = new ASTSetValueExpressionsOptimizer();
final QueryRoot queryRoot2 = (QueryRoot) opt.optimize(ctx, new QueryNodeWithBindingSet(queryRoot, null)).getQueryNode();
termsResolver.resolve(store, queryRoot2, dcLists, bs);
queryRoot2.setPrefixDecls(ast.getOriginalAST().getPrefixDecls());
ast.setOriginalAST(queryRoot2);
ast.setResolveValuesTime(System.nanoTime() - beginNanos);
ast.setProperty(Annotations.RESOLVED, Boolean.TRUE);
// Note: Full recursive traversal can be used to inspect post-condition of all bops.
// if(true) {
// final Iterator<BOp> itr = BOpUtility.preOrderIteratorWithAnnotations(ast);
// while(itr.hasNext()) {
// final BOp bop = itr.next();
// log.error("bop="+bop);
// }
// }
return new DeferredResolutionResult(resolvedBindingset, resolvedDataset);
}
/**
* Do deferred resolution of IVs, which were left unresolved while preparing the update
* @param store - triple store, which will be used for values resolution
* @param ast - AST model of the update, which should be resolved
* @throws MalformedQueryException
*/
public static DeferredResolutionResult resolveUpdate(final AbstractTripleStore store, final ASTContainer ast) throws MalformedQueryException {
return resolveUpdate(store, ast, null, null);
}
/**
* Do deferred resolution of IVs, which were left unresolved while preparing the update
* @param store - triple store, which will be used for values resolution
* @param ast - AST model of the update, which should be resolved
* @param bs - binding set, which should be resolved
* @param dataset
* @return
* @throws MalformedQueryException
*/
public static DeferredResolutionResult resolveUpdate(final AbstractTripleStore store, final ASTContainer ast, final BindingSet bs, final Dataset dataset) throws MalformedQueryException {
final ASTDeferredIVResolution termsResolver = new ASTDeferredIVResolution(store);
// process provided binding set
BindingSet resolvedBindingSet = termsResolver.handleBindingSet(store, bs);
// process provided dataset
final Dataset resolvedDataset = termsResolver.handleDataset(store, dataset);
/*
* Prevent running IV resolution more than once.
* Property RESOLVED is set after resolution completed,
* so subsequent repetitive calls to update execute
* (for example with different bindings) would not result
* in running resolution again.
*/
if (Boolean.TRUE.equals(ast.getProperty(Annotations.RESOLVED))) {
/*
* Resolve binding set or dataset if there are any values to be processed
*/
if (!termsResolver.deferred.isEmpty()) {
termsResolver.resolveIVs(store);
}
return new DeferredResolutionResult(resolvedBindingSet, resolvedDataset);
}
final long beginNanos = System.nanoTime();
final UpdateRoot qc = (UpdateRoot)ast.getProperty(Annotations.ORIGINAL_AST);
/*
* Handle dataset declaration. It only appears for DELETE/INSERT
* (aka ASTModify). It is attached to each DeleteInsertNode for
* which it is given.
*/
final Map<IDataSetNode, List<ASTDatasetClause>> dcLists = new LinkedHashMap<>();
for (final Update update: qc.getChildren()) {
if (update instanceof IDataSetNode) {
final List<ASTDatasetClause> dcList = new ArrayList();
dcList.addAll(update.getDatasetClauses());
dcLists.put((IDataSetNode)update, dcList);
}
}
termsResolver.resolve(store, qc, dcLists, bs);
if (ast.getOriginalUpdateAST().getPrefixDecls()!=null && !ast.getOriginalUpdateAST().getPrefixDecls().isEmpty()) {
qc.setPrefixDecls(ast.getOriginalUpdateAST().getPrefixDecls());
}
ast.setOriginalUpdateAST(qc);
ast.setResolveValuesTime(System.nanoTime() - beginNanos);
ast.setProperty(Annotations.RESOLVED, Boolean.TRUE);
return new DeferredResolutionResult(resolvedBindingSet, resolvedDataset);
}
/**
* Do deferred resolution of IVs, which were left unresolved after execution of each Update in UpdateRoot
* @param store - triple store, which will be used for values resolution
* @param ast - AST model of the update, which should be resolved
* @param bs - binding set, which should be resolved
* @param dataset
* @return
* @throws MalformedQueryException
*/
public static DeferredResolutionResult resolveUpdate(final AbstractTripleStore store, final Update update, final BindingSet bs, final Dataset dataset) throws MalformedQueryException {
final ASTDeferredIVResolution termsResolver = new ASTDeferredIVResolution(store);
// process provided binding set
BindingSet resolvedBindingSet = termsResolver.handleBindingSet(store, bs);
// process provided dataset
final Dataset resolvedDataset = termsResolver.handleDataset(store, dataset);
// final long beginNanos = System.nanoTime();
termsResolver.resolve(store, update, null/*datasetClauseLists*/, bs);
// ast.setResolveValuesTime(System.nanoTime() - beginNanos);
return new DeferredResolutionResult(resolvedBindingSet, resolvedDataset);
}
/**
* Schedule resolution if IV in provided value, provided handler will be
* used to process resolved IV. If provided BigdataValue was created using
* BigdataValueFactory bound to triple store, and has real IV already
* resolved (for example dataset definition), handler will be fired
* immediately and no value will be queued for resolution.
*
* @param value
* @param handler
*/
private void defer(final BigdataValue value, final Handler handler) {
if (value == null)
return;
if (value.getValueFactory() == vf && value.isRealIV()) {
/*
* We have a BigdataValue that belongs to the correct namespace and
* which has already been resolved to a real IV.
*/
if (value.getIV().needsMaterialization()) {
value.getIV().setValue(value);
}
handler.handle(value.getIV());
return;
}
List<Handler> handlers = deferred.get(value);
if (handlers == null) {
handlers = new ArrayList<>();
deferred.put(value, handlers);
}
handlers.add(handler);
}
/**
* Schedule execution of runnable after batch resolution if IVs (to handle
* creation of DataSetSummary instances for default and named graphs
* collections)
*
* @param runnable
*/
private void deferRunnable(final Runnable runnable) {
deferredRunnables.add(runnable);
}
/**
* Prepare and execute batch resolution of IVs in provided queryNode
* @param bs
* @param dcList
* @throws MalformedQueryException
*/
private void resolve(final AbstractTripleStore store, final QueryNodeBase queryNode, final Map<IDataSetNode, List<ASTDatasetClause>> dcLists, final BindingSet bs) throws MalformedQueryException {
// prepare deferred handlers for batch IVs resolution
prepare(store, queryNode);
// Assign DataSetNode to each IDataSetNode (sets up handlers that are
// then invoked by call backs).
resolveDataset(store, dcLists);
// execute batch resolution and run all deferred handlers,
// which will update unresolved values across AST model
resolveIVs(store);
}
/**
* Method is invoked after IV resolution and sets the
* {@link IDataSetNode#setDataset(DatasetNode) data set} on each
* {@link IDataSetNode} to a newly constructed {@link DatasetNode}
* object.
*
* @param context
* @param dcLists
* A mapping from the {@link IDataSetNode} objects to the set of
* {@link ASTDatasetClause data set declarations clauses} (there
* can be more than one for SPARQL UPDATE).
*
* @throws MalformedQueryException
*/
private void resolveDataset(final AbstractTripleStore store, final Map<IDataSetNode, List<ASTDatasetClause>> dcLists) throws MalformedQueryException {
if (dcLists == null) {
return;
}
for (final Entry<IDataSetNode, List<ASTDatasetClause>> dcList: dcLists.entrySet()) {
final boolean update = dcList.getKey() instanceof Update;
final List<ASTDatasetClause> datasetClauses = dcList.getValue();
if (datasetClauses != null && !datasetClauses.isEmpty()) {
if (!store.isQuads()) {
throw new QuadsOperationInTriplesModeException(
"NAMED clauses in queries are not supported in" + " triples mode.");
}
/*
* Lazily instantiated sets for the default and named graphs.
*/
final Set<IV<?,?>> defaultGraphs = new LinkedHashSet<>();
final Set<IV<?,?>> namedGraphs = new LinkedHashSet<>();
for (final ASTDatasetClause dc : datasetClauses) {
final ASTIRI astIri = dc.jjtGetChild(ASTIRI.class);
// Setup the callback handler : TODO Pull handler into a private class? Questions about scope for defaultGraphs and namedGraphs.
defer((BigdataURI) astIri.getRDFValue(), new Handler() {
@Override
public void handle(final IV newIV) {
final BigdataValue uri = newIV.getValue();
if (dc.isVirtual()) {
if (uri.getIV().isNullIV()) {
/*
* A virtual graph was referenced which is not
* declared in the database. This virtual graph will
* not have any members.
*/
throw new RuntimeException("Not declared: " + uri);
}
final IV virtualGraph = resolvedValues.get(BD.VIRTUAL_GRAPH);
if (virtualGraph == null) {
throw new RuntimeException("Not declared: "
+ BD.VIRTUAL_GRAPH);
}
final IAccessPath<ISPO> ap = store
.getSPORelation()
.getAccessPath(//
uri.getIV(),// the virtual graph "name"
virtualGraph, null/* o */, null/* c */);
final Iterator<ISPO> itr = ap.iterator();
while(itr.hasNext()) {
final IV memberGraph = itr.next().o();
final BigdataValue value = store.getLexiconRelation().getTerm(memberGraph);
memberGraph.setValue(value);
if (dc.isNamed()) {
namedGraphs.add(memberGraph);
} else {
defaultGraphs.add(memberGraph);
}
}
} else {
if (uri.getIV() != null) {
if (dc.isNamed()) {
namedGraphs.add(uri.getIV());
} else {
defaultGraphs.add(uri.getIV());
}
}
}
}
});
deferRunnable(new Runnable(){
public void run() {
if (!defaultGraphs.isEmpty() || !namedGraphs.isEmpty()) {
// Note: Cast required to shut up the compiler.
final DatasetNode datasetNode = new DatasetNode((Set) defaultGraphs, (Set) namedGraphs,
update);
/*
* Set the data set on the QueryRoot or
* DeleteInsertGraph node.
*/
dcList.getKey().setDataset(datasetNode);
}
}
});
}
}
}
}
/**
* prepare deferred handlers for batch IVs resolution. the handlers will go back
* and put the IVs into place afterwards.
*
* @param context
* @param queryNode
* @param dcList
*/
private void prepare(final AbstractTripleStore store, final QueryNodeBase queryNode) {
if (queryNode instanceof QueryRoot) {
fillInIV(store, ((QueryRoot)queryNode).getDataset());
}
if (queryNode instanceof UpdateRoot) {
final UpdateRoot updateRoot = (UpdateRoot) queryNode;
fillInIV(store, updateRoot);
} else if (queryNode instanceof Update) {
final Update update = (Update) queryNode;
fillInIV(store, update);
} else if (queryNode instanceof QueryBase) {
final QueryBase queryRoot = (QueryBase) queryNode;
// SELECT clause
{
final ProjectionNode projection = queryRoot.getProjection();
if (projection!=null) {
fillInIV(store, projection);
}
}
// Main CONSTRUCT clause
{
final GroupNodeBase constructClause = queryRoot.getConstruct();
if (constructClause != null) {
fillInIV(store, constructClause);
}
}
// Main WHERE clause
{
final GroupNodeBase<IGroupMemberNode> whereClause = queryRoot
.getWhereClause();
if (whereClause != null) {
fillInIV(store, whereClause);
}
}
// GROUP BY clause
{
final GroupByNode groupBy = queryRoot.getGroupBy();
if (groupBy != null) {
fillInIV(store, groupBy);
}
}
// HAVING clause
{
final HavingNode having = queryRoot.getHaving();
if (having != null) {
fillInIV(store, having);
}
}
// BINDINGS clause
{
final BindingsClause bc = queryRoot.getBindingsClause();
if (bc!=null) {
for (final IBindingSet bs: bc.getBindingSets()) {
handleBindingSet(store, bs);
}
}
}
// Named subqueries
if (queryRoot instanceof QueryRoot && ((QueryRoot)queryRoot).getNamedSubqueries() != null) {
final NamedSubqueriesNode namedSubqueries = ((QueryRoot)queryRoot)
.getNamedSubqueries();
/*
* Note: This loop uses the current size() and get(i) to avoid
* problems with concurrent modification during visitation.
*/
for (int i = 0; i < namedSubqueries.size(); i++) {
final NamedSubqueryRoot namedSubquery = (NamedSubqueryRoot) namedSubqueries
.get(i);
// process subquery recursively, handling all the clauses of the subquery
// @see https://jira.blazegraph.com/browse/BLZG-1682
prepare(store, namedSubquery);
}
}
}
}
private void handleBindingSet(final AbstractTripleStore store, final IBindingSet s) {
final Iterator<Entry<IVariable, IConstant>> itr = s.iterator();
while (itr.hasNext()) {
final Entry<IVariable, IConstant> entry = itr.next();
final Object value = entry.getValue().get();
if (value instanceof BigdataValue) {
defer((BigdataValue)value, new Handler(){
@Override
public void handle(final IV newIV) {
entry.setValue(new Constant(newIV));
}
});
} else if (value instanceof AbstractIV) {
// See BLZG-1788 (Typed literals in VALUES clause not matching data)
// Changed from TermId to AbstractIV, as there are other types of IVs,
// which could require resolution against the store
// (for ex. FullyInlineTypedLiteralIV which represents typed literal)
defer(((AbstractIV)value).getValue(), new Handler(){
@Override
public void handle(final IV newIV) {
entry.setValue(new Constant(newIV));
}
});
}
}
}
private BindingSet handleBindingSet(final AbstractTripleStore store, final BindingSet bs) {
if (bs != null) {
MapBindingSet newBs = new MapBindingSet();
for (Binding entry: bs) {
Value value = entry.getValue();
if (!(value instanceof BigdataValue)) {
if (bs instanceof QueryBindingSet) {
BigdataValue bValue = store.getValueFactory().asValue(value);
// bValue.setIV(TermId.mockIV(VTE.valueOf(bValue)));
// bValue.getIV().setValue(bValue);
value = bValue;
}
}
if (value instanceof BigdataValue && !((BigdataValue) value).isRealIV()) {
final BigdataValue bValue = (BigdataValue) value;
defer((BigdataValue)value, new Handler(){
@Override
public void handle(final IV newIV) {
bValue.setIV(newIV);
}
});
}
newBs.addBinding(entry.getName(), value);
}
return newBs;
}
return bs;
}
private Dataset handleDataset(final AbstractTripleStore store, final Dataset dataset) {
if (dataset != null) {
DatasetImpl newDataset = new DatasetImpl();
for (final URI uri: dataset.getDefaultGraphs()) {
URI value = handleDatasetGraph(store, uri);
newDataset.addDefaultGraph(value);
}
for (final URI uri: dataset.getDefaultRemoveGraphs()) {
URI value = handleDatasetGraph(store, uri);
newDataset.addDefaultRemoveGraph(value);
}
for (final URI uri: dataset.getNamedGraphs()) {
URI value = handleDatasetGraph(store, uri);
newDataset.addNamedGraph(value);
}
URI value = handleDatasetGraph(store, dataset.getDefaultInsertGraph());
newDataset.setDefaultInsertGraph(value);
return newDataset;
}
return dataset;
}
private URI handleDatasetGraph(final AbstractTripleStore store, final URI uri) {
URI value = uri;
if (value!= null && !(value instanceof BigdataValue)) {
value = store.getValueFactory().asValue(value);
}
if (value instanceof BigdataValue) {
final BigdataValue bValue = (BigdataValue) value;
defer((BigdataValue)value, new Handler(){
@Override
public void handle(final IV newIV) {
bValue.setIV(newIV);
}
});
}
return value;
}
/**
* Transitively handles all unresolved IVs inside provided bop
*/
private void fillInIV(final AbstractTripleStore store, final BOp bop) {
if (bop == null) {
return;
}
if (bop instanceof ConstantNode) {
final BigdataValue value = ((ConstantNode) bop).getValue();
if (value != null) {
/*
* Even if iv is already filled in we should try to resolve it
* against triplestore, as previously resolved IV may be
* inlined, but expected to be term from lexicon relation on
* evaluation.
*/
defer(value, new Handler(){
@Override
public void handle(final IV newIV) {
((ConstantNode) bop).setArg(0, new Constant(newIV));
}
});
}
return;
}
for (int k = 0; k < bop.arity(); k++) {
final BOp pathBop = bop.get(k);
if (pathBop instanceof Constant) {
final Object v = ((Constant)pathBop).get();
final int fk = k;
if (v instanceof BigdataValue) {
defer((BigdataValue)v, new Handler(){
@Override
public void handle(final IV newIV) {
bop.args().set(fk, new Constant(newIV));
}
});
} else if (v instanceof TermId) {
defer(((TermId)v).getValue(), new Handler(){
@Override
public void handle(final IV newIV) {
if (bop instanceof BOpBase) {
((BOpBase)bop).__replaceArg(fk, new Constant(newIV));
} else {
List<BOp> args = bop.args();
if (args instanceof ArrayList) {
args.set(fk, new Constant(newIV));
} else {
log.warn("bop.args() class " + args.getClass() + " or " + bop.getClass() + " does not allow updates");
}
}
}
});
}
} else {
fillInIV(store,pathBop);
}
}
if (bop instanceof AbstractOneGraphManagement) {
fillInIV(store,((AbstractOneGraphManagement)bop).getTargetGraph());
} if (bop instanceof AbstractFromToGraphManagement) {
fillInIV(store, ((AbstractFromToGraphManagement)bop).getSourceGraph());
fillInIV(store, ((AbstractFromToGraphManagement)bop).getTargetGraph());
} if (bop instanceof AbstractGraphDataUpdate) {
final AbstractGraphDataUpdate update = ((AbstractGraphDataUpdate)bop);
// @see https://jira.blazegraph.com/browse/BLZG-1176
// Check for using context value in DATA block with triple store not supporting quads
// Moved from com.bigdata.rdf.sail.sparql.UpdateExprBuilder.doUnparsedQuadsDataBlock(ASTUpdate, Object, boolean, boolean)
if (!store.isQuads()) {
for (final BigdataStatement sp: update.getData()) {
if (sp.getContext()!=null) {
throw new QuadsOperationInTriplesModeException(
"Quads in SPARQL update data block are not supported " +
"in triples mode.");
}
}
}
} if (bop instanceof DeleteInsertGraph) {
fillInIV(store, ((DeleteInsertGraph)bop).getDataset());
fillInIV(store, ((DeleteInsertGraph)bop).getDeleteClause());
fillInIV(store, ((DeleteInsertGraph)bop).getInsertClause());
fillInIV(store, ((DeleteInsertGraph)bop).getWhereClause());
} else if (bop instanceof QuadsDataOrNamedSolutionSet) {
fillInIV(store, ((QuadsDataOrNamedSolutionSet)bop).getQuadData());
} else if (bop instanceof DatasetNode) {
final DatasetNode dataset = ((DatasetNode) bop);
final Set<IV> newDefaultGraphs = new LinkedHashSet<IV>();
for(final IV iv: dataset.getDefaultGraphs().getGraphs()) {
defer(iv.getValue(), new Handler(){
@Override
public void handle(final IV newIV) {
newDefaultGraphs.add(newIV);
}
});
}
deferRunnable(new Runnable(){
@Override
public void run() {
dataset.setDefaultGraphs(new DataSetSummary(newDefaultGraphs, true));
}
});
final Set<IV> newNamedGraphs = new LinkedHashSet<IV>();
final Iterator<IV> namedGraphs = dataset.getNamedGraphs().getGraphs().iterator();
while(namedGraphs.hasNext()) {
final IV iv = namedGraphs.next();
defer(iv.getValue(), new Handler(){
@Override
public void handle(final IV newIV) {
newNamedGraphs.add(newIV);
}
});
}
deferRunnable(new Runnable(){
@Override
public void run() {
dataset.setNamedGraphs(new DataSetSummary(newNamedGraphs, true));
}
});
} else if (bop instanceof PathNode) {
final PathAlternative path = ((PathNode) bop).getPathAlternative();
for (int k = 0; k < path.arity(); k++) {
final BOp pathBop = path.get(k);
fillInIV(store,pathBop);
}
} else if (bop instanceof FunctionNode) {
if (bop instanceof SubqueryFunctionNodeBase) {
fillInIV(store, ((SubqueryFunctionNodeBase)bop).getGraphPattern());
}
final IValueExpression<? extends IV> fve = ((FunctionNode)bop).getValueExpression();
if (fve instanceof IVValueExpression) {
for (int k = 0; k < fve.arity(); k++) {
final BOp veBop = fve.get(k);
// https://jira.blazegraph.com/browse/BLZG-2091 (Regression: IF + BOUND produce exception in 2.1.4)
// any constant IV with set value should be resolved against target store,
// but those IVs, which do not have materialized value, do not require resolution
// https://github.com/blazegraph/database/pull/23#issuecomment-261355901
// fix failing TestTicket1747: not materialized IVs do not require resolution
if (veBop instanceof Constant && ((Constant)veBop).get() instanceof IV &&
((IV) ((Constant)veBop).get()).hasValue()) {
final BigdataValue v = ((IV) ((Constant)veBop).get()).getValue();
final int fk = k;
defer(v, new Handler(){
@Override
public void handle(final IV newIV) {
final BigdataValue resolved = vf.asValue(v);
if (resolved.getIV() == null && newIV!=null) {
resolved.setIV(newIV);
newIV.setValue(resolved);
final Constant newConstant = new Constant(newIV);
// we need to reread value expression from the node, as it might get changed by sibling nodes resolution
// @see https://jira.blazegraph.com/browse/BLZG-1682
final IValueExpression<? extends IV> fve = ((ValueExpressionNode)bop).getValueExpression();
IValueExpression<? extends IV> newVe = (IValueExpression<? extends IV>) ((IVValueExpression) fve).setArg(fk, newConstant);