/
sparqlprog.pl
716 lines (585 loc) · 23.6 KB
/
sparqlprog.pl
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
/* Part of sparqlprog
Adapted by Chris Mungall 2018
Copyright 2014-2015 Samer Abdallah (UCL)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version 2
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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
:- module(sparqlprog,[
sparql_endpoint/2
, sparql_endpoint/3
, current_sparql_endpoint/5
, sparql_endpoint_url/2
, srule/2
, srule/3
, srule/4
, query_goal/3 % Endpoint, Context, Opts
, query_phrase/3 % Endpoint, QueryPhrase, Result
, query_sparql/3 % Endpoint,QueryText,Result
, create_sparql_select/2
, create_sparql_select/3
, create_sparql_select/4
, create_sparql_construct/3
, create_sparql_construct/4
, inject_label_query/5
, service_query_all/4
, (??)/1
, (??)/2
, (??)/3
, op(1150,fx,??)
, op(1150,xfy,??)
]).
/** <module> Query to SPARQL endpoints with a more Prolog-like syntax
Samer Abdallah, Dept. of Computer Science, UCL (2014)
Based on Yves Raimond's swic package, but completely re-written.
Adapted by Chris Mungall
This module provides a little language for expressing SPARQL queries
and a database of known SPARQL endpoints. Queries can be executed
across multiple endpoints in parallel. When using auto-paging,
multiple queries are made automatically to fetch new bindings as
they are needed. For example,
==
EP ?? rdf(A,B,C).
==
will retrieve all triples from all endpoints in parallel, fetching
100 bindings at a time from each endpoint (assuming the setting
sparqlprog:limit takes it's default value of 100).
*/
:- use_module(library(sandbox)).
:- use_module(library(settings)).
:- use_module(library(semweb/sparql_client)).
:- use_module(library(semweb/rdf11)).
:- use_module(library(dcg_core)).
:- use_module(library(dcg_codes)).
:- use_module(sparql_dcg).
:- use_module(concurrency).
:- dynamic srule/4.
:- multifile srule/4.
:- dynamic sparql_endpoint/5.
:- multifile sparql_endpoint/5.
:- set_prolog_flag(double_quotes, codes).
:- setting(limit,integer,1000,'Default SPARQL SELECT limit').
:- setting(select_options,list,[distinct(true)],'Default select options').
:- setting(user_agent,atom,'sparqlprog','Value for http user-agent').
:- meta_predicate query_phrase(+,//,-).
sandbox:safe_meta(sparql_dcg:phrase_to_sparql(Phr,_),[Phr]).
sandbox:safe_primitive(sparql_dcg:select(_,_,_,_,_)).
sandbox:safe_primitive(sparql_dcg:describe(_,_,_,_)).
sandbox:safe_primitive(sparql_dcg:describe(_,_,_)).
sandbox:safe_primitive(sparql_dcg:ask(_,_,_)).
service_query_all(EP,Template,Spec,Results) :-
setof(Template,??(EP,Spec),Results),
!.
service_query_all(_,_,_,[]).
%% '??'(+Goal:sparql_goal) is nondet.
% Equivalent to _ ?? Goal. Will query all endpoints
% in parallel. Identical bindings may be returned multiple times.
% See query_goal/3 for details.
??(Spec) :- ??(_,Spec).
%% '??'(EP,+Goal:sparql_goal) is nondet.
% Equivalent to query_goal(EP,Goal,Opts) where Opts is the value of
% the setting sparqlprog:select_options. See query_goal/3 for details.
% IF EP is unbound on entry, it is bound to the endpoint from which
% the current bindings were obtained.
??(EP,Spec) :-
??(EP,Spec,Spec).
??(EP,Spec,SelectTerm) :-
debug(sparqlprog,'Finding subqueries: ~q',[Spec]),
expand_subqueries(Spec,Spec2,EP),
debug(sparqlprog,'Rewriting goal: ~q',[Spec2]),
rewrite_goal(Spec2,SpecRewrite),
debug(sparqlprog,'Rewritten goal: ~q',[SpecRewrite]),
spec_goal_opts(SpecRewrite,Goal,Opts),
debug(sparqlprog,'Opts: ~q',[Opts0]),
setting(select_options,Opts0),
merge_options(Opts,Opts0,Opts1),
query_goal(EP,Goal,SelectTerm,Opts1).
spec_goal_opts(Opts ?? Goal, Goal, Opts) :- !.
spec_goal_opts(Goal,Goal,[]).
subq_term(subq(Q),EP,Q,EP).
subq_term(subq(Q,EP),_,Q,EP).
subq_term(x:Q,EP,Q,EP).
expand_subqueries(V,V,_) :-
var(V),
!.
expand_subqueries(In,Out,EP) :-
ground(In),
subq_term(In,EP,Q,EP2),
!,
Q =.. L,
append(L,[NewVar],L2),
Q2 =.. L2,
debug(sparqlprog,'SUBQ: ~q on ~w',[Q2, EP2]),
setof(NewVar,??(EP2,Q2),Values),
debug(sparqlprog,'>> RESULTS: ~q',[Values]),
% TODO: allow cacheing
% TODO: allow option of parallelizing this
member(Out,Values).
expand_subqueries([],[],_) :- !.
expand_subqueries([H|L],[H2|L2],EP) :-
!,
expand_subqueries(H,H2,EP),
expand_subqueries(L,L2,EP).
expand_subqueries(In,Out,EP) :-
compound(In),
!,
In =.. [P|Args],
expand_subqueries(Args,Args2,EP),
Out =.. [P|Args2].
expand_subqueries(X,X,_) :- !.
% convert a prolog list [A,B,..] to a disjunctive term A;B;...
plist_to_disj([_-X],X) :- !.
plist_to_disj([_-X|T],(X;T2)) :- plist_to_disj(T,T2).
:- multifile rewrite_goal_hook/2.
%% rewrite_goal(+InGoal, ?OutGoalDisjunction) is semidet
%
% non-deterministic top-level goal rewrite
% if multiple goals possible, return a disjunction of goals (G1;G2;...;Gn)
% TODO: may be nondet if select variables in In...
rewrite_goal(In,OutDisj) :-
debug(sparqlprog,'XXX: Rewriting goal: ~q',[In]),
setof(Out,rewrite_goal(In,Out,1),Outs),
list_to_disj(Outs,OutDisj).
/*
% deterministic version
xxxrewrite_goal(In,OutDisj) :-
debug(sparqlprog,'XXX: Rewriting goal: ~q',[In]),
setof(In-Out,rewrite_goal(In,Out,1),InOuts),
debug(sparqlprog,'YYY: Rewritten goal: ~q -> ~q',[In,InOuts]),
unify_keys(In,InOuts),
plist_to_disj(InOuts,OutDisj),
!.
unify_keys(_,[]).
unify_keys(Term,[TermX-_ | T]) :-
term_variables(Term, Vars),
term_variables(TermX, Vars),
unify_keys(Term,T).
*/
%% rewrite_goal(+InGoal, ?OutGoal, +Depth) is semidet
%
% typically deterministic, but non-deterministic if
% multiple possible paths
rewrite_goal(In,Out,N) :-
debug(sparqlprog,'rewriting: ~q',[In]),
rewrite_goal_hook(In,X), !,
debug(sparqlprog,'Using hook to transform ~q -> ~q',[In,X]),
rewrite_goal(X,Out,N).
% ------
% terminals
% ------
rewrite_goal(T, T2,_) :- T=rdf(_,_,_), !, replace_string_unification(T,T2).
rewrite_goal(T, T2,_) :- T=rdf(_,_,_,_), !, replace_string_unification(T,T2).
rewrite_goal(filter(A), filter(A),_) :- !.
rewrite_goal(rdf_has(S,P,O), T2,_) :- !, replace_string_unification(rdf(S,P,O),T2).
rewrite_goal(service(S,G), service(S,G2), D) :- !, rewrite_goal(G,G2,D).
% TODO: consider adding semantics
%rewrite_goal(rdf(S,P,O), rdf_has(S,P,O),_) :- !.
%rewrite_goal('??'(Opts,Q), '??'(Opts,Q2), _) :- !, rewrite_goal(Q,Q2).
rewrite_goal(aggregate(A,G,V), aggregate(A,G2,V), D) :- !, rewrite_goal(G,G2,D).
rewrite_goal(aggregate_group(A,GVs,G,V), aggregate_group(A,GVs,G2,V), D) :- !, rewrite_goal(G,G2,D).
rewrite_goal(aggregate_group(A,GVs,G,H,V), aggregate_group(A,GVs,G2,H2,V), D) :- !, rewrite_goal(G,G2,D), rewrite_goal(H,H2,_).
% rdfs terminals
rewrite_goal(rdf_where(Q), rdf_where(Q2), D) :-
!,
rewrite_goal(Q, Q2, D).
rewrite_goal({Q}, {Q2}, D) :-
!,
rewrite_goal(Q, Q2, D).
rewrite_goal(optional(Q), optional(Q2), _) :-
!,
rewrite_goal(Q,Q2).
rewrite_goal(rdfs_subclass_of(C,P), rdf(C,oneOrMore(rdfs:subClassOf),P),_) :- !.
rewrite_goal(rdfs_subproperty_of(C,P), rdf(C,oneOrMore(rdfs:subPropertyOf),P),_) :- !.
rewrite_goal(rdfs_individual_of(I,C), (rdf(I,rdf:type,X),rdf(X,zeroOrMore(rdfs:subClassOf),C)),_) :- !.
rewrite_goal(a(I,C), rdf(I,rdf:type,C),_) :- !.
%rewrite_goal(rdf_member(X,L), rdf(L,oneOrMore(rdf:rest)/rdf:last,X),_) :- !.
rewrite_goal(rdf_member(X,L), rdf(L,(zeroOrMore(rdf:rest)/(rdf:first)),X),_) :- !.
% rdf11 rules
rewrite_goal(substring(S,P), contains(S,P), _) :- !.
rewrite_goal(prefix(S,P), str_starts(S,P), _) :- !.
% Match any literal that matches Pattern case insensitively, where the `*' character in Pattern matches zero or more characters
rewrite_goal(like(S,P1), regex(S,P2,i), _) :- !, like_to_regex(P1,P2).
% TODO
%rewrite_goal(word(S,P1), regex(S,P2,i), _) :- !, like_to_regex(P1,P2).
% ------
% non-terminals
% ------
rewrite_goal((A,B),(A2,B2),D) :-
!,
rewrite_goal(A,A2,D),
rewrite_goal(B,B2,D).
rewrite_goal((A;B),(A2;B2),D) :-
!,
rewrite_goal(A,A2,D),
rewrite_goal(B,B2,D).
rewrite_goal(\+A, \+A2, D) :-
!,
rewrite_goal(A,A2,D).
% EXPERIMENTING WITH NONDET
rewrite_goal(A,A2,D) :-
% TODO: see refl/2 test in test_aux
setof(A-Clause,safe_clause(A,Clause),Clauses),
!,
debug(sparqlprog,' ~q CLAUSES==> ~q',[A,Clauses,A]),
increase_depth(D,D2),
%list_to_disj(Clauses,X),
member(A-Clause,Clauses),
rewrite_goal(Clause,A2,D2).
rewrite_goal(A,A,_).
% for certain predicates, do not use replace_string_unification(T,T3)
% TODO: make this a hook
nofilter(P) :-
ground(P),
rdf_global_id(P,Px),
atomic(Px),
atom_concat('http://www.bigdata.com/rdf/search#',_,Px).
% rdf11 'like' construct
like_to_regex(Like,Re) :-
concat_atom(Parts,'*',Like),
( Parts=[''|_]
-> Init=''
; Init='^'),
( reverse(Parts,[''|_])
-> Last=''
; Last='$'),
concat_atom(Parts,'.*',Re1),
concat_atom([Init,Re1,Last],Re).
% We avoid translation rdf(X,rdf:label,"foo") to a direct
% triple in the SPARQL query, since this may fail to
% match (e.g. if xsd:string is the actual type)
% instead we translate to (rdf(X,rdf:label,VAR),VAR=="foo")
% because this yields a FILTER in the SPARQL giving desired results
replace_string_unification(T,T) :-
( T=rdf(_,P,_)
; T=rdf(_,P,_,_)),
nofilter(P),
!.
replace_string_unification(T,T3) :-
debug(sparqlprog,'replacing string unification: ~q',[T]),
T =.. [P|Args],
replace_string_unification_args(Args,Args2,T2,T3),
T2 =.. [P|Args2],
debug(sparqlprog,'replaced string unification: ~q',[T3]).
replace_string_unification_args([],[],T,T).
replace_string_unification_args([A|Args],[A2|Args2],T,(T2,FreshVar==A)) :-
string(A),
!,
A2 = FreshVar,
replace_string_unification_args(Args,Args2,T,T2).
replace_string_unification_args([A|Args],[A|Args2],T,T2) :-
replace_string_unification_args(Args,Args2,T,T2).
no_rewrite(rdf_graph(_)).
no_rewrite(rdf_predicate(_)).
no_rewrite(rdf_is_iri(_)).
no_rewrite(member(_,_)).
safe_clause(Goal,Body) :-
catch(clause(Goal,Body,Ref),_,fail),
% TODO: come up with a more extensible way to prevent SPARQL builtins being expanded
\+ no_rewrite(Goal),
\+ ((clause_property(Ref,module(Mod)),
Mod=emulate_builtins)).
% TODO: attempt at expanding clauses not exported
% not clear this is a good idea...
todo__safe_clause(Goal,LocalBody) :-
catch(clause(Goal,Body,Ref),_,fail),
clause_property(Ref,module(M)),
( M\=system,
\+ ((Body=..[rdf|_])),
catch(clause(M:Body,_),_,fail)
-> LocalBody = M:Body
; LocalBody=Body).
list_to_disj([X],X) :- !.
list_to_disj([X|T],(X;T2)) :- list_to_disj(T,T2).
increase_depth(D,_) :-
D > 10,
!,
throw(error(max_depth_exceeded(D))).
increase_depth(D,D2) :-
D2 is D+1.
%! srule(+Pred, +Args) is det.
%! srule(+Pred, +Args, +Desc) is det.
%
% declare a new sparql rule
srule(P,A) :- srule(P,A,'').
srule(P,A,D) :-
current_module(M),
assert(srule(P,A,D,M)).
/*
* Assert/declare a new sparql end point
*/
%% sparql_endpoint(+EP:ground, +URL:atom, +Options) is det.
%% sparql_endpoint(+EP:ground, +URL:atom) is det.
%
% Declares EP as a short name for a SPARQL endpoint with the given URL.
% No options are defined at the moment.
sparql_endpoint(EP,Url) :- sparql_endpoint(EP,Url,[]).
sparql_endpoint(EP,Url,Options) :-
url_endpoint(Url,Host,Port,Path),
!,
retract_declared_endpoint(EP,Url),
debug(sparqlprog,'Asserting SPARQL end point ~q: ~q ~q ~q ~q.',[EP,Host,Port,Path,Options]),
assert(sparql_endpoint(EP,Host,Port,Path,Options)).
retract_declared_endpoint(EP,Url) :-
sparql_endpoint(EP,Host,Port,Path,_),
format('% WARNING: Updating already registered SPARQL end point ~q.\n',[Url]),
retractall(sparql_endpoint(EP,Host,Port,Path,_)),
!.
retract_declared_endpoint(_,_).
user:term_expansion(:-(sparql_endpoint(EP,Url)), Expanded) :-
endpoint_declaration(EP,Url,[],Expanded).
user:term_expansion(:-(sparql_endpoint(EP,Url,Options)), Expanded) :-
endpoint_declaration(EP,Url,Options,Expanded).
sparql_endpoint_url(EP,Url) :- sparql_endpoint(EP,Url,_,_,_).
endpoint_declaration(EP,Url,Options, sparqlprog:sparql_endpoint(EP,Host,Port,Path,Options)) :-
debug(sparqlprog,'Declaring SPARQL end point ~q: ~q ~q ~q ~q.',[EP,Host,Port,Path,Options]),
url_endpoint(Url,Host,Port,Path).
url_endpoint(Url,Host,Port,Path) :-
parse_url(Url,Parsed),
member(host(Host),Parsed),
member(path(Path),Parsed),
(member(port(Port),Parsed);Port=80).
%% current_sparql_endpoint(-EP:ground,-Host:atom,-Port:natural,-Path:atom,-Options:list) is nondet.
%
% Succeeds once for each known endpoint.
current_sparql_endpoint(EP,Host,Port,Path,Options) :-
sparql_endpoint(EP,Host,Port,Path,Options).
% ----------------------------------------------------
% Goal-based queries
% These get translated into phrase-based queries.
%% query_goal(+EP,+Goal:sparql_goal,+Opts) is nondet.
%% query_goal(-EP,+Goal:sparql_goal,+Opts) is nondet.
%
% Runs a SPARQL query against one or more SPARQL endpoints.
% Goal is converted into a textual SPARQL query using the DCG
% defined in sparql_dcg.pl.
%
% If EP is ground on entry, the query is run against the specified endpoint.
% If EP is unbound on entry, the query is run agains all endpoints
% in parallel, possibly returning multiple results from each.
%
% (The following applies only to queries that return bindings, not
% to simple boolean questions, which return only true or false.)
% Options are as follows:
% * limit(L:natural)
% At-most this many bindings will be returned per SPARQL call.
% * offset(O:natural)
% Begin returning bindings from the Oth result on.
% * autopage(Auto:bool)
% If false, a single SPARQL call is made using any limit and offset
% options if supplied. If true, then the offset option is ignored
% and multiple SPARQL queries are made as necessary to supply
% results, using the limit option to determine the number of results
% retrieved from the endpoint at a time.
% Other options are passed to phrase_to_sparql/2.
query_goal(EP,Goal,Opts) :-
query_goal(EP,Goal,Goal,Opts).
query_goal(EP,Goal,SelectTerm,Opts) :-
findall(EP,sparql_endpoint(EP,_,_,_,_),EPs),
term_variables(SelectTerm,Vars),
( Vars = [] % if no variables, do an ASK query, otherwise, SELECT
-> phrase_to_sparql(ask(Goal),SPARQL),
parallel_query(simple_query(SPARQL),EPs,EP-true)
; Result =.. [row|Vars],
setting(limit,DefaultLimit),
call_dcg(( option_default_select(limit(Limit),DefaultLimit),
option_default_select(autopage(Auto),true),
( {Auto=true}
-> {Query = autopage_query(Limit,SPARQL)},
option_default_select(offset(_),_)
; {Query = simple_query(SPARQL)},
cons(limit(Limit))
)
), Opts, Opts1),
debug(sparqlprog,'DCG: ~q ~q ~q',[Vars,Goal,Opts1]),
phrase_to_sparql(select(Vars,Goal,Opts1),SPARQL),
debug(sparqlprog,'Executing parallel query: ~w // ~w // ~w',[SPARQL,Query,EPs]),
parallel_query(Query,EPs,EP-Result)
).
%% create_sparql_select(+Goal,-SPARQL,+Opts) is det.
%% create_sparql_select(+Goal,-SPARQL) is det.
%
% Generates a sparql SELECT or ASK statement for a
% prolog goal without executing it.
%
% Goal can be any prolog goal consisting of based
% rdf/3 or rdf/4 statements, filters, or terms
% that can be rewritten in this way
create_sparql_select(Goal,SPARQL) :-
create_sparql_select(Goal,SPARQL,[]).
create_sparql_select(Goal,SPARQL,Opts) :-
create_sparql_select(Goal,Goal,SPARQL,Opts).
create_sparql_select(Select,Goal,SPARQL,Opts) :-
select(inject_labels(true),Opts,OptsRest),
!,
inject_label_query(Select,Goal,Select2,Goal2,Opts),
create_sparql_select(Select2,Goal2,SPARQL,OptsRest).
create_sparql_select(Select,Goal,SPARQL,Opts) :-
filter_opts(Opts,OptsFiltered),
rewrite_goal(Goal,Goal2),
debug(sparqlprog,'Rewritten goal2: ~q',[Goal2]),
term_variables(Select,Vars),
debug(sparqlprog,'Vars: ~q',[Vars]),
( Vars = [] % if no variables, do an ASK query, otherwise, SELECT
-> phrase_to_sparql(ask(Goal2),SPARQL)
; setting(limit,DefaultLimit),
call_dcg(( option_default_select(limit(Limit),DefaultLimit),
option_default_select(autopage(Auto),true),
( {Auto=true}
-> {Query = autopage_query(Limit,SPARQL)},
option_default_select(offset(_),_)
; {Query = simple_query(SPARQL)},
cons(limit(Limit))
)
), OptsFiltered, Opts1),
phrase_to_sparql(select(Vars,Goal2,Opts1),SPARQL,Opts)).
filter_opts([],[]).
filter_opts([H|T],[H|T2]) :-
H=..[P|_],
P\=inject_labels,
P\=bindings,
P\=label_predicate,
!,
filter_opts(T,T2).
filter_opts([_|T],T2) :-
filter_opts(T,T2).
%% inject_label_query(+Select, +Query, ?Select2, ?Query2, +Opts) is det
%
% Add an optional(rdf(X,rdfs:label,XL)) for every variable X in Select
% TODO: interleave
inject_label_query(Select, Goal, Select2, (Goal,ConjGoal), Opts) :-
term_variables(Select,Vars),
option(label_predicate(P),Opts,rdfpred(rdfs:label)),
inject_label_for_vars(Vars,ConjGoal,LabelVars,P),
conjoin(Select,LabelVars,Select2).
inject_label_for_vars([Var],Goal,[LabelVar],P) :-
!,
inject_label_for_var(Var,Goal,LabelVar,P).
inject_label_for_vars([Var|Vars],(Goal1,Goal2),[LabelVar|LabelVars],P) :-
!,
inject_label_for_var(Var,Goal1,LabelVar,P),
inject_label_for_vars(Vars,Goal2,LabelVars,P).
inject_label_for_var(Var,optional(rdf(Var,P,VarLabel)),VarLabel,rdfpred(P)) :- !. % e.g. rdfs:label
inject_label_for_var(Var,optional(Goal),VarLabel,P) :- Goal =.. [P,Var,VarLabel]. % prolog predicate, e.g. enlabel/2
conjoin(Term,L,T2) :-
is_list(Term),
!,
append(Term,L,T2).
conjoin(Term,L,[Term|L]) :-
\+compound(Term),
!.
conjoin(Term,L,T2) :-
Term =.. [P|Args],
append(Args,L,Args2),
T2 =.. [P|Args2].
%% create_sparql_construct(+Head,+Goal,-SPARQL,+Opts) is det.
%% create_sparql_construct(+Head,+Goal,-SPARQL) is det.
%
% Generates a sparql CONSTRUCT statement for a
% prolog goal without executing it.
%
% Goal or Head can be any prolog goal consisting of based
% rdf/3 or rdf/4 statements, filters, or terms
% that can be rewritten in this way
%
% the Head forms the head part of the CONSTRUCT
create_sparql_construct(Head,Goal,SPARQL) :-
create_sparql_construct(Head,Goal,SPARQL,[]).
create_sparql_construct(Head,Goal,SPARQL,Opts) :-
rewrite_goal(Goal,Goal2),
rewrite_goal(Head,Head2),
debug(sparqlprog,'Rewritten: ~q <- ~q',[Head2,Goal2]),
phrase_to_sparql(construct(Head2,Goal2,Opts),SPARQL).
cons(X,T,[X|T]).
option_default_select(Opt,Def,O1,O2) :- select_option(Opt,O1,O2,Def).
simple_query(SPARQL,EP,EP-Result) :- query_sparql(EP,SPARQL,Result).
autopage_query(Limit,SPARQL,EP,EP-Result) :- autopage(EP,SPARQL,Limit,0,Result).
autopage(EP,SPARQL,Limit,Offset,Result) :-
format(string(Q),'~s LIMIT ~d OFFSET ~d',[SPARQL,Limit,Offset]),
findall(R,query_sparql(EP,Q,R),Results),
( member(Result,Results)
; length(Results,Limit), % no next page if length(Results) < Limit
Offset1 is Offset + Limit, % next batch of results
autopage(EP,SPARQL,Limit,Offset1,Result)
).
parallel_query(_,[],_) :- !, fail.
parallel_query(P,[X],Y) :- !, call(P,X,Y).
parallel_query(P,Xs,Y) :-
maplist(par_goal(P,Y),Xs,Goals),
concurrent_or(Y,Goals,[on_error(continue)]).
par_goal(P,Y,X,call(P,X,Y)).
%% query_phrase(+EP,+Q:sparqle_phrase(R),R) is nondet.
%% query_phrase(-EP,+Q:sparqle_phrase(R),R) is nondet.
%
% Phrase-based queries using the DCG defined in sparql_dcg.pl.
% The return type depends on the query:
% ==
% select(V:list(var), sparql_goal, options) :: sparql_phrase(row(N)) :- length(V,N).
% describe(resource,sparql_goal) :: sparql_phrase(rdf).
% describe(resource) :: sparql_phrase(rdf).
% ask(sparql_goal) :: sparql_phrase(bool).
%
% rdf ---> rdf(resource,resource,object).
% bool ---> true; false.
% ==
% =|row(N)|= is the type of terms of functor row/N.
query_phrase(EP,Phrase,Result) :-
phrase_to_sparql(Phrase,SPARQL),
query_sparql(EP,SPARQL,Result).
phrase_to_sparql(Phrase,SPARQL) :-
phrase_to_sparql(Phrase,SPARQL,[]).
phrase_to_sparql(Phrase,SPARQL,Opts) :-
option(bindings(Bindings),Opts),
!,
term_variables(Phrase,Vars),
copy_term(t(Vars,Phrase,Bindings),t(Vars1,Phrase1,Bindings1)),
assign_vars_using_bindings(Vars1,Bindings1),
phrase_vars_to_sparql(Phrase1,Vars1,SPARQL).
phrase_to_sparql(Phrase,SPARQL,_Opts) :-
term_variables(Phrase,Vars),
copy_term(t(Vars,Phrase),t(Vars1,Phrase1)),
phrase_vars_to_sparql(Phrase1,Vars1,SPARQL).
phrase_vars_to_sparql(Phrase1,Vars1,SPARQL) :-
numbervars(Vars1,0,_),
( phrase(Phrase1,Codes)
-> true
; throw(unrecognised_query(Phrase1))
),
string_codes(SPARQL,Codes),
debug(sparqlprog,'SPARQL query: ~s',[SPARQL]).
%! assign_vars_using_bindings(+Vars:list,+Bindings:list) is det
%
% Bindings = [A='A',B='B', ...]
% assign all variables in Bindings to a variable v(Name)
%
% rationale: by default, we assign vars to numbers using numbervars/3
% these are then translated by the DCG to ?v1, ?v2, ... etc
% if the SPARQL is intended to be seen, then it's preferable
% to use the user's own meaningful assigned variable names
assign_vars_using_bindings(_,[]).
assign_vars_using_bindings(Vars1,[VN=v(VN2)|Bindings]) :-
downcase_first_char(VN,VN2),
assign_vars_using_bindings(Vars1,Bindings).
downcase_first_char(A,A2) :-
atom_chars(A,[C|Chars]),
downcase_atom(C,C2),
atom_chars(A2,[C2|Chars]).
% ----------------------------------------------------
% In the end, everything comes through this.
%% query_sparql(?EP,SPARQL,-Result) is nondet.
%
% Runs textual SPARQL query against an endpoint, exactly as
% with sparql_query/3. If EP is unbound on entry, all known
% endpoints will be tried sequentially.
query_sparql(EP,SPARQL,Result) :-
sparql_endpoint(EP,Host,Port,Path,EPOpts),
debug(sparqlprog,'Querying endpoint http://~q:~q~q - ~w',[Host,Port,Path,SPARQL]),
setting(user_agent,UserAgent),
sparql_query(SPARQL,Result,[user_agent(UserAgent),host(Host),port(Port),path(Path)|EPOpts]).