Class: SPARQL::Client

Inherits:
Object show all
Defined in:
vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb,
vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client/query.rb,
vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client/update.rb,
vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client/version.rb,
vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client/repository.rb

Overview

A SPARQL 1.0/1.1 client for RDF.rb.

Defined Under Namespace

Modules: Update, VERSION Classes: ClientError, MalformedQuery, Query, QueryElement, Repository, ServerError

Constant Summary collapse

RESULT_JSON =
'application/sparql-results+json'.freeze
RESULT_XML =
'application/sparql-results+xml'.freeze
RESULT_CSV =
'text/csv'.freeze
RESULT_TSV =
'text/tab-separated-values'.freeze
RESULT_BOOL =

Sesame-specific

'text/boolean'.freeze
RESULT_BRTR =

Sesame-specific

'application/x-binary-rdf-results-table'.freeze
RESULT_ALL =
[
  RESULT_JSON,
  RESULT_XML,
  RESULT_BOOL,
  "#{RESULT_TSV};q=0.8",
  "#{RESULT_CSV};q=0.2",
  '*/*;q=0.1'
].join(', ').freeze
GRAPH_ALL =
(
  RDF::Format.content_types.keys +
  ['*/*;q=0.1']
).join(', ').freeze
ACCEPT_JSON =
{'Accept' => RESULT_JSON}.freeze
ACCEPT_XML =
{'Accept' => RESULT_XML}.freeze
ACCEPT_CSV =
{'Accept' => RESULT_CSV}.freeze
ACCEPT_TSV =
{'Accept' => RESULT_TSV}.freeze
ACCEPT_BRTR =
{'Accept' => RESULT_BRTR}.freeze
ACCEPT_RESULTS =
{'Accept' => RESULT_ALL}.freeze
ACCEPT_GRAPH =
{'Accept' => GRAPH_ALL}.freeze
DEFAULT_PROTOCOL =
1.0
DEFAULT_METHOD =
:post
XMLNS =
{'sparql' => 'http://www.w3.org/2005/sparql-results#'}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, **options, &block) ⇒ Client

Initialize a new sparql client, either using the URL of a SPARQL endpoint or an RDF::Queryable instance to use the native SPARQL gem.

Parameters:

Options Hash (**options):

  • :method (Symbol) — default: DEFAULT_METHOD
  • :protocol (Number) — default: DEFAULT_PROTOCOL
  • :headers (Hash)

    HTTP Request headers

    Defaults Accept header based on available reader content types if triples are expected and to SPARQL result types otherwise, to allow for content negotiation based on available readers.

    Defaults User-Agent header, unless one is specified.

  • :read_timeout (Hash)


95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 95

def initialize(url, **options, &block)
  case url
  when RDF::Queryable
    @url, @options = url, options.dup
  else
    @url, @options = RDF::URI.new(url.to_s), options.dup
    @headers = @options.delete(:headers) || {}
    @http = http_klass(@url.scheme)

    # Close the http connection when object is deallocated
    ObjectSpace.define_finalizer(self, self.class.finalize(@http))
  end

  if block_given?
    case block.arity
      when 1 then block.call(self)
      else instance_eval(&block)
    end
  end
end

Instance Attribute Details

#headersHash{String => String} (readonly)

The HTTP headers that will be sent in requests to the endpoint.

Returns:



70
71
72
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 70

def headers
  @headers
end

#optionsHash{Symbol => Object} (readonly)

Any miscellaneous configuration.

Returns:



76
77
78
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 76

def options
  @options
end

#urlRDF::URI, RDF::Queryable (readonly)

The SPARQL endpoint URL, or an RDF::Queryable instance, to use the native SPARQL engine.

Returns:



64
65
66
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 64

def url
  @url
end

Class Method Details

.finalize(klass) ⇒ Object

Close the http connection when object is deallocated



117
118
119
120
121
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 117

def self.finalize(klass)
  proc do
    klass.shutdown if klass.respond_to?(:shutdown)
  end
end

.parse_csv_bindings(csv, nodes = {}) ⇒ <RDF::Query::Solutions>



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 458

def self.parse_csv_bindings(csv, nodes = {})
  require 'csv' unless defined?(::CSV)
  csv = CSV.parse(csv.to_s) unless csv.is_a?(Array)
  vars = csv.shift
  solutions = RDF::Query::Solutions.new
  csv.each do |row|
    solution = RDF::Query::Solution.new
    row.each_with_index do |v, i|
      term = case v
      when /^_:(.*)$/ then nodes[$1] ||= RDF::Node($1)
      when /^\w+:.*$/ then RDF::URI(v)
      else RDF::Literal(v)
      end
      solution[vars[i].to_sym] = term
    end
    solutions << solution
  end
  solutions
end

.parse_json_bindings(json, nodes = {}) ⇒ <RDF::Query::Solutions>



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 413

def self.parse_json_bindings(json, nodes = {})
  require 'json' unless defined?(::JSON)
  json = JSON.parse(json.to_s) unless json.is_a?(Hash)
  case
    when json.has_key?('boolean')
      json['boolean']
    when json.has_key?('results')
      solutions = json['results']['bindings'].map do |row|
        row = row.inject({}) do |cols, (name, value)|
          cols.merge(name.to_sym => parse_json_value(value, nodes))
        end
        RDF::Query::Solution.new(row)
      end
      RDF::Query::Solutions.new(solutions)
  end
end

.parse_json_value(value, nodes = {}) ⇒ RDF::Value



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 435

def self.parse_json_value(value, nodes = {})
  case value['type'].to_sym
    when :bnode
      nodes[id = value['value']] ||= RDF::Node.new(id)
    when :uri
      RDF::URI.new(value['value'])
    when :literal
      RDF::Literal.new(value['value'], datatype: value['datatype'], language: value['xml:lang'])
    when :'typed-literal'
      RDF::Literal.new(value['value'], datatype: value['datatype'])
    when :triple
      s = parse_json_value(value['value']['subject'], nodes)
      p = parse_json_value(value['value']['predicate'], nodes)
      o = parse_json_value(value['value']['object'], nodes)
      RDF::Statement(s, p, o)
    else nil
  end
end

.parse_tsv_bindings(tsv, nodes = {}) ⇒ <RDF::Query::Solutions>



482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 482

def self.parse_tsv_bindings(tsv, nodes = {})
  tsv = tsv.lines.map {|l| l.chomp.split("\t")} unless tsv.is_a?(Array)
  vars = tsv.shift.map {|h| h.sub(/^\?/, '')}
  solutions = RDF::Query::Solutions.new
  tsv.each do |row|
    solution = RDF::Query::Solution.new
    row.each_with_index do |v, i|
      if !v.empty?
        term = RDF::NTriples.unserialize(v) || case v
        when /^\d+\.\d*[eE][+-]?[0-9]+$/  then RDF::Literal::Double.new(v)
        when /^\d*\.\d+[eE][+-]?[0-9]+$/  then RDF::Literal::Double.new(v)
        when /^\d*\.\d+$/                 then RDF::Literal::Decimal.new(v)
        when /^\d+$/                      then RDF::Literal::Integer.new(v)
        else
          RDF::Literal(v)
        end
        nodes[term.id] = term if term.is_a? RDF::Node
        solution[vars[i].to_sym] = term
      end
    end
    solutions << solution
  end
  solutions
end

.parse_xml_bindings(xml, nodes = {}) ⇒ <RDF::Query::Solutions>



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
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 511

def self.parse_xml_bindings(xml, nodes = {})
  xml.force_encoding(::Encoding::UTF_8) if xml.respond_to?(:force_encoding)

  if defined?(::Nokogiri)
    xml = Nokogiri::XML(xml).root unless xml.is_a?(Nokogiri::XML::Document)
    case
      when boolean = xml.xpath("//sparql:boolean", XMLNS)[0]
        boolean.text == 'true'
      when results = xml.xpath("//sparql:results", XMLNS)[0]
        solutions = results.elements.map do |result|
          row = {}
          result.elements.each do |binding|
            name  = binding.attr('name').to_sym
            value = binding.elements.first
            row[name] = parse_xml_value(value, nodes)
          end
          RDF::Query::Solution.new(row)
        end
        RDF::Query::Solutions.new(solutions)
    end
  else
    # REXML
    xml = REXML::Document.new(xml).root unless xml.is_a?(REXML::Element)
    case
      when boolean = xml.elements['boolean']
        boolean.text == 'true'
      when results = xml.elements['results']
        solutions = results.elements.map do |result|
          row = {}
          result.elements.each do |binding|
            name  = binding.attributes['name'].to_sym
            value = binding.select { |node| node.kind_of?(::REXML::Element) }.first
            row[name] = parse_xml_value(value, nodes)
          end
          RDF::Query::Solution.new(row)
        end
        RDF::Query::Solutions.new(solutions)
    end
  end
end

.parse_xml_value(value, nodes = {}) ⇒ RDF::Value



556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 556

def self.parse_xml_value(value, nodes = {})
  case value.name.to_sym
    when :bnode
      nodes[id = value.text] ||= RDF::Node.new(id)
    when :uri
      RDF::URI.new(value.text)
    when :literal
      lang     = value.respond_to?(:attr) ? value.attr('xml:lang') : value.attributes['xml:lang']
      datatype = value.respond_to?(:attr) ? value.attr('datatype') : value.attributes['datatype']
      RDF::Literal.new(value.text, language: lang, datatype: datatype)
    when :triple
      # Note, this is order dependent
      res = value.elements.map {|e| e.elements.to_a}.
        flatten.map {|e| parse_xml_value(e, nodes)}
      RDF::Statement(*res)
    else nil
  end
end

Instance Method Details

#ask(*args, **options) ⇒ Query

Executes a boolean ASK query.

Parameters:

Returns:



138
139
140
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 138

def ask(*args, **options)
  call_query_method(:ask, *args, **options)
end

#clear(what, *arguments) #clear(what, *arguments, **options)

Executes a CLEAR operation.

This requires that the endpoint support SPARQL 1.1 Update.

Examples:

CLEAR GRAPH <http://example.org/>

client.clear(:graph, RDF::URI("http://example.org/"))

CLEAR DEFAULT

client.clear(:default)

CLEAR NAMED

client.clear(:named)

CLEAR ALL

client.clear(:all)

Overloads:

See Also:



285
286
287
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 285

def clear(what, *arguments)
  self.update(Update::Clear.new(what, *arguments))
end

#clear_graph(graph_uri, **options)

This method returns an undefined value.

Executes a CLEAR GRAPH operation.

This is a convenience wrapper for the #clear method.

Examples:

CLEAR GRAPH <http://example.org/>

client.clear_graph("http://example.org/")

Parameters:

Options Hash (**options):

  • :silent (Boolean)

See Also:



250
251
252
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 250

def clear_graph(graph_uri, **options)
  self.clear(:graph, graph_uri, **options)
end

#close

This method returns an undefined value.

Closes a client instance by finishing the connection. The client is unavailable for any further data operations; an IOError is raised if such an attempt is made. I/O streams are automatically closed when they are claimed by the garbage collector.



127
128
129
130
131
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 127

def close
  @http.shutdown if @http
  @http = nil
  self
end

#construct(*args, **options) ⇒ Query

Executes a graph CONSTRUCT query.

Parameters:

Returns:



165
166
167
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 165

def construct(*args, **options)
  call_query_method(:construct, *args, **options)
end

#delete_data(data, **options)

This method returns an undefined value.

Executes a DELETE DATA operation.

This requires that the endpoint support SPARQL 1.1 Update.

Examples:

Deleting data sourced from a file or URL

data = RDF::Graph.load("https://raw.githubusercontent.com/ruby-rdf/rdf/develop/etc/doap.nt")
client.delete_data(data)

Deleting data from a named graph

client.delete_data(data, graph: "http://example.org/")

Parameters:

Options Hash (**options):

See Also:



217
218
219
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 217

def delete_data(data, **options)
  self.update(Update::DeleteData.new(data, **options))
end

#delete_insert(delete_graph, insert_graph = nil, where_graph = nil, **options)

This method returns an undefined value.

Executes a DELETE/INSERT operation.

This requires that the endpoint support SPARQL 1.1 Update.

Parameters:

Options Hash (**options):

See Also:



233
234
235
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 233

def delete_insert(delete_graph, insert_graph = nil, where_graph = nil, **options)
  self.update(Update::DeleteInsert.new(delete_graph, insert_graph, where_graph, **options))
end

#describe(*args, **options) ⇒ Query

Executes a DESCRIBE query.

Parameters:

Returns:



156
157
158
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 156

def describe(*args, **options)
  call_query_method(:describe, *args, **options)
end

#http_klass(scheme) ⇒ Net::HTTP::Proxy (protected)

Returns an HTTP class or HTTP proxy class based on the http_proxy and https_proxy environment variables.

Parameters:

Returns:

  • (Net::HTTP::Proxy)


689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 689

def http_klass(scheme)
  proxy_url = nil
  case scheme
    when 'http'
      value = ENV['http_proxy']
      proxy_url = URI.parse(value) unless value.nil? || value.empty?
    when 'https'
      value = ENV['https_proxy']
      proxy_url = URI.parse(value) unless value.nil? || value.empty?
  end
  klass = Net::HTTP::Persistent.new(name: self.class.to_s, proxy: proxy_url)
  klass.keep_alive =  @options[:keep_alive] || 120
  klass.read_timeout = @options[:read_timeout] || 60
  klass
end

#insert_data(data, **options)

This method returns an undefined value.

Executes an INSERT DATA operation.

This requires that the endpoint support SPARQL 1.1 Update.

Note that for inserting non-trivial amounts of data, you probably ought to consider using the RDF store's native bulk-loading facilities or APIs, as INSERT DATA operations entail comparably higher parsing overhead.

Examples:

Inserting data constructed ad-hoc

client.insert_data(RDF::Graph.new { |graph|
  graph << [:jhacker, RDF::Vocab::FOAF.name, "J. Random Hacker"]
})

Inserting data sourced from a file or URL

data = RDF::Graph.load("https://raw.githubusercontent.com/ruby-rdf/rdf/develop/etc/doap.nt")
client.insert_data(data)

Inserting data into a named graph

client.insert_data(data, graph: "http://example.org/")

Parameters:

Options Hash (**options):

See Also:



196
197
198
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 196

def insert_data(data, **options)
  self.update(Update::InsertData.new(data, **options))
end

#inspectString

Returns a developer-friendly representation of this object.

Returns:



677
678
679
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 677

def inspect
  sprintf("#<%s:%#0x(%s)>", self.class.name, __id__, url.to_s)
end

#inspect!

This method returns an undefined value.

Outputs a developer-friendly representation of this object to stderr.



669
670
671
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 669

def inspect!
  warn(inspect)
end

#make_get_request(query, headers = {}) ⇒ Net::HTTPRequest (protected)

Constructs an HTTP GET request according to the SPARQL Protocol.

Parameters:

Returns:

  • (Net::HTTPRequest)

See Also:



768
769
770
771
772
773
774
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 768

def make_get_request(query, headers = {})
  url = self.url.dup
  url.query_values = (url.query_values || {}).merge(query: query.to_s)
  set_url_default_graph url unless @options[:graph].nil?
  request = Net::HTTP::Get.new(url.request_uri, self.headers.merge(headers))
  request
end

#make_post_request(query, headers = {}) ⇒ Net::HTTPRequest (protected)

Constructs an HTTP POST request according to the SPARQL Protocol.

Parameters:

Returns:

  • (Net::HTTPRequest)

See Also:



784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 784

def make_post_request(query, headers = {})
  if @alt_endpoint.nil?
    url = self.url.dup
    set_url_default_graph url unless @options[:graph].nil?
    endpoint = url.request_uri
  else
    endpoint = @alt_endpoint
  end

  request = Net::HTTP::Post.new(endpoint, self.headers.merge(headers))
  case (self.options[:protocol] || DEFAULT_PROTOCOL).to_s
    when '1.1'
      request['Content-Type'] = 'application/sparql-' + (@op || :query).to_s
      request.body = query.to_s
    when '1.0'
      form_data = {(@op || :query) => query.to_s}
      form_data.merge!(
        {:'default-graph-uri' => @options[:graph]}
      ) if !@options[:graph].nil? && (@op.eql? :query)
      form_data.merge!(
        {:'using-graph-uri' => @options[:graph]}
      ) if !@options[:graph].nil? && (@op.eql? :update)
      request.set_form_data(form_data)
    else
      raise ArgumentError, "unknown SPARQL protocol version: #{self.options[:protocol].inspect}"
  end
  request
end

#parse_rdf_serialization(response, **options) ⇒ RDF::Enumerable

Parameters:

Returns:



579
580
581
582
583
584
585
586
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 579

def parse_rdf_serialization(response, **options)
  options = {content_type: response.content_type} unless options[:content_type]
  if reader = RDF::Reader.for(options)
    reader.new(response.body)
  else
    raise RDF::ReaderError, "no RDF reader was found for #{options}."
  end
end

#parse_response(response, **options) ⇒ Object

Parameters:

Returns:



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 390

def parse_response(response, **options)
  case options[:content_type] || response.content_type
    when NilClass
      response.body
    when RESULT_BOOL # Sesame-specific
      response.body == 'true'
    when RESULT_JSON
      self.class.parse_json_bindings(response.body, nodes)
    when RESULT_XML
      self.class.parse_xml_bindings(response.body, nodes)
    when RESULT_CSV
      self.class.parse_csv_bindings(response.body, nodes)
    when RESULT_TSV
      self.class.parse_tsv_bindings(response.body, nodes)
    else
      parse_rdf_serialization(response, **options)
  end
end

#query(query, **options) ⇒ Array<RDF::Query::Solution>

Executes a SPARQL query and returns the parsed results.

Parameters:

Options Hash (**options):

Returns:

Raises:

  • (IOError)

    if connection is closed

See Also:



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 318

def query(query, **options)
  @op = :query
  @alt_endpoint = options[:endpoint]
  case @url
  when RDF::Queryable
    require 'sparql' unless defined?(::SPARQL::Grammar)
    begin
      SPARQL.execute(query, @url, optimize: true, **options)
    rescue SPARQL::MalformedQuery
      $stderr.puts "error running #{query}: #{$!}"
      raise
    end
  else
    parse_response(response(query, **options), **options)
  end
end

#request(query, headers = {}) {|response| ... } ⇒ Net::HTTPResponse (protected)

Yields:

Yield Parameters:

  • response (Net::HTTPResponse)

Returns:

  • (Net::HTTPResponse)

Raises:

  • (IOError)

    if connection is closed

See Also:



720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 720

def request(query, headers = {}, &block)
  # Make sure an appropriate Accept header is present
  headers['Accept'] ||= if (query.respond_to?(:expects_statements?) ?
                            query.expects_statements? :
                            (query =~ /CONSTRUCT|DESCRIBE|DELETE|CLEAR/))
    GRAPH_ALL
  else
    RESULT_ALL
  end
  headers['User-Agent'] ||= "Ruby SPARQL::Client/#{SPARQL::Client::VERSION}"

  request = send("make_#{request_method(query)}_request", query, headers)

  request.basic_auth(url.user, url.password) if url.user && !url.user.empty?

  pre_http_hook(request) if respond_to?(:pre_http_hook)

  raise IOError, "Client has been closed" unless @http
  response = @http.request(::URI.parse(url.to_s), request)

  post_http_hook(response) if respond_to?(:post_http_hook)

  10.times do
    if response.kind_of? Net::HTTPRedirection
      response = @http.request(::URI.parse(response['location']), request)
    else
      return block_given? ? block.call(response) : response
    end
  end
  raise ServerError, "Infinite redirect at #{url}. Redirected more than 10 times."
end

#request_method(query) ⇒ Object (protected)

Return the HTTP verb for posting this request. this is useful if you need to override the HTTP verb based on the request being made. (e.g. Marmotta 3.3.0 requires GET for DELETE requests, but can accept POST for INSERT)



756
757
758
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 756

def request_method(query)
  (options[:method] || DEFAULT_METHOD).to_sym
end

#response(query, **options) ⇒ String

Executes a SPARQL query and returns the Net::HTTP::Response of the result.

Parameters:

Options Hash (**options):

Returns:

Raises:

  • (IOError)

    if connection is closed



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 369

def response(query, **options)
  headers = options[:headers] || @headers
  headers['Accept'] = options[:content_type] if options[:content_type]
  request(query, headers) do |response|
    case response
      when Net::HTTPBadRequest  # 400 Bad Request
        raise MalformedQuery.new(response.body + " Processing query #{query}")
      when Net::HTTPClientError # 4xx
        raise ClientError.new(response.body + " Processing query #{query}")
      when Net::HTTPServerError # 5xx
        raise ServerError.new(response.body + " Processing query #{query}")
      when Net::HTTPSuccess     # 2xx
        response
    end
  end
end

#select(*args, **options) ⇒ Query

Executes a tuple SELECT query.

Parameters:

Returns:



147
148
149
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 147

def select(*args, **options)
  call_query_method(:select, *args, **options)
end

#set_url_default_graph(url) ⇒ Object (protected)

Setup url query parameter to use a specified default graph



818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 818

def set_url_default_graph url
  if @options[:graph].is_a? Array
    graphs = @options[:graph].map {|graph|
      CGI::escape(graph)
    }
  else
    graphs = CGI::escape(@options[:graph])
  end
  case @op
  when :query
    url.query_values = (url.query_values || {})
      .merge(:'default-graph-uri' => graphs)
  when :update
    url.query_values = (url.query_values || {})
      .merge(:'using-graph-uri' => graphs)
  end
end

#update(query, **options)

This method returns an undefined value.

Executes a SPARQL update operation.

Parameters:

Options Hash (**options):

Raises:

  • (IOError)

    if connection is closed

See Also:



346
347
348
349
350
351
352
353
354
355
356
357
# File 'vendor/bundler/ruby/3.0.0/bundler/gems/sparql-client-39558059b9a6/lib/sparql/client.rb', line 346

def update(query, **options)
  @op = :update
  @alt_endpoint = options[:endpoint]
  case @url
  when RDF::Queryable
    require 'sparql' unless defined?(::SPARQL::Grammar)
    SPARQL.execute(query, @url, update: true, optimize: true, **options)
  else
    response(query, **options)
  end
  self
end