Class: Tripod::SparqlQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/tripod/sparql_query.rb

Constant Summary collapse

@@PREFIX_KEYWORDS =
%w(BASE PREFIX)
@@KEYWORDS =
%w(CONSTRUCT ASK DESCRIBE SELECT)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query_string) ⇒ SparqlQuery

Returns a new instance of SparqlQuery.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/tripod/sparql_query.rb', line 18

def initialize(query_string)
  @query = query_string.strip

  if self.has_prefixes?
    @prefixes, @body = self.extract_prefixes
  else
    @body = self.query
  end

  @query_type = get_query_type
end

Instance Attribute Details

#bodyObject (readonly)

 the body of the query



10
11
12
# File 'lib/tripod/sparql_query.rb', line 10

def body
  @body
end

#prefixesObject (readonly)

any prefixes the query may have



11
12
13
# File 'lib/tripod/sparql_query.rb', line 11

def prefixes
  @prefixes
end

#queryObject (readonly)

the original query string



8
9
10
# File 'lib/tripod/sparql_query.rb', line 8

def query
  @query
end

#query_typeObject (readonly)

symbol representing the type (:select, :ask etc)



9
10
11
# File 'lib/tripod/sparql_query.rb', line 9

def query_type
  @query_type
end

Instance Method Details

#as_count_query_strObject



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/tripod/sparql_query.rb', line 49

def as_count_query_str
  check_subqueryable!

  count_query = "SELECT (COUNT(*) as ?tripod_count_var) {
  #{self.body}
}"
  count_query = "#{self.prefixes} #{count_query}" if self.prefixes

  # just returns the string representing the count query for this query.
  count_query
end

#as_first_query_strObject



61
62
63
64
65
66
67
68
69
# File 'lib/tripod/sparql_query.rb', line 61

def as_first_query_str
  check_subqueryable!

  first_query = "SELECT * { #{self.body} } LIMIT 1"
  first_query = "#{self.prefixes} #{first_query}" if self.prefixes

  # just returns the string representing the 'first' query for this query.
  first_query
end

#check_subqueryable!Object

Raises:



44
45
46
47
# File 'lib/tripod/sparql_query.rb', line 44

def check_subqueryable!
  # only allow for selects
  raise SparqlQueryError.new("Can't turn this into a subquery") unless self.query_type == :select
end

#extract_prefixesObject



37
38
39
40
41
42
# File 'lib/tripod/sparql_query.rb', line 37

def extract_prefixes
  i = self.class.KEYWORDS.map {|k| self.query.index(/#{k}/i) || self.query.size+1 }.min
  p = query[0..i-1]
  b = query[i..-1]
  return p.strip, b.strip
end

#has_prefixes?Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
# File 'lib/tripod/sparql_query.rb', line 30

def has_prefixes?
  self.class.PREFIX_KEYWORDS.each do |k|
    return true if /^#{k}/i.match(query)
  end
  return false
end