Class: Stardog::Connection

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConnection

Returns a new instance of Connection.



95
96
97
98
99
# File 'lib/stardog.rb', line 95

def initialize
  # By default (for testing)
  @endpoint = 'http://localhost:5822/'
  @credentials = {:user =>'admin', :password => 'admin'}
end

Instance Attribute Details

#credentialsObject

Returns the value of attribute credentials.



93
94
95
# File 'lib/stardog.rb', line 93

def credentials
  @credentials
end

#endpointObject

Returns the value of attribute endpoint.



93
94
95
# File 'lib/stardog.rb', line 93

def endpoint
  @endpoint
end

#reasoningObject

Returns the value of attribute reasoning.



93
94
95
# File 'lib/stardog.rb', line 93

def reasoning
  @reasoning
end

Instance Method Details

#add(database, body, graph_uri = nil, content_type = "text/plain") ⇒ Object



144
145
146
147
148
149
150
# File 'lib/stardog.rb', line 144

def add(database, body, graph_uri=nil, content_type="text/plain")
  with_transaction(database) do |txId|
    result = add_in_transaction(database, txId, body, graph_uri, content_type)
    raise Exception.new("Error adding data to database #{database} -> #{result.body}") unless(result.success?)
    result
  end
end

#add_icv(database, body, content_type = "text/plain") ⇒ Object



346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/stardog.rb', line 346

def add_icv(database, body, content_type = "text/plain")

  if(File.exists?(body))
    body = File.open(body,"r").read
  elsif(body =~ /^https?:\/\/[\S]+$/)
    result = http_request("GET", body, (content_type == "text/plain" ? "*/*" : content_type), {}, nil, false)
    raise Exception.new("Error adding data from remote URL #{body} => #{result.status} : #{result}") if result.status != 200
    body = result.body
  end

  is_json =  (content_type.index("json") ? true : false)
  http_request("POST", "#{database}/icv/add", "*/*", {}, body, is_json, content_type, nil)
end

#add_in_transaction(database, txID, body, graph_uri = nil, content_type = "text/plain") ⇒ Object



279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/stardog.rb', line 279

def add_in_transaction(database, txID, body, graph_uri=nil, content_type="text/plain")
  options = nil
  options = {"graph-uri" => graph_uri} if graph_uri

  if(File.exists?(body))
    body = File.open(body,"r").read
  elsif(body =~ /^https?:\/\/[\S]+$/)
    result = http_request("GET", body, (content_type == "text/plain" ? "*/*" : content_type), {}, nil, false)
    raise Exception.new("Error adding data from remote URL #{body} => #{result.status} : #{result}") if result.status != 200
    body = result.body
  end
  
  http_request("POST", "#{database}/#{txID}/add", "*/*", options, body, false, content_type, nil)
end

#begin(database) ⇒ Object

Transactions



193
194
195
196
197
198
199
200
# File 'lib/stardog.rb', line 193

def begin(database)
  result = http_request("POST", "#{database}/transaction/begin", "text/plain", "")
  if(result.status == 200)
    result.body
  else
    raise Exception.new("Error beginning transaction #{result}")
  end
end

#clear_db(database, txId, graph_uri = nil) ⇒ Object



309
310
311
312
313
314
# File 'lib/stardog.rb', line 309

def clear_db(database, txId, graph_uri = nil)
  options = nil
  options = {"graph-uri" => graph_uri} if graph_uri

  http_request("POST", database + "/" + txId + "/clear", "text/plain", options);
end

#clear_icvs(database) ⇒ Object



373
374
375
# File 'lib/stardog.rb', line 373

def clear_icvs(database)
  http_request("POST", "#{database}/icv/clear", "*/*", {}, "", false, "text/plain", nil)
end

#clear_stardogObject

Admin



466
467
468
469
470
# File 'lib/stardog.rb', line 466

def clear_stardog
  list_dbs.body["databases"].each do |db|
    drop_db db
  end
end

#commit(database, txID) ⇒ Object



203
204
205
# File 'lib/stardog.rb', line 203

def commit(database, txID)
  http_request("POST", "#{database}/transaction/commit/#{txID}", "text/plain", "")
end

#consistent?(database) ⇒ Boolean

Returns:

  • (Boolean)


332
333
334
335
# File 'lib/stardog.rb', line 332

def consistent?(database)
  res = http_request("GET", "#{database}/reasoning/consistency", "text/boolean", {}, nil, false)
  (res.body == "true" ? true : false)
end

#convert_icv(database, body, content_type = "text/plain") ⇒ Object



377
378
379
380
381
382
383
384
385
386
387
# File 'lib/stardog.rb', line 377

def convert_icv(database, body, content_type = "text/plain")
  if(File.exists?(body))
    body = File.open(body,"r").read
  elsif(body =~ /^https?:\/\/[\S]+$/)
    result = http_request("GET", body, (content_type == "text/plain" ? "*/*" : content_type), {}, nil, false)
    raise Exception.new("Error adding data from remote URL #{body} => #{result.status} : #{result}") if result.status != 200
    body = result.body
  end

  http_request("POST", "#{database}/icv/convert", "*/*", {}, body, false, content_type, nil)
end

#copy_db(db_source, db_target) ⇒ Object

Copy a database Copies a database. The source database must be offline. The target database will be created.



419
420
421
# File 'lib/stardog.rb', line 419

def copy_db(db_source,db_target)
  http_request("PUT", "admin/databases/#{db_source}/copy", "application/json", { "to" => db_target })
end

#create_db(dbname, creation_options = {}) ⇒ Object

Creates a new database



424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/stardog.rb', line 424

def create_db(dbname, creation_options={})
  options = creation_options[:options] || {}
  files = creation_options[:files] ||= []
  if(files.empty?)
    http_request("POST", "admin/databases", "text/plain", {}, {:dbname => dbname, :options => options, :files => files}.to_json, true, "application/json", true)
  else
    f = Tempfile.new("stardog_rb_#{Time.now.to_i}")
    f << "{\"dbname\":\"#{dbname}\",\"options\":#{options.to_json},\"files\":[{"
    files.each_with_index do |datafile,i|
      f << "\"name\":\"#{File.basename(datafile)}\", \"content\":"
      f << File.open(datafile,"r").read.chomp.to_json
      f << "," if i != (files.length - 1)
    end
    f << "}]}"
    f.flush
    f.close
    http_request("POST", "admin/databases", "text/plain", {}, File.new(f.path), true, "application/json", true)                  
  end
end

#db_options(db_name, options = ["database.name", "icv.enabled", "search.enabled", "database.online", "index.type"]) ⇒ Object

Get configuration properties for the database. The list of properties can be found here: stardog.com/docs/admin/#admin-db By default, “database.name”, “icv.enabled”, “search.enabled”, “database.online”, “index.type” properties a requested.



402
403
404
# File 'lib/stardog.rb', line 402

def db_options(db_name, options = ["database.name", "icv.enabled", "search.enabled", "database.online", "index.type"])
  http_request("PUT", "admin/databases/#{db_name}/options", "application/json", {}, options.inject({}){|ac,i| ac[i]=""; ac})
end

#drop_db(dbname) ⇒ Object

Drops an existent database.



445
446
447
# File 'lib/stardog.rb', line 445

def drop_db(dbname)
  http_request("DELETE", "admin/databases/#{dbname}", "application/json", "")      
end

#get_db(database) ⇒ Object



118
119
120
# File 'lib/stardog.rb', line 118

def get_db(database)
  http_request("GET", database)
end

#get_db_size(database) ⇒ Object



122
123
124
# File 'lib/stardog.rb', line 122

def get_db_size(database)
  http_request("GET", "#{database}/size")      
end

#get_property(database, uri, property) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
# File 'lib/stardog.rb', line 106

def get_property(database, uri, property)
  str_query = 'select ?val where { '+ uri +' '+ property +' ?val }' 

  json_res = query(database, str_query).body

  if (json_res["results"] && json_res["results"]["bindings"].length > 0)
json_res["results"]["bindings"].first["val"]["value"]
  else
    nil
  end
end

#list_dbsObject

List all available databases



394
395
396
# File 'lib/stardog.rb', line 394

def list_dbs
  http_request("GET", "admin/databases", "application/json", "")
end

#list_icvs(database, options = {}) ⇒ Object

Integrity Constraints



341
342
343
344
# File 'lib/stardog.rb', line 341

def list_icvs(database, options = {})
  accept = options[:accept] || "application/x-turtle"
  http_request("GET", "#{database}/icv", accept, {}, nil, false)
end

#offline_db(dbname, strategy_op = 'WAIT', timeout = 3) ⇒ Object

Sets database offline.

  • strategy_op: ‘WAIT’ | ‘NO_WAIT’, default ‘WAIT’.

  • timeout: timeout in ms, default 3 ms.



453
454
455
# File 'lib/stardog.rb', line 453

def offline_db(dbname, strategy_op = 'WAIT', timeout = 3)
  http_request("PUT", "admin/databases/#{dbname}/offline", "application/json", {}, { "strategy" => strategy_op, "timeout" => timeout })
end

#online_db(dbname, strategy_op = 'WAIT') ⇒ Object

Sets database offline.

  • strategy_op: ‘WAIT’ | ‘NO_WAIT’, default ‘WAIT’.



459
460
461
# File 'lib/stardog.rb', line 459

def online_db(dbname, strategy_op = 'WAIT')
  http_request("PUT", "admin/databases/#{dbname}/online", "application/json", {}, { "strategy" => strategy_op })
end

#query(database, query, options = {}) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/stardog.rb', line 126

def query(database, query, options = {})
  base_uri = options[:base_uri]
  limit = options[:limit] 
  offset = options[:offset] 
  accept = options[:accept]

  accept_header = accept ? accept : 'application/sparql-results+json'
  options = {
    :query => query
  }

  options[:"base-uri"] = base_uri if base_uri
  options[:limit] = limit if limit
  options[:offset] = offset if offset

  http_request("GET", "#{database}/query", accept, options)
end

#query_explain(database, query, options = {}) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
# File 'lib/stardog.rb', line 177

def query_explain(database, query, options = {})
  base_uri = options[:base_uri]
  
  options = {
    :query => query
  }

  options[:"base-uri"] = base_uri if base_uri

  http_request("GET", "#{database}/explain", "text/plain", options)
end

#query_graph(database, query, base_uri, options) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/stardog.rb', line 159

def query_graph(database, query, base_uri, options)
  base_uri = options[:base_uri]
  limit = options[:limit] 
  offset = options[:offset] 
  accept = options[:accept]

  accept_header = accept ? accept : 'application/ld+json'
  options = {
    :query => query
  }

  options[:"base-uri"] = base_uri if base_uri
  options[:limit] = limit if limit
  options[:offset] = offset if offset

  http_request("GET", "#{database}/query", accept, options)
end

#query_in_transaction(database, txID, query, options = {}) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/stardog.rb', line 258

def query_in_transaction(database, txID, query, options = {})
  base_uri = options[:base_uri]
  limit = options[:limit] 
  offset = options[:offset] 
  accept = options[:accept]
  ask_request = options.delete(:ask)

  accept = 'text/boolean' if(ask_request)
  accept_header = accept ? accept : 'application/sparql-results+json'
  
  options = {
    :query => query
  }

  options["base-uri"] = base_uri if base_uri
  options[:limit] = limit if limit
  options[:offset] = offset if offset

  http_request("GET", "#{database}/#{txID}/query", accept_header, options, nil, (ask_request ? false: true))
end

#reasoning_explain(database, axioms, options = {}) ⇒ Object

Reasoning



320
321
322
323
324
325
326
327
328
329
330
# File 'lib/stardog.rb', line 320

def reasoning_explain(database, axioms, options = {})
  content_type = options[:content_type] || "text/plain"
  txID = options[:tx_id]

  url = "#{database}/reasoning"
  url = "#{url}/#{txID}" if txID

  url = "#{url}/explain"

  http_request("POST", url, "application/x-turtle", {}, axioms, false, content_type)
end

#remove(database, body, graph_uri = nil, content_type = "text/plain") ⇒ Object



152
153
154
155
156
157
# File 'lib/stardog.rb', line 152

def remove(database, body, graph_uri=nil, content_type="text/plain")
  with_transaction(database) do |txId|
    result = remove_in_transaction(database, txId, body, graph_uri, content_type)
    raise Exception.new("Error removing data to database #{database} -> #{result.body}") unless(result.success?)
  end
end

#remove_icv(database, body, content_type = "text/plain") ⇒ Object



360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/stardog.rb', line 360

def remove_icv(database, body, content_type = "text/plain")
  if(File.exists?(body))
    body = File.open(body,"r").read
  elsif(body =~ /^https?:\/\/[\S]+$/)
    result = http_request("GET", body, (content_type == "text/plain" ? "*/*" : content_type), {}, nil, false)
    raise Exception.new("Error adding data from remote URL #{body} => #{result.status} : #{result}") if result.status != 200
    body = result.body
  end

  is_json =  (content_type.index("json") ? true : false)
  http_request("POST", "#{database}/icv/remove", "*/*", {}, body, is_json, content_type, nil)
end

#remove_in_transaction(database, txID, body, graph_uri = nil, content_type = "text/plain") ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/stardog.rb', line 294

def remove_in_transaction(database, txID, body, graph_uri=nil, content_type="text/plain")
  options = nil
  options = {"graph-uri" => graph_uri} if graph_uri

  if(File.exists?(body))
    body = File.open(body,"r").read
  elsif(body =~ /^https?:\/\/[\S]+$/)
    result = http_request("GET", body, (content_type == "text/plain" ? "*/*" : content_type), {}, nil, false)
    raise Exception.new("Error adding data from remote URL #{body} => #{result.status} : #{result}") if result.status != 200
    body = result.body
  end

  http_request("POST", "#{database}/#{txID}/remove", "text/plain", options, body, false, content_type, nil)
end

#rollback(database, txID) ⇒ Object



207
208
209
# File 'lib/stardog.rb', line 207

def rollback(database, txID)
  http_request("POST", "#{database}/transaction/rollback/#{txID}", "text/plain", "")
end

#set_credentials(username, password) ⇒ Object



101
102
103
# File 'lib/stardog.rb', line 101

def set_credentials(username, password)
  @credentials = {:user => username, :password => password}
end

#set_db_options(db_name, options) ⇒ Object

Set properties for a DB. options and values must be passed as the second argument to the method. DB must be offline before being setting the new values. The lis of properties can be found here: stardog.com/docs/admin/#admin-db

  • db_name

  • options: hash with properties and values.



412
413
414
# File 'lib/stardog.rb', line 412

def set_db_options(db_name, options)
  http_request("POST", "admin/databases/#{db_name}/options", "application/json", {}, options)
end

#shutdown_serverObject



472
473
474
# File 'lib/stardog.rb', line 472

def shutdown_server()
  http_request("POST", "admin/shutdown", "application/json")
end

#with_transaction(db_name) ⇒ Object

Initiates a transaction and handles the commit or rollback of it. if an exception is raised the transaction will be committed. It accepts a block that will receive a transaction ID as argument.

  • db_name

  • transaction block



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/stardog.rb', line 216

def with_transaction(db_name)
  begin
    txID = self.begin(db_name)
    yield txID
    result = commit(db_name,txID)
    raise ICVException.new("ICV constraing violated") if(!result.success? && result.body.index("IC validation failed"))
    result.success? || false
  rescue ICVException => ex
    debug "* Error in commit due to ICV constraint violation. Transaction has already be rolled back"
    raise ex
  rescue Exception => ex
    debug "* Error in transaction #{txID}"
    debug ex.message
    debug ex.backtrace.join("\n")
    rollback(db_name, txID)
    raise ex
  end
end