-
Notifications
You must be signed in to change notification settings - Fork 3
/
sparqlhelper.js
798 lines (681 loc) · 14.8 KB
/
sparqlhelper.js
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
/*
* copyright: IBM Confidential
* copyright: OCO Source Materials
* copyright: © IBM Corp. All Rights Reserved
* date: 2020
*
* IBM Certificate of Originality
*/
"use strict";
const { NamedNode } = require("n3");
const SparqlJS = require("sparqljs");
const BOOLEAN_XSD_URI = "http://www.w3.org/2001/XMLSchema#boolean";
const HKUris = require("./hk");
/**
* @deprecated after https://github.com/RubenVerborgh/SPARQL.js/issues/92 get fixed.
*/
function traverseValues(values, out)
{
for(let k in values)
{
let entry = values[k]
for(let j in entry)
{
let v = entry[j];
if(v.termType === "Literal") // Workaround to this bug: https://github.com/RubenVerborgh/SPARQL.js/issues/92
{
if(v.datatypeString === BOOLEAN_XSD_URI)
{
entry[j] = new v.constructor(`"${v.value.toLowerCase()}"^^${v.datatypeString}`);
}
}
}
}
}
function traverseBGP(triples, out, state)
{
for(let i = 0; i < triples.length; i++)
{
let t = triples[i];
if(!state.skipBgp)
{
if(t.subject.termType === "Variable")
{
out.subjects.add(t.subject.value)
}
if(t.predicate.termType === "Variable")
{
out.predicates.add(t.predicate.value)
}
if(t.object.termType === "Variable")
{
out.objects.add(t.object.value);
}
}
// if(t.object.termType === "Literal") // Workaround to this bug: https://github.com/RubenVerborgh/SPARQL.js/issues/92
// {
// if(t.object.datatypeString === BOOLEAN_XSD_URI)
// {
// t.object = new t.object.constructor(`"${t.object.value.toLowerCase()}"^^${t.object.datatypeString}`);
// }
// }
}
}
function traverseOperation(operation, out)
{
for(let i = 0; i < operation.args.length; i++)
{
let o = operation.args[i];
// if(o.termType)
// {
// if(o.termType === "Literal")
// {
// if(o.datatypeString === BOOLEAN_XSD_URI)
// {
// operation.args[i] = new o.constructor(`"${o.value.toLowerCase()}"^^${o.datatypeString}`);
// }
// }
// }
// else
if(o.type === "expression")
{
traverseExpression(o, out);
}
else if(o.type === "operation")
{
traverseOperation(o, out);
}
}
}
function traverseExpression(expression, out)
{
if(expression.type === "operation")
{
traverseOperation(expression, out)
}
}
function traverseFilter(filter, out)
{
if(filter.expression)
{
traverseExpression(filter.expression, out);
}
}
function traverseGraph(graph, out)
{
if(graph.name)
{
out.graphs.add(graph.name.value);
}
}
function generalTraverse(parts, out, state)
{
for(let i = 0; i < parts.length; i++)
{
let n = parts[i];
switch(n.type)
{
case "bgp":
traverseBGP(n.triples, out, state);
break;
case "graph":
traverseGraph(n, out, state);
case "group":
generalTraverse(n.patterns, out, state);
break;
case "query":
traverseQuery(n, out, state)
break;
case "filter":
traverseFilter(n, out, state);
break;
case "optional":
generalTraverse(n.patterns, out, {skipBgp: true});
break;
case "bind":
break;
case "union":
generalTraverse(n.patterns, out, state)
break;
case "values":
//traverseValues(n.values, out, state);
break;
default:
console.log("Unknown term?", n.type);
break;
}
}
}
function traverseQuery(query, out, state)
{
state = state || {skipBgp: false};
out.queries.push(query);
let parts = query.where;
generalTraverse(parts, out, state);
}
function setHKFiltered(query)
{
/**
* Prefixes that Triplestores recognize although not passed in a query.
*/
const prefixes = { owl: 'http://www.w3.org/2002/07/owl#' };
try
{
let sparqlParser = new SparqlJS.Parser({prefixes});
let sparqlGenerator = new SparqlJS.Generator();
let sparqlObj = sparqlParser.parse(query);
let filteredSparqlParser = new SparqlJS.Parser();
let out = {subjects: new Set(),
predicates: new Set(),
objects: new Set(),
graphs: new Set(),
queries: []};
traverseQuery(sparqlObj, out);
for(let i = 0; i < out.queries.length; i++)
{
let query = out.queries[i];
let queryTraversal = out;
let temp = {filters: ""}
let subjects = Array.from(queryTraversal.subjects);
let predicates = Array.from(queryTraversal.predicates);
let objects = Array.from(queryTraversal.objects);
let graphs = Array.from(queryTraversal.graphs);
if((subjects.length + predicates.length + objects.length + graphs.length) === 0)
{
continue;
}
let first = false;
let variables = new Set();
for(let i = 0; i < subjects.length; i++)
{
let v = subjects[i];
variables.add(`?${v}`);
if( first )
{
temp.filters += " && ";
}
filterSubjectsForHK(v, temp);
first = true;
}
// add filters for predicate variables
for(let i = 0; i < predicates.length; i++)
{
let v = predicates[i];
variables.add(`?${v}`);
if( first )
{
temp.filters += " && ";
}
filterPredicatesForHK(v, temp);
first = true;
}
// add filters for object variables
for(let i = 0; i < objects.length; i++)
{
let v = objects[i];
variables.add(`?${v}`);
if( first )
{
temp.filters += " && ";
}
filterObjectsForHK(v, temp);
first = true;
}
let filteredQuery = `select ${[...variables].join(' ')} where { filter(${temp.filters}) }`;
let filteredQueryObject = filteredSparqlParser.parse(filteredQuery);
if (query.where.length == 1 && query.where[0].type == 'query') {
// should create a group that contains the current where...
let newGroup = {
type: 'group',
patterns: [query.where[0]]
};
query.where[0] = newGroup;
}
query.where = query.where.concat(filteredQueryObject.where);
}
return sparqlGenerator.stringify(sparqlObj);
}
catch(err)
{
throw err;
}
}
function setFilterFrom(query, namedGraph)
{
try
{
let sparqlParser = new SparqlJS.Parser();
let sparqlGenerator = new SparqlJS.Generator();
let sparqlObj = sparqlParser.parse(query);
if (sparqlObj.from === undefined)
{
sparqlObj.from = { 'default': [new NamedNode(namedGraph)] };
}
else
{
if (sparqlObj.from.default)
{
sparqlObj.from.default.push(new NamedNode(namedGraph));
}
else
{
sparqlObj.from.default = [new NamedNode(namedGraph)];
}
}
return sparqlGenerator.stringify(sparqlObj);
}
catch (err)
{
throw err;
}
}
function filterPredicatesForHK (variable, filters)
{
if(!variable.startsWith("?"))
{
variable = "?" + variable;
}
filters.filters += `(
!BOUND(${variable}) ||
(
${variable} != ${HKUris.ISA_URI} &&
${variable} != ${HKUris.USES_CONNECTOR_URI} &&
${variable} != ${HKUris.CLASSNAME_URI} &&
${variable} != ${HKUris.REFERENCES_URI} &&
${variable} != ${HKUris.REFERENCED_BY_URI} &&
${variable} != ${HKUris.HAS_PARENT_URI} &&
${variable} != ${HKUris.DATA_LITERAL_URI} &&
!STRSTARTS(STR(${variable}), "hk://role") &&
!STRSTARTS(STR(${variable}), "hk://b/") &&
!STRSTARTS(STR(${variable}), "hk://link")
)
)`;
}
function filterSubjectsForHK (variable, filters)
{
filterObjectsForHK (variable, filters);
}
function filterObjectsForHK (variable, filters)
{
if(!variable.startsWith("?"))
{
variable = "?" + variable;
}
const stringBasedFilters = `!( ISIRI(${variable}) && ( STRSTARTS(STR(${variable}), "hk://role") || STRSTARTS(STR(${variable}), "hk://link") || STRSTARTS(STR(${variable}), "hk://b/") || STRSTARTS(STR(${variable}), "hk://node/") || ${variable} = ${HKUris.DATA_LITERAL_URI} ) )`;
const functionBasedFilters = `( isIRI(${variable}) || isBlank(${variable}) || datatype(${variable}) != ${HKUris.DATA_LIST_URI} )`;
filters.filters += `(
!BOUND(${variable}) ||
(
${stringBasedFilters} && ${functionBasedFilters}
)
)`;
}
function optimizeFilter (filters)
{
let out = [];
let clusters = {};
let addPairToCluster = (key)=>
{
if(!clusters.hasOwnProperty(key))
{
clusters[key] = 1;
}
else
{
clusters[key] = clusters[key] + 1;;
}
}
let getHashes = (andFilters) =>
{
let hashes = [];
for(let j = 0; j < andFilters.length; j++)
{
let constraint = andFilters[j];
for(let k in constraint)
{
let v = constraint[k];
if(typeof v === "object")
{
for(let i in v)
{
let pair = `${k}.${i}=${v[i]}`;
hashes.push(pair);
}
}
else
{
let pair = `${k}=${v}`;
hashes.push(pair);
}
}
}
return hashes;
}
for(let i = 0; i < filters.length; i++)
{
let andFilters = filters[i];
let hashes = getHashes(andFilters);
for(let h of hashes)
{
addPairToCluster(h);
}
out.push(andFilters);
}
filters.sort((a, b) =>
{
let hashesA = getHashes(a);
let hashesB = getHashes(b);
if(hashesA.length < hashesB.length)
{
return -1;
}
else if(hashesA.length > hashesB.length)
{
return 1;
}
else
{
let aCounts = [];
for(let i = 0; i < hashesA.length; i++)
{
aCounts.push(clusters[hashesA[i]]);
}
let bCounts = [];
for(let i = 0; i < hashesB.length; i++)
{
bCounts.push(clusters[hashesA[i]]);
}
aCounts.sort();
bCounts.sort();
let ka = aCounts.join("_");
let kb = bCounts.join("_");
if(ka < kb)
{
return -1;
}
else if(kb < ka)
{
return -1;
}
else
{
hashesA.sort();
hashesB.sort();
let ha = hashesA.join(";");
let hb = hashesB.join(";");
if(ha < hb)
{
return -1;
}
else if(ha > hb)
{
return 1;
}
return 0;
}
}
});
let optimized = [];
let last = filters[0];
let willBreak = false;
for(let i = 1; i < filters.length; i++)
{
let item = filters[i];
let pendingValue = null;
let pendingKey = null;
let pendingProperty = null;
let foundWildcard = false;
for(let i = 0 ; i < item.length; i++)
{
let c1 = item[i];
for(let k in c1)
{
for(let j = 0; j < last.length; j++)
{
let c2 = last[j];
if(c2.hasOwnProperty(k))
{
if(Array.isArray(c2[k]))
{
if(!foundWildcard)
{
foundWildcard = true;
pendingValue = c1[k];
pendingKey = k;
pendingProperty = c2;
}
else
{
optimized.push(last);
last = item;
willBreak = true;
break;
}
}
else if(typeof c2[k] === "object" && typeof c1[k] === "object")
{
let v1 = c1[k];
let v2 = c2[k];
for(let x in v1)
{
if(Array.isArray(v2[x]))
{
if(!foundWildcard)
{
foundWildcard = true;
pendingValue = v1[x];
pendingKey = x;
pendingProperty = v2;
}
else
{
optimized.push(last);
last = item;
willBreak = true;
break;
}
}
else if(v2.hasOwnProperty(x))
{
if(v1[x] !== v2[x])
{
if(!foundWildcard)
{
foundWildcard = true;
pendingValue = v1[x];
pendingKey = x;
pendingProperty = v2;
}
else
{
optimized.push(last);
last = item;
willBreak = true;
break;
}
}
}
else
{
optimized.push(last);
last = item;
willBreak = true;
break;
}
}
}
else
{
if(c1[k] !== c2[k])
{
if(foundWildcard)
{
optimized.push(last);
last = item;
willBreak = true;
break;
}
else
{
pendingValue = c1[k];
pendingKey = k;
pendingProperty = c2;
foundWildcard = true;
}
}
}
}
else
{
optimized.push(last);
last = item;
willBreak = true;
break;
}
}
if(willBreak)
{
break;
}
}
if(willBreak)
{
break;
}
}
if(!willBreak && pendingValue && pendingProperty && pendingKey)
{
if(!Array.isArray(pendingProperty[pendingKey]))
{
pendingProperty[pendingKey] = [pendingProperty[pendingKey]];
}
pendingProperty[pendingKey].push(pendingValue);
}
willBreak = false;
}
optimized.push(last);
return optimized;
}
function optimizeFilter2 (filters)
{
const clusters = {};
const bindClusters = {};
const bindConnClusters = {};
let out = [];
let map = {};
let bindsArray = [];
for(let i = 0; i < filters.length; i++)
{
let andFilters = filters[i];
let currentConstraint = [];
if(andFilters.length === 1)
{
for(let j = 0; j < andFilters.length; j++)
{
let constraint = andFilters[j];
let keys = Object.keys(constraint);
if(keys.length === 2)
{
if(constraint.binds && constraint.connector && Object.keys(constraint.binds).length === 1)
{
if(!bindConnClusters.hasOwnProperty(constraint.connector))
{
bindConnClusters[constraint.connector] = {};
}
let role = Object.keys(constraint.binds)[0];
let binds = bindConnClusters[constraint.connector];
if(!binds.hasOwnProperty(role))
{
binds[role] = new Set();
}
binds[role].add(constraint.binds[role]);
}
else
{
currentConstraint.push(constraint);
}
}
else
if(keys.length === 1)
{
let k = keys[0];
let v = constraint[k];
switch(k)
{
case "parent":
case "ref":
case "id":
case "connector":
if(!clusters.hasOwnProperty(k))
{
clusters[k] = new Set();
}
clusters[k].add(v);
break;
case "binds":
let role = Object.keys(constraint[k])[0];
if(!bindClusters.hasOwnProperty(role))
{
bindClusters[role] = new Set();
}
bindClusters[role].add(v[role]);
break;
default:
// out.push([constraint]);
currentConstraint.push(constraint);
break;
}
}
else
{
// out.push([constraint]);
currentConstraint.push(constraint);
}
}
if(currentConstraint.length > 0)
{
out.push(currentConstraint);
}
}
else
{
out.push(andFilters);
}
}
if(Object.keys(clusters).length > 0)
{
for(let k in clusters)
{
let optimized = {}
optimized[k] = Array.from(clusters[k]);
out.push([optimized]);
}
}
if(Object.keys(bindClusters).length > 0)
{
for(let k in bindClusters)
{
let optimized = {binds: {}};
optimized.binds[k] = Array.from(bindClusters[k]);
out.push([optimized]);
}
}
if(Object.keys(bindConnClusters).length > 0)
{
for(let k in bindConnClusters)
{
let binds = bindConnClusters[k];
for(let role in binds)
{
let optimized = {connector: k, binds: {}};
optimized.binds[role] = Array.from(binds[role]);
out.push([optimized]);
}
}
}
return out;
}
exports.optimizeFilter = optimizeFilter;
exports.filterForHK = filterPredicatesForHK;
exports.setHKFiltered = setHKFiltered;
exports.setFilterFrom = setFilterFrom;