-
Notifications
You must be signed in to change notification settings - Fork 14
/
alt.rb
86 lines (80 loc) · 2.48 KB
/
alt.rb
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
module SPARQL; module Algebra
class Operator
##
# The SPARQL Property Path `alt` (Alternative Property Path) operator.
#
# Let P and Q be property path expressions.
#
# eval(Path(X, alt(P,Q), Y)) = Union(eval(Path(X, P, Y)), eval(Path(X, Q, Y)))
#
# [89] PathAlternative ::= PathSequence ( '|' PathSequence )*
#
# @example SPARQL Query
# PREFIX : <http://www.example.org/>
# SELECT ?t
# WHERE {
# :a :p1|:p2/:p3|:p4 ?t
# }
#
# @example SSE
# (prefix ((: <http://www.example.org/>))
# (project (?t)
# (path :a
# (alt
# (alt :p1 (seq :p2 :p3))
# :p4)
# ?t)))
#
# @see https://www.w3.org/TR/sparql11-query/#defn_evalPP_alternative
class Alt < Operator::Binary
include Query
NAME = :alt
##
# Equivalent to:
#
# (path x (alt :p :q) y)
# => (union (bgp (x :p y)) (bgp (x :q y)))
#
# @param [RDF::Queryable] queryable
# the graph or repository to query
# @param [Hash{Symbol => Object}] options
# any additional keyword options
# @option options [RDF::Term, RDF::Variable] :subject
# @option options [RDF::Term, RDF::Variable] :object
# @yield [solution]
# each matching solution
# @yieldparam [RDF::Query::Solution] solution
# @yieldreturn [void] ignored
# @see https://www.w3.org/TR/sparql11-query/#sparqlAlgebra
def execute(queryable, **options, &block)
subject, object = options[:subject], options[:object]
debug(options) {"Alt #{[subject, operands, object].to_sse}"}
# Solutions where predicate exists
qa = if operand(0).is_a?(RDF::Term)
RDF::Query.new do |q|
q.pattern [subject, operand(0), object]
end
else
operand(0)
end
qb = if operand(1).is_a?(RDF::Term)
RDF::Query.new do |q|
q.pattern [subject, operand(1), object]
end
else
operand(1)
end
query = Union.new(qa, qb)
queryable.query(query, **options.merge(depth: options[:depth].to_i + 1), &block)
end
##
#
# Returns a partial SPARQL grammar for this operator.
#
# @return [String]
def to_sparql(**options)
"(#{operands.first.to_sparql(**options)}|#{operands.last.to_sparql(**options)})"
end
end # Alt
end # Operator
end; end # SPARQL::Algebra