forked from IKS/rdfQuery
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.rdf.js
2474 lines (2350 loc) · 103 KB
/
jquery.rdf.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
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
/*
* jQuery RDF @VERSION
*
* Copyright (c) 2008,2009 Jeni Tennison
* Licensed under the MIT (MIT-LICENSE.txt)
*
* Depends:
* jquery.uri.js
* jquery.xmlns.js
* jquery.datatype.js
* jquery.curie.js
* jquery.json.js
*/
/**
* @fileOverview jQuery RDF
* @author <a href="mailto:[email protected]">Jeni Tennison</a>
* @copyright (c) 2008,2009 Jeni Tennison
* @license MIT license (MIT-LICENSE.txt)
* @version 1.0
*/
/**
* @exports $ as jQuery
*/
/**
* @ignore
*/
(function ($) {
var
memResource = {},
memBlank = {},
memLiteral = {},
memTriple = {},
memPattern = {},
xsdNs = "http://www.w3.org/2001/XMLSchema#",
rdfNs = "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
rdfsNs = "http://www.w3.org/2000/01/rdf-schema#",
uriRegex = /^<(([^>]|\\>)*)>$/,
literalRegex = /^("""((\\"|[^"])*)"""|"((\\"|[^"])*)")(@([a-z]+(-[a-z0-9]+)*)|\^\^(.+))?$/,
tripleRegex = /(("""((\\"|[^"])*)""")|("(\\"|[^"]|)*")|(<(\\>|[^>])*>)|\S)+/g,
blankNodeSeed = databankSeed = new Date().getTime() % 1000,
blankNodeID = function () {
blankNodeSeed += 1;
return 'b' + blankNodeSeed.toString(16);
},
databankID = function () {
databankSeed += 1;
return 'data' + databankSeed.toString(16);
},
databanks = {},
documentQueue = {},
subject = function (subject, opts) {
if (typeof subject === 'string') {
try {
return $.rdf.resource(subject, opts);
} catch (e) {
try {
return $.rdf.blank(subject, opts);
} catch (f) {
throw "Bad Triple: Subject " + subject + " is not a resource: " + f;
}
}
} else {
return subject;
}
},
property = function (property, opts) {
if (property === 'a') {
return $.rdf.type;
} else if (typeof property === 'string') {
try {
return $.rdf.resource(property, opts);
} catch (e) {
throw "Bad Triple: Property " + property + " is not a resource: " + e;
}
} else {
return property;
}
},
object = function (object, opts) {
if (typeof object === 'string') {
try {
return $.rdf.resource(object, opts);
} catch (e) {
try {
return $.rdf.blank(object, opts);
} catch (f) {
try {
return $.rdf.literal(object, opts);
} catch (g) {
throw "Bad Triple: Object " + object + " is not a resource or a literal " + g;
}
}
}
} else {
return object;
}
},
testResource = function (resource, filter, existing) {
var variable;
if (typeof filter === 'string') {
variable = filter.substring(1);
if (existing[variable] && existing[variable] !== resource) {
return null;
} else {
existing[variable] = resource;
return existing;
}
} else if (filter === resource) {
return existing;
} else {
return null;
}
},
findMatches = function (databank, pattern) {
if (databank.union === undefined) {
if (pattern.subject.type !== undefined) {
if (databank.subjectIndex[pattern.subject] === undefined) {
return [];
}
return $.map(databank.subjectIndex[pattern.subject], function (triple) {
var bindings = pattern.exec(triple);
return bindings === null ? null : { bindings: bindings, triples: [triple] };
});
} else if (pattern.object.type === 'uri' || pattern.object.type === 'bnode') {
if (databank.objectIndex[pattern.object] === undefined) {
return [];
}
return $.map(databank.objectIndex[pattern.object], function (triple) {
var bindings = pattern.exec(triple);
return bindings === null ? null : { bindings: bindings, triples: [triple] };
});
} else if (pattern.property.type !== undefined) {
if (databank.propertyIndex[pattern.property] === undefined) {
return [];
}
return $.map(databank.propertyIndex[pattern.property], function (triple) {
var bindings = pattern.exec(triple);
return bindings === null ? null : { bindings: bindings, triples: [triple] };
});
}
}
return $.map(databank.triples(), function (triple) {
var bindings = pattern.exec(triple);
return bindings === null ? null : { bindings: bindings, triples: [triple] };
});
},
mergeMatches = function (existingMs, newMs, optional) {
return $.map(existingMs, function (existingM, i) {
var compatibleMs = $.map(newMs, function (newM) {
// For newM to be compatible with existingM, all the bindings
// in newM must either be the same as in existingM, or not
// exist in existingM
var k, b, isCompatible = true;
for (k in newM.bindings) {
b = newM.bindings[k];
if (!(existingM.bindings[k] === undefined ||
existingM.bindings[k] === b)) {
isCompatible = false;
break;
}
}
return isCompatible ? newM : null;
});
if (compatibleMs.length > 0) {
return $.map(compatibleMs, function (compatibleM) {
return {
bindings: $.extend({}, existingM.bindings, compatibleM.bindings),
triples: unique(existingM.triples.concat(compatibleM.triples))
};
});
} else {
return optional ? existingM : null;
}
});
},
registerQuery = function (databank, query) {
var s, p, o;
if (query.filterExp !== undefined && !$.isFunction(query.filterExp)) {
if (databank.union === undefined) {
s = typeof query.filterExp.subject === 'string' ? '' : query.filterExp.subject;
p = typeof query.filterExp.property === 'string' ? '' : query.filterExp.property;
o = typeof query.filterExp.object === 'string' ? '' : query.filterExp.object;
if (databank.queries[s] === undefined) {
databank.queries[s] = {};
}
if (databank.queries[s][p] === undefined) {
databank.queries[s][p] = {};
}
if (databank.queries[s][p][o] === undefined) {
databank.queries[s][p][o] = [];
}
databank.queries[s][p][o].push(query);
} else {
$.each(databank.union, function (i, databank) {
registerQuery(databank, query);
});
}
}
},
resetQuery = function (query) {
query.length = 0;
query.matches = [];
$.each(query.children, function (i, child) {
resetQuery(child);
});
$.each(query.partOf, function (i, union) {
resetQuery(union);
});
},
updateQuery = function (query, matches) {
if (matches.length > 0) {
$.each(query.children, function (i, child) {
leftActivate(child, matches);
});
$.each(query.partOf, function (i, union) {
updateQuery(union, matches);
});
$.each(matches, function (i, match) {
query.matches.push(match);
Array.prototype.push.call(query, match.bindings);
});
}
},
filterMatches = function (matches, variables) {
var i, bindings, triples, j, k, variable, value, nvariables = variables.length,
newbindings, match = {}, keyobject = {}, keys = {}, filtered = [];
for (i = 0; i < matches.length; i += 1) {
bindings = matches[i].bindings;
triples = matches[i].triples;
keyobject = keys;
for (j = 0; j < nvariables; j += 1) {
variable = variables[j];
value = bindings[variable];
if (j === nvariables - 1) {
if (keyobject[value] === undefined) {
match = { bindings: {}, triples: triples };
for (k = 0; k < nvariables; k += 1) {
match.bindings[variables[k]] = bindings[variables[k]];
}
keyobject[value] = match;
filtered.push(match);
} else {
match = keyobject[value];
match.triples = match.triples.concat(triples);
}
} else {
if (keyobject[value] === undefined) {
keyobject[value] = {};
}
keyobject = keyobject[value];
}
}
}
return filtered;
},
renameMatches = function (matches, old) {
var i, match, newMatch, keys = {}, renamed = [];
for (i = 0; i < matches.length; i += 1) {
match = matches[i];
if (keys[match.bindings[old]] === undefined) {
newMatch = {
bindings: { node: match.bindings[old] },
triples: match.triples
};
renamed.push(newMatch);
keys[match.bindings[old]] = newMatch;
} else {
newMatch = keys[match.bindings[old]];
newMatch.triples = newMatch.triples.concat(match.triples);
}
}
return renamed;
},
leftActivate = function (query, matches) {
var newMatches;
if (query.union === undefined) {
if (query.top || query.parent.top) {
newMatches = query.alphaMemory;
} else {
matches = matches || query.parent.matches;
if ($.isFunction(query.filterExp)) {
newMatches = $.map(matches, function (match, i) {
return query.filterExp.call(match.bindings, i, match.bindings, match.triples) ? match : null;
});
} else if (query.filterExp !== undefined) {
newMatches = mergeMatches(matches, query.alphaMemory, query.filterExp.optional);
} else {
newMatches = matches;
}
}
} else {
newMatches = $.map(query.union, function (q) {
return q.matches;
});
}
if (query.selections !== undefined) {
newMatches = filterMatches(newMatches, query.selections);
} else if (query.navigate !== undefined) {
newMatches = renameMatches(newMatches, query.navigate);
}
updateQuery(query, newMatches);
},
rightActivate = function (query, match) {
var newMatches;
if (query.filterExp.optional) {
resetQuery(query);
leftActivate(query);
} else {
if (query.top || query.parent.top) {
newMatches = [match];
} else {
newMatches = mergeMatches(query.parent.matches, [match], false);
}
updateQuery(query, newMatches);
}
},
addToQuery = function (query, triple) {
var match,
bindings = query.filterExp.exec(triple);
if (bindings !== null) {
match = { triples: [triple], bindings: bindings };
query.alphaMemory.push(match);
rightActivate(query, match);
}
},
removeFromQuery = function (query, triple) {
query.alphaMemory.splice($.inArray(triple, query.alphaMemory), 1);
resetQuery(query);
leftActivate(query);
},
addToQueries = function (queries, triple) {
$.each(queries, function (i, query) {
addToQuery(query, triple);
});
},
removeFromQueries = function (queries, triple) {
$.each(queries, function (i, query) {
removeFromQuery(query, triple);
});
},
addToDatabankQueries = function (databank, triple) {
var s = triple.subject,
p = triple.property,
o = triple.object;
if (databank.union === undefined) {
if (databank.queries[s] !== undefined) {
if (databank.queries[s][p] !== undefined) {
if (databank.queries[s][p][o] !== undefined) {
addToQueries(databank.queries[s][p][o], triple);
}
if (databank.queries[s][p][''] !== undefined) {
addToQueries(databank.queries[s][p][''], triple);
}
}
if (databank.queries[s][''] !== undefined) {
if (databank.queries[s][''][o] !== undefined) {
addToQueries(databank.queries[s][''][o], triple);
}
if (databank.queries[s][''][''] !== undefined) {
addToQueries(databank.queries[s][''][''], triple);
}
}
}
if (databank.queries[''] !== undefined) {
if (databank.queries[''][p] !== undefined) {
if (databank.queries[''][p][o] !== undefined) {
addToQueries(databank.queries[''][p][o], triple);
}
if (databank.queries[''][p][''] !== undefined) {
addToQueries(databank.queries[''][p][''], triple);
}
}
if (databank.queries[''][''] !== undefined) {
if (databank.queries[''][''][o] !== undefined) {
addToQueries(databank.queries[''][''][o], triple);
}
if (databank.queries[''][''][''] !== undefined) {
addToQueries(databank.queries[''][''][''], triple);
}
}
}
} else {
$.each(databank.union, function (i, databank) {
addToDatabankQueries(databank, triple);
});
}
},
removeFromDatabankQueries = function (databank, triple) {
var s = triple.subject,
p = triple.property,
o = triple.object;
if (databank.union === undefined) {
if (databank.queries[s] !== undefined) {
if (databank.queries[s][p] !== undefined) {
if (databank.queries[s][p][o] !== undefined) {
removeFromQueries(databank.queries[s][p][o], triple);
}
if (databank.queries[s][p][''] !== undefined) {
removeFromQueries(databank.queries[s][p][''], triple);
}
}
if (databank.queries[s][''] !== undefined) {
if (databank.queries[s][''][o] !== undefined) {
removeFromQueries(databank.queries[s][''][o], triple);
}
if (databank.queries[s][''][''] !== undefined) {
removeFromQueries(databank.queries[s][''][''], triple);
}
}
}
if (databank.queries[''] !== undefined) {
if (databank.queries[''][p] !== undefined) {
if (databank.queries[''][p][o] !== undefined) {
removeFromQueries(databank.queries[''][p][o], triple);
}
if (databank.queries[''][p][''] !== undefined) {
removeFromQueries(databank.queries[''][p][''], triple);
}
}
if (databank.queries[''][''] !== undefined) {
if (databank.queries[''][''][o] !== undefined) {
removeFromQueries(databank.queries[''][''][o], triple);
}
if (databank.queries[''][''][''] !== undefined) {
removeFromQueries(databank.queries[''][''][''], triple);
}
}
}
} else {
$.each(databank.union, function (i, databank) {
removeFromDatabankQueries(databank, triple);
});
}
},
group = function (bindings, variables, base) {
var variable = variables[0], grouped = {}, results = [], i, newbase;
base = base || {};
if (variables.length === 0) {
for (i = 0; i < bindings.length; i += 1) {
for (v in bindings[i]) {
if (base[v] === undefined) {
base[v] = [];
}
if ($.isArray(base[v])) {
base[v].push(bindings[i][v]);
}
}
}
return [base];
}
// collect together the grouped results
for (i = 0; i < bindings.length; i += 1) {
key = bindings[i][variable];
if (grouped[key] === undefined) {
grouped[key] = [];
}
grouped[key].push(bindings[i]);
}
// call recursively on each group
variables = variables.splice(1, 1);
for (v in grouped) {
newbase = $.extend({}, base);
newbase[variable] = grouped[v][0][variable];
results = results.concat(group(grouped[v], variables, newbase));
}
return results;
},
queue = function (databank, url, callbacks) {
if (documentQueue[databank.id] === undefined) {
documentQueue[databank.id] = {};
}
if (documentQueue[databank.id][url] === undefined) {
documentQueue[databank.id][url] = callbacks;
return false;
}
return true;
},
dequeue = function (databank, url, result, args) {
var callbacks = documentQueue[databank.id][url];
if ($.isFunction(callbacks[result])) {
callbacks[result].call(databank, args);
}
documentQueue[databank.id][url] = undefined;
},
unique = function( b ) {
var a = [];
var l = b.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
// If b[i] is found later in the array
if (b[i] === b[j])
j = ++i;
}
a.push(b[i]);
}
return a;
};
$.typedValue.types['http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral'] = {
regex: /^.*$/m,
strip: false,
value: function (v) {
return v;
}
};
/**
* <p>Creates a new jQuery.rdf object. This should be invoked as a method rather than constructed using new; indeed you will usually want to generate these objects using a method such as {@link jQuery#rdf} or {@link jQuery.rdf#where}.</p>
* @class <p>A jQuery.rdf object represents the results of a query over its {@link jQuery.rdf#databank}. The results of a query are a sequence of objects which represent the bindings of values to the variables used in filter expressions specified using {@link jQuery.rdf#where} or {@link jQuery.rdf#optional}. Each of the objects in this sequence has associated with it a set of triples that are the sources for the variable bindings, which you can get at using {@link jQuery.rdf#sources}.</p>
* <p>The {@link jQuery.rdf} object itself is a lot like a {@link jQuery} object. It has a {@link jQuery.rdf#length} and the individual matches can be accessed using <code>[<var>n</var>]</code>, but you can also iterate through the matches using {@link jQuery.rdf#map} or {@link jQuery.rdf#each}.</p>
* <p>{@link jQuery.rdf} is designed to mirror the functionality of <a href="http://www.w3.org/TR/rdf-sparql-query/">SPARQL</a> while providing an interface that's familiar and easy to use for jQuery programmers.</p>
* @param {Object} [options]
* @param {jQuery.rdf.databank} [options.databank] The databank that this query should operate over.
* @param {jQuery.rdf.triple[]} [options.triples] A set of triples over which the query operates; this is only used if options.databank isn't specified, in which case a new databank with these triples is generated.
* @param {Object} [options.namespaces] An object representing a set of namespace bindings. Rather than passing this in when you construct the {@link jQuery.rdf} instance, you will usually want to use the {@link jQuery.rdf#prefix} method.
* @param {String|jQuery.uri} [options.base] The base URI used to interpret any relative URIs used within the query.
* @returns {jQuery.rdf}
* @example rdf = jQuery.rdf();
* @see jQuery#rdf
*/
$.rdf = function (options) {
return new $.rdf.fn.init(options);
};
$.rdf.fn = $.rdf.prototype = {
/**
* The version of rdfQuery.
* @type String
*/
rdfquery: '1.1',
init: function (options) {
var databanks, i;
options = options || {};
/* must specify either a parent or a union, otherwise it's the top */
this.parent = options.parent;
this.union = options.union;
this.top = this.parent === undefined && this.union === undefined;
if (this.union === undefined) {
if (options.databank === undefined) {
/**
* The databank over which this query operates.
* @type jQuery.rdf.databank
*/
this.databank = this.parent === undefined ? $.rdf.databank(options.triples, options) : this.parent.databank;
} else {
this.databank = options.databank;
}
} else {
databanks = $.map(this.union, function (query) {
return query.databank;
});
databanks = unique(databanks);
if (databanks[1] !== undefined) {
this.databank = $.rdf.databank(undefined, { union: databanks });
} else {
this.databank = databanks[0];
}
}
this.children = [];
this.partOf = [];
this.filterExp = options.filter;
this.selections = options.distinct;
this.navigate = options.navigate;
this.alphaMemory = [];
this.matches = [];
/**
* The number of matches represented by the {@link jQuery.rdf} object.
* @type Integer
*/
this.length = 0;
if (this.filterExp !== undefined) {
if (!$.isFunction(this.filterExp)) {
registerQuery(this.databank, this);
this.alphaMemory = findMatches(this.databank, this.filterExp);
}
} else if (options.nodes !== undefined) {
this.alphaMemory = [];
for (i = 0; i < options.nodes.length; i += 1) {
this.alphaMemory.push({
bindings: { node: options.nodes[i] },
triples: []
});
}
}
leftActivate(this);
return this;
},
/**
* Sets or returns the base URI of the {@link jQuery.rdf#databank}.
* @param {String|jQuery.uri} [base]
* @returns A {@link jQuery.uri} if no base URI is specified, otherwise returns this {@link jQuery.rdf} object.
* @example baseURI = jQuery('html').rdf().base();
* @example jQuery('html').rdf().base('http://www.example.org/');
* @see jQuery.rdf.databank#base
*/
base: function (base) {
if (base === undefined) {
return this.databank.base();
} else {
this.databank.base(base);
return this;
}
},
/**
* Sets or returns a namespace binding on the {@link jQuery.rdf#databank}.
* @param {String} [prefix]
* @param {String} [namespace]
* @returns {Object|jQuery.uri|jQuery.rdf} If no prefix or namespace is specified, returns an object providing all namespace bindings on the {@link jQuery.rdf.databank}. If a prefix is specified without a namespace, returns the {@link jQuery.uri} associated with that prefix. Otherwise returns this {@link jQuery.rdf} object after setting the namespace binding.
* @example namespace = jQuery('html').rdf().prefix('foaf');
* @example jQuery('html').rdf().prefix('foaf', 'http://xmlns.com/foaf/0.1/');
* @see jQuery.rdf.databank#prefix
*/
prefix: function (prefix, namespace) {
if (namespace === undefined) {
return this.databank.prefix(prefix);
} else {
this.databank.prefix(prefix, namespace);
return this;
}
},
/**
* Adds a triple to the {@link jQuery.rdf#databank} or another {@link jQuery.rdf} object to create a union.
* @param {String|jQuery.rdf.triple|jQuery.rdf.pattern|jQuery.rdf} triple The triple, {@link jQuery.rdf.pattern} or {@link jQuery.rdf} object to be added to this one. If the triple is a {@link jQuery.rdf} object, the two queries are unioned together. If the triple is a string, it's parsed as a {@link jQuery.rdf.pattern}. The pattern will be completed using the current matches on the {@link jQuery.rdf} object to create multiple triples, one for each set of bindings.
* @param {Object} [options]
* @param {Object} [options.namespaces] An object representing a set of namespace bindings used to interpret CURIEs within the triple. Defaults to the namespace bindings defined on the {@link jQuery.rdf#databank}.
* @param {String|jQuery.uri} [options.base] The base URI used to interpret any relative URIs used within the triple. Defaults to the base URI defined on the {@link jQuery.rdf#databank}.
* @returns {jQuery.rdf} This {@link jQuery.rdf} object.
* @example
* var rdf = $.rdf()
* .prefix('dc', ns.dc)
* .prefix('foaf', ns.foaf)
* .add('<photo1.jpg> dc:creator <http://www.blogger.com/profile/1109404> .')
* .add('<http://www.blogger.com/profile/1109404> foaf:img <photo1.jpg> .');
* @example
* var rdfA = $.rdf()
* .prefix('dc', ns.dc)
* .add('<photo1.jpg> dc:creator "Jane"');
* var rdfB = $.rdf()
* .prefix('foaf', ns.foaf)
* .add('<photo1.jpg> foaf:depicts "Jane"');
* var rdf = rdfA.add(rdfB);
* @see jQuery.rdf.databank#add
*/
add: function (triple, options) {
var query, databank;
if (triple.rdfquery !== undefined) {
if (triple.top) {
databank = this.databank.add(triple.databank);
query = $.rdf({ parent: this.parent, databank: databank });
return query;
} else if (this.top) {
databank = triple.databank.add(this.databank);
query = $.rdf({ parent: triple.parent, databank: databank });
return query;
} else if (this.union === undefined) {
query = $.rdf({ union: [this, triple] });
this.partOf.push(query);
triple.partOf.push(query);
return query;
} else {
this.union.push(triple);
triple.partOf.push(this);
}
} else {
if (typeof triple === 'string') {
options = $.extend({}, { base: this.base(), namespaces: this.prefix(), source: triple }, options);
triple = $.rdf.pattern(triple, options);
}
if (triple.isFixed()) {
this.databank.add(triple.triple(), options);
} else {
query = this;
this.each(function (i, data) {
var t = triple.triple(data);
if (t !== null) {
query.databank.add(t, options);
}
});
}
}
return this;
},
/**
* Removes a triple or several triples from the {@link jQuery.rdf#databank}.
* @param {String|jQuery.rdf.triple|jQuery.rdf.pattern} triple The triple to be removed, or a {@link jQuery.rdf.pattern} that matches the triples that should be removed.
* @param {Object} [options]
* @param {Object} [options.namespaces] An object representing a set of namespace bindings used to interpret any CURIEs within the triple or pattern. Defaults to the namespace bindings defined on the {@link jQuery.rdf#databank}.
* @param {String|jQuery.uri} [options.base] The base URI used to interpret any relative URIs used within the triple or pattern. Defaults to the base URI defined on the {@link jQuery.rdf#databank}.
* @returns {jQuery.rdf} The {@link jQuery.rdf} object itself.
* @example
* var rdf = $('html').rdf()
* .prefix('foaf', ns.foaf)
* .where('?person foaf:givenname ?gname')
* .where('?person foaf:family_name ?fname')
* .remove('?person foaf:family_name ?fname');
* @see jQuery.rdf.databank#remove
*/
remove: function (triple, options) {
if (typeof triple === 'string') {
options = $.extend({}, { base: this.base(), namespaces: this.prefix() }, options);
triple = $.rdf.pattern(triple, options);
}
if (triple.isFixed()) {
this.databank.remove(triple.triple(), options);
} else {
query = this;
this.each(function (i, data) {
var t = triple.triple(data);
if (t !== null) {
query.databank.remove(t, options);
}
});
}
return this;
},
/**
* Loads some data into the {@link jQuery.rdf#databank}
* @param data
* @param {Object} [options]
* @see jQuery.rdf.databank#load
*/
load: function (data, options) {
var rdf = this,
options = options || {},
success = options.success;
if (success !== undefined) {
options.success = function () {
success.call(rdf);
}
}
this.databank.load(data, options);
return this;
},
/**
* Creates a new {@link jQuery.rdf} object whose databank contains all the triples in this object's databank except for those in the argument's databank.
* @param {jQuery.rdf} query
* @see jQuery.rdf.databank#except
*/
except: function (query) {
return $.rdf({ databank: this.databank.except(query.databank) });
},
/**
* Creates a new {@link jQuery.rdf} object that is the result of filtering the matches on this {@link jQuery.rdf} object based on the filter that's passed into it.
* @param {String|jQuery.rdf.pattern} filter An expression that filters the triples in the {@link jQuery.rdf#databank} to locate matches based on the matches on this {@link jQuery.rdf} object. If it's a string, the filter is parsed as a {@link jQuery.rdf.pattern}.
* @param {Object} [options]
* @param {Object} [options.namespaces] An object representing a set of namespace bindings used to interpret any CURIEs within the pattern. Defaults to the namespace bindings defined on the {@link jQuery.rdf#databank}.
* @param {String|jQuery.uri} [options.base] The base URI used to interpret any relative URIs used within the pattern. Defaults to the base URI defined on the {@link jQuery.rdf#databank}.
* @param {boolean} [options.optional] Not usually used (use {@link jQuery.rdf#optional} instead).
* @returns {jQuery.rdf} A new {@link jQuery.rdf} object whose {@link jQuery.rdf#parent} is this {@link jQuery.rdf}.
* @see jQuery.rdf#optional
* @see jQuery.rdf#filter
* @see jQuery.rdf#about
* @example
* var rdf = $.rdf()
* .prefix('foaf', ns.foaf)
* .add('_:a foaf:givenname "Alice" .')
* .add('_:a foaf:family_name "Hacker" .')
* .add('_:b foaf:givenname "Bob" .')
* .add('_:b foaf:family_name "Hacker" .')
* .where('?person foaf:family_name "Hacker"')
* .where('?person foaf:givenname "Bob");
*/
where: function (filter, options) {
var query, base, namespaces, optional;
options = options || {};
if (typeof filter === 'string') {
base = options.base || this.base();
namespaces = $.extend({}, this.prefix(), options.namespaces || {});
optional = options.optional || false;
filter = $.rdf.pattern(filter, { namespaces: namespaces, base: base, optional: optional });
}
query = $.rdf($.extend({}, options, { parent: this, filter: filter }));
this.children.push(query);
return query;
},
/**
* Creates a new {@link jQuery.rdf} object whose set of bindings might optionally include those based on the filter pattern.
* @param {String|jQuery.rdf.pattern} filter An pattern for a set of bindings that might be added to those in this {@link jQuery.rdf} object.
* @param {Object} [options]
* @param {Object} [options.namespaces] An object representing a set of namespace bindings used to interpret any CURIEs within the pattern. Defaults to the namespace bindings defined on the {@link jQuery.rdf#databank}.
* @param {String|jQuery.uri} [options.base] The base URI used to interpret any relative URIs used within the pattern. Defaults to the base URI defined on the {@link jQuery.rdf#databank}.
* @returns {jQuery.rdf} A new {@link jQuery.rdf} object whose {@link jQuery.rdf#parent} is this {@link jQuery.rdf}.
* @see jQuery.rdf#where
* @see jQuery.rdf#filter
* @see jQuery.rdf#about
* @example
* var rdf = $.rdf()
* .prefix('foaf', 'http://xmlns.com/foaf/0.1/')
* .prefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')
* .add('_:a rdf:type foaf:Person .')
* .add('_:a foaf:name "Alice" .')
* .add('_:a foaf:mbox <mailto:[email protected]> .')
* .add('_:a foaf:mbox <mailto:[email protected]> .')
* .add('_:b rdf:type foaf:Person .')
* .add('_:b foaf:name "Bob" .')
* .where('?x foaf:name ?name')
* .optional('?x foaf:mbox ?mbox');
*/
optional: function (filter, options) {
return this.where(filter, $.extend({}, options || {}, { optional: true }));
},
/**
* Creates a new {@link jQuery.rdf} object whose set of bindings include <code>property</code> and <code>value</code> for every triple that is about the specified resource.
* @param {String|jQuery.rdf.resource} resource The subject of the matching triples.
* @param {Object} [options]
* @param {Object} [options.namespaces] An object representing a set of namespace bindings used to interpret the resource if it's a CURIE. Defaults to the namespace bindings defined on the {@link jQuery.rdf#databank}.
* @param {String|jQuery.uri} [options.base] The base URI used to interpret the resource if it's a relative URI (wrapped in <code><</code> and <code>></code>). Defaults to the base URI defined on the {@link jQuery.rdf#databank}.
* @returns {jQuery.rdf} A new {@link jQuery.rdf} object whose {@link jQuery.rdf#parent} is this {@link jQuery.rdf}.
* @see jQuery.rdf#where
* @see jQuery.rdf#optional
* @see jQuery.rdf#filter
* @example
* var rdf = $.rdf()
* .prefix('dc', ns.dc)
* .prefix('foaf', ns.foaf)
* .add('<photo1.jpg> dc:creator <http://www.blogger.com/profile/1109404> .')
* .add('<http://www.blogger.com/profile/1109404> foaf:img <photo1.jpg> .')
* .add('<photo2.jpg> dc:creator <http://www.blogger.com/profile/1109404> .')
* .add('<http://www.blogger.com/profile/1109404> foaf:img <photo2.jpg> .')
* .about('<http://www.blogger.com/profile/1109404>');
*/
about: function (resource, options) {
return this.where(resource + ' ?property ?value', options);
},
/**
* Creates a new {@link jQuery.rdf} object whose set of bindings include only those that satisfy some arbitrary condition. There are two main ways to call this method: with two arguments in which case the first is a binding to be tested and the second represents a condition on the test, or with one argument which is a function that should return true for acceptable bindings.
* @param {Function|String} property <p>In the two-argument version, this is the name of a property to be tested against the condition specified in the second argument. In the one-argument version, this is a function in which <code>this</code> is an object whose properties are a set of {@link jQuery.rdf.resource}, {@link jQuery.rdf.literal} or {@link jQuery.rdf.blank} objects and whose arguments are:</p>
* <dl>
* <dt>i</dt>
* <dd>The index of the set of bindings amongst the other matches</dd>
* <dt>bindings</dt>
* <dd>An object representing the bindings (the same as <code>this</code>)</dd>
* <dt>triples</dt>
* <dd>The {@link jQuery.rdf.triple}s that underly this set of bindings</dd>
* </dl>
* @param {RegExp|String} condition In the two-argument version of this function, the condition that the property's must match. If it is a regular expression, the value must match the regular expression. If it is a {@link jQuery.rdf.literal}, the value of the literal must match the property's value. Otherwise, they must be the same resource.
* @returns {jQuery.rdf} A new {@link jQuery.rdf} object whose {@link jQuery.rdf#parent} is this {@link jQuery.rdf}.
* @see jQuery.rdf#where
* @see jQuery.rdf#optional
* @see jQuery.rdf#about
* @example
* var rdf = $.rdf()
* .prefix('foaf', 'http://xmlns.com/foaf/0.1/')
* .add('_:a foaf:surname "Jones" .')
* .add('_:b foaf:surname "Macnamara" .')
* .add('_:c foaf:surname "O\'Malley"')
* .add('_:d foaf:surname "MacFee"')
* .where('?person foaf:surname ?surname')
* .filter('surname', /^Ma?c/)
* .each(function () { scottish.push(this.surname.value); })
* .end()
* .filter('surname', /^O'/)
* .each(function () { irish.push(this.surname.value); })
* .end();
* @example
* var rdf = $.rdf()
* .prefix('foaf', 'http://xmlns.com/foaf/0.1/')
* .add('_:a foaf:surname "Jones" .')
* .add('_:b foaf:surname "Macnamara" .')
* .add('_:c foaf:surname "O\'Malley"')
* .add('_:d foaf:surname "MacFee"')
* .where('?person foaf:surname ?surname')
* .filter(function () { return this.surname !== "Jones"; })
*/
filter: function (property, condition) {
var func, query;
if (typeof property === 'string') {
if (condition.constructor === RegExp) {
/** @ignore func */
func = function () {
return condition.test(this[property].value);
};
} else {
func = function () {
return this[property].type === 'literal' ? this[property].value === condition : this[property] === condition;
};
}
} else {
func = property;
}
query = $.rdf({ parent: this, filter: func });
this.children.push(query);
return query;
},
/**
* Creates a new {@link jQuery.rdf} object containing one binding for each selected resource.
* @param {String|Object} node The node to be selected. If this is a string beginning with a question mark the resources are those identified by the bindings of that value in the currently selected bindings. Otherwise, only the named resource is selected as the node.
* @returns {jQuery.rdf} A new {@link jQuery.rdf} object.
* @see jQuery.rdf#find
* @see jQuery.rdf#back
* @example
* // returns an rdfQuery object with a pointer to <http://example.com/aReallyGreatBook>
* var rdf = $('html').rdf()
* .node('<http://example.com/aReallyGreatBook>');
*/
node: function (resource) {
var variable, query;
if (resource.toString().substring(0, 1) === '?') {
variable = resource.toString().substring(1);
query = $.rdf({ parent: this, navigate: variable });
} else {
if (typeof resource === 'string') {
resource = object(resource, { namespaces: this.prefix(), base: this.base() });
}
query = $.rdf({ parent: this, nodes: [resource] });
}
this.children.push(query);
return query;
},
/**
* Navigates from the resource identified by the 'node' binding to another node through the property passed as the argument.
* @param {String|Object} property The property whose value will be the new node.
* @returns {jQuery.rdf} A new {@link jQuery.rdf} object whose {@link jQuery.rdf#parent} is this {@link jQuery.rdf}.
* @see jQuery.rdf#back
* @see jQuery.rdf#node
* @example
* var creators = $('html').rdf()
* .node('<>')
* .find('dc:creator');
*/
find: function (property) {
return this.where('?node ' + property + ' ?object', { navigate: 'object' });
},
/**
* Navigates from the resource identified by the 'node' binding to another node through the property passed as the argument, like {jQuery.rdf#find}, but backwards.
* @param {String|Object} property The property whose value will be the new node.
* @returns {jQuery.rdf} A new {@link jQuery.rdf} object whose {@link jQuery.rdf#parent} is this {@link jQuery.rdf}.
* @see jQuery.rdf#find
* @see jQuery.rdf#node
* @example
* var people = $('html').rdf()
* .node('foaf:Person')
* .back('rdf:type');
*/
back: function (property) {
return this.where('?subject ' + property + ' ?node', { navigate: 'subject' });
},
/**
* Groups the bindings held by this {@link jQuery.rdf} object based on the values of the variables passed as the parameter.
* @param {String[]} [bindings] The variables to group by. The returned objects will contain all their current properties, but those aside from the specified variables will be arrays listing the relevant values.
* @returns {jQuery} A jQuery object containing objects representing the grouped bindings.
* @example
* // returns one object per person and groups all the names and all the emails together in arrays
* var grouped = rdf
* .where('?person foaf:name ?name')
* .where('?person foaf:email ?email')
* .group('person');
* @example
* // returns one object per surname/firstname pair, with the person property being an array in the resulting objects
* var grouped = rdf
* .where('?person foaf:first_name ?forename')
* .where('?person foaf:givenname ?surname')
* .group(['surname', 'forename']);
*/
group: function (bindings) {
var grouped = {}, results = [], i, key, v;
if (!$.isArray(bindings)) {