Class: RedlandAdapter

Inherits:
ActiveRdfAdapter
  • Object
show all
Defined in:
lib/activerdf_redland/redland.rb

Overview

Adapter to Redland database uses SPARQL for querying

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ RedlandAdapter

instantiate connection to Redland database



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
# File 'lib/activerdf_redland/redland.rb', line 16

def initialize(params = {})
   super()

	if params[:location] and params[:location] == :postgresql
		initialize_postgresql(params)
		return
	end

	if params[:location] and params[:location] != :memory
		# setup file defaults for redland database
		type = 'bdb'
                       want_new = false    # create new or use existing store
                       write = true
                       contexts = true

                       if params[:want_new] == true
                          want_new = true
                       end
                       if params[:write] == false
                          write = false
                       end
                       if params[:contexts] == false
                          contexts = false
                       end

     if params[:location].include?('/')
       path, file = File.split(params[:location])
     else
       path = '.'
       file = params[:location]
     end
	else
		# fall back to in-memory redland 	
		type = 'memory'; path = '';	file = '.'; want_new = false; write = true; contexts = true
	end
	
	
	begin
		@store = Redland::HashStore.new(type, file, path, want_new, write, contexts)
		@model = Redland::Model.new @store
		@reads = true
		@writes = true
     $activerdflog.info "initialised Redland adapter to #{@model.inspect}"

	rescue Redland::RedlandError => e
		raise ActiveRdfError, "could not initialise Redland database: #{e.message}"
	end
end

Instance Method Details

#add(s, p, o) ⇒ Object

add triple to datamodel



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/activerdf_redland/redland.rb', line 175

def add(s, p, o)
   $activerdflog.debug "adding triple #{s} #{p} #{o}"

	# verify input
	if s.nil? || p.nil? || o.nil?
     $activerdflog.debug "cannot add triple with empty subject, exiting"
	  return false
	end 
	
	unless s.respond_to?(:uri) && p.respond_to?(:uri)
     $activerdflog.debug "cannot add triple where s/p are not resources, exiting"
	  return false
	end

	begin
	  @model.add(wrap(s), wrap(p), wrap(o))		  
		save if ConnectionPool.auto_flush?
	rescue Redland::RedlandError => e
	  $activerdflog.warn "RedlandAdapter: adding triple failed in Redland library: #{e}"
	  return false
	end		
end

#clearObject

clear all real triples of adapter



228
229
230
# File 'lib/activerdf_redland/redland.rb', line 228

def clear
  @model.find(nil, nil, nil) {|s,p,o| @model.delete(s,p,o)}
end

#closeObject

close adapter and remove it from the ConnectionPool



233
234
235
# File 'lib/activerdf_redland/redland.rb', line 233

def close
  ConnectionPool.remove_data_source(self)
end

#delete(s, p, o) ⇒ Object

deletes triple(s,p,o) from datastore nil parameters match anything: delete(nil,nil,nil) will delete all triples



200
201
202
203
204
205
# File 'lib/activerdf_redland/redland.rb', line 200

def delete(s,p,o)
	s = wrap(s) unless s.nil?
	p = wrap(p) unless p.nil?
	o = wrap(o) unless o.nil?
	@model.delete(s,p,o)
end

#dumpObject

returns all triples in the datastore



214
215
216
# File 'lib/activerdf_redland/redland.rb', line 214

def dump
	Redland.librdf_model_to_string(@model.model, nil, 'ntriples')
end

#get_query_results(query, result_format = nil) ⇒ Object

executes query and returns results as SPARQL JSON or XML results requires svn version of redland-ruby bindings

  • query: ActiveRDF Query object

  • result_format: :json or :xml



147
148
149
# File 'lib/activerdf_redland/redland.rb', line 147

def get_query_results(query, result_format=nil)
	get_sparql_query_results(Query2SPARQL.translate(query), result_format)
end

#get_sparql_query_results(qs, result_format = nil) ⇒ Object

executes sparql query and returns results as SPARQL JSON or XML results

  • query: sparql query string

  • result_format: :json or :xml



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/activerdf_redland/redland.rb', line 154

def get_sparql_query_results(qs, result_format=nil)
# author: Eric Hanson

# set uri for result formatting
result_uri = 
	case result_format
 	when :json
      Redland::Uri.new('http://www.w3.org/2001/sw/DataAccess/json-sparql/')
    when :xml
      Redland::Uri.new('http://www.w3.org/TR/2004/WD-rdf-sparql-XMLres-20041221/')
	end

# query redland
  redland_query = Redland::Query.new(qs, 'sparql')
  query_results = @model.query_execute(redland_query)

# get string representation in requested result_format (json or xml)
  query_results.to_string()
end

#initialize_postgresql(params = {}) ⇒ Object

instantiate connection to Redland database in Postgres



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
# File 'lib/activerdf_redland/redland.rb', line 66

def initialize_postgresql(params = {})
   # author: Richard Dale
	type = 'postgresql'
	name = params[:name]

	options = []
	options << "new='#{params[:new]}'" if params[:new]
   options << "bulk='#{params[:bulk]}'" if params[:bulk]
   options << "merge='#{params[:merge]}'" if params[:merge]
	options << "host='#{params[:host]}'" if params[:host]
	options << "database='#{params[:database]}'" if params[:database]
	options << "user='#{params[:user]}'" if params[:user]
	options << "password='#{params[:password]}'" if params[:password]
	options << "port='#{params[:port]}'" if params[:port]

	
	$activerdflog.info "RedlandAdapter: initializing with type: #{type} name: #{name} options: #{options.join(',')}"
	
	begin
		@store = Redland::TripleStore.new(type, name, options.join(','))
		@model = Redland::Model.new @store
		@reads = true
		@writes = true
	rescue Redland::RedlandError => e
		raise ActiveRdfError, "could not initialise Redland database: #{e.message}"
	end
end

#load(location, syntax = "ntriples") ⇒ Object

load a file from the given location with the given syntax into the model. use Redland syntax strings, e.g. “ntriples” or “rdfxml”, defaults to “ntriples”



96
97
98
99
100
101
102
103
# File 'lib/activerdf_redland/redland.rb', line 96

def load(location, syntax="ntriples")
   parser = Redland::Parser.new(syntax, "", nil)
   if location =~ /^http/
     parser.parse_into_model(@model, location)
   else
     parser.parse_into_model(@model, "file:#{location}")
   end
end

#query(query) ⇒ Object

yields query results (as many as requested in select clauses) executed on data source



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
# File 'lib/activerdf_redland/redland.rb', line 106

def query(query)
	qs = Query2SPARQL.translate(query)
   $activerdflog.debug "RedlandAdapter: executing SPARQL query #{qs}"
	
	clauses = query.select_clauses.size
	redland_query = Redland::Query.new(qs, 'sparql')
	query_results = @model.query_execute(redland_query)

	# return Redland's answer without parsing if ASK query
	return [[query_results.get_boolean?]] if query.ask?
	
	$activerdflog.debug "RedlandAdapter: found #{query_results.size} query results"

	# verify if the query has failed
	if query_results.nil?
	  $activerdflog.debug "RedlandAdapter: query has failed with nil result"
	  return false
	end
	if not query_results.is_bindings?
	  $activerdflog.debug "RedlandAdapter: query has failed without bindings"
	  return false
	end


	# convert the result to array
	#TODO: if block is given we should not parse all results into array first
	results = query_result_to_array(query_results) 
	
	if block_given?
		results.each do |clauses|
			yield(*clauses)
		end
	else
		results
	end
end

#saveObject Also known as: flush

saves updates to the model into the redland file location



208
209
210
# File 'lib/activerdf_redland/redland.rb', line 208

def save
	Redland::librdf_model_sync(@model.model).nil?
end

#sizeObject

returns size of datasources as number of triples warning: expensive method as it iterates through all statements



220
221
222
223
224
225
# File 'lib/activerdf_redland/redland.rb', line 220

def size
	# we cannot use @model.size, because redland does not allow counting of 
	# file-based models (@model.size raises an error if used on a file)
	# instead, we just dump all triples, and count them
   @model.triples.size
end