Class: Neo4j::Server::CypherSession

Inherits:
Neo4j::Session show all
Includes:
Core::CypherTranslator, Resource
Defined in:
lib/neo4j-server/cypher_session.rb

Constant Summary

Constants included from Core::CypherTranslator

Core::CypherTranslator::EMPTY_PROPS, Core::CypherTranslator::SANITIZE_ESCAPED_REGEXP

Instance Attribute Summary collapse

Attributes included from Resource

#resource_data, #resource_url

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Core::CypherTranslator

#create_escape_value, #cypher_prop_list, #cypher_string, #escape_quotes, #escape_value, #label_string, #prop_identifier, #sanitize_escape_sequences, sanitized_column_names, translate_response

Methods included from Resource

#convert_from_json_value, #expect_response_code, #handle_response_error, #init_resource_data, #resource_headers, #resource_url_id, #response_exception, #wrap_resource

Methods inherited from Neo4j::Session

_listeners, _notify_listeners, add_listener, #auto_commit?, create_session, current, current!, inspect, named, on_session_available, open_named, query, register, register_db, #running, set_current, #shutdown, #start, unregister, user_agent_string

Constructor Details

#initialize(data_url, connection) ⇒ CypherSession

Returns a new instance of CypherSession.



15
16
17
18
19
20
# File 'lib/neo4j-server/cypher_session.rb', line 15

def initialize(data_url, connection)
  @connection = connection
  Neo4j::Session.register(self)
  initialize_resource(data_url)
  Neo4j::Session._notify_listeners(:session_available, self)
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



13
14
15
# File 'lib/neo4j-server/cypher_session.rb', line 13

def connection
  @connection
end

Class Method Details

.create_connection(params) ⇒ Faraday

Parameters:

  • params (Hash)

    could be empty or contain basic authentication user and password

Returns:

  • (Faraday)

See Also:



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/neo4j-server/cypher_session.rb', line 25

def self.create_connection(params)
  init_params = params[:initialize] && params.delete(:initialize)
  conn = Faraday.new(init_params) do |b|
    b.request :basic_auth, params[:basic_auth][:username], params[:basic_auth][:password] if params[:basic_auth]
    b.request :json
    # b.response :logger
    b.response :json, content_type: 'application/json'
    # b.use Faraday::Response::RaiseError
    b.use Faraday::Adapter::NetHttpPersistent
    # b.adapter  Faraday.default_adapter
  end
  conn.headers = {'Content-Type' => 'application/json', 'User-Agent' => ::Neo4j::Session.user_agent_string}
  conn
end

.establish_session(root_data, connection) ⇒ Object



54
55
56
57
58
# File 'lib/neo4j-server/cypher_session.rb', line 54

def self.establish_session(root_data, connection)
  data_url = root_data['data']
  data_url << '/' unless data_url.nil? || data_url.end_with?('/')
  CypherSession.new(data_url, connection)
end

.open(endpoint_url = nil, params = {}) ⇒ Object

Opens a session to the database

Parameters:

  • endpoint_url (String) (defaults to: nil)
  • params (Hash) (defaults to: {})

    faraday params, see #create_connection or an already created faraday connection

See Also:

  • Neo4j::Session#open


45
46
47
48
49
50
51
52
# File 'lib/neo4j-server/cypher_session.rb', line 45

def self.open(endpoint_url = nil, params = {})
  extract_basic_auth(endpoint_url, params)
  connection = params[:connection] || create_connection(params)
  url = endpoint_url || 'http://localhost:7474'
  response = connection.get(url)
  fail "Server not available on #{url} (response code #{response.status})" unless response.status == 200
  establish_session(response.body, connection)
end

Instance Method Details

#_query(q, params = nil) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/neo4j-server/cypher_session.rb', line 204

def _query(q, params = nil)
  # puts "q #{q}"
  curr_tx = Neo4j::Transaction.current
  if curr_tx
    curr_tx._query(q, params)
  else
    url = resource_url('cypher')
    q = params.nil? ? {'query' => q} : {'query' => q, 'params' => params}
    response = @connection.post(url, q)
    CypherResponse.create_with_no_tx(response)
  end
end

#_query_data(q) ⇒ Object



186
187
188
189
190
# File 'lib/neo4j-server/cypher_session.rb', line 186

def _query_data(q)
  r = _query_or_fail(q, true)
  # the response is different if we have a transaction or not
  Neo4j::Transaction.current ? r : r['data']
end

#_query_entity_data(q, id = nil, params = nil) ⇒ Object



198
199
200
201
202
# File 'lib/neo4j-server/cypher_session.rb', line 198

def _query_entity_data(q, id = nil, params = nil)
  response = _query(q, params)
  response.raise_error if response.error?
  response.entity_data(id)
end

#_query_or_fail(q, single_row = false, params = nil) ⇒ Object



192
193
194
195
196
# File 'lib/neo4j-server/cypher_session.rb', line 192

def _query_or_fail(q, single_row = false, params = nil)
  response = _query(q, params)
  response.raise_error if response.error?
  single_row ? response.first_data : response
end

#begin_txObject



100
101
102
103
104
105
106
107
108
# File 'lib/neo4j-server/cypher_session.rb', line 100

def begin_tx
  if Neo4j::Transaction.current
    # Handle nested transaction "placebo transaction"
    Neo4j::Transaction.current.push_nested!
  else
    wrap_resource(@connection)
  end
  Neo4j::Transaction.current
end

#closeObject



95
96
97
98
# File 'lib/neo4j-server/cypher_session.rb', line 95

def close
  super
  Neo4j::Transaction.unregister_current
end

#create_label(name) ⇒ Object



141
142
143
# File 'lib/neo4j-server/cypher_session.rb', line 141

def create_label(name)
  CypherLabel.new(self, name)
end

#create_node(props = nil, labels = []) ⇒ Object



110
111
112
113
114
# File 'lib/neo4j-server/cypher_session.rb', line 110

def create_node(props = nil, labels = [])
  id = _query_or_fail(cypher_string(labels, props), true, cypher_prop_list(props))
  value = props.nil? ? id : {'id' => id, 'metadata' => {'labels' => labels}, 'data' => props}
  CypherNode.new(self, value)
end

#db_typeObject



70
71
72
# File 'lib/neo4j-server/cypher_session.rb', line 70

def db_type
  :server_db
end

#find_all_nodes(label_name) ⇒ Object



159
160
161
# File 'lib/neo4j-server/cypher_session.rb', line 159

def find_all_nodes(label_name)
  search_result_to_enumerable_first_column(_query_or_fail("MATCH (n:`#{label_name}`) RETURN ID(n)"))
end

#find_nodes(label_name, key, value) ⇒ Object



163
164
165
166
167
168
169
170
171
172
# File 'lib/neo4j-server/cypher_session.rb', line 163

def find_nodes(label_name, key, value)
  value = "'#{value}'" if value.is_a? String

  response = _query_or_fail <<-CYPHER
    MATCH (n:`#{label_name}`)
    WHERE n.#{key} = #{value}
    RETURN ID(n)
  CYPHER
  search_result_to_enumerable_first_column(response)
end

#indexes(label) ⇒ Object



149
150
151
# File 'lib/neo4j-server/cypher_session.rb', line 149

def indexes(label)
  schema_properties("#{@resource_url}schema/index/#{label}")
end

#initialize_resource(data_url) ⇒ Object



86
87
88
89
90
91
92
93
# File 'lib/neo4j-server/cypher_session.rb', line 86

def initialize_resource(data_url)
  response = @connection.get(data_url)
  expect_response_code(response, 200)
  data_resource = response.body
  fail "No data_resource for #{response.body}" unless data_resource
  # store the resource data
  init_resource_data(data_resource, data_url)
end

#inspectObject



78
79
80
# File 'lib/neo4j-server/cypher_session.rb', line 78

def inspect
  "#{self} version: '#{version}'"
end

#load_entity(clazz, cypher_response) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/neo4j-server/cypher_session.rb', line 124

def load_entity(clazz, cypher_response)
  return nil if cypher_response.data.nil? || cypher_response.data[0].nil?
  data  = if cypher_response.transaction_response?
            cypher_response.rest_data_with_id
          else
            cypher_response.first_data
          end

  if cypher_response.error?
    cypher_response.raise_error
  elsif cypher_response.error_msg =~ /not found/  # Ugly that the Neo4j API gives us this error message
    return nil
  else
    clazz.new(self, data)
  end
end

#load_node(neo_id) ⇒ Object



116
117
118
# File 'lib/neo4j-server/cypher_session.rb', line 116

def load_node(neo_id)
  load_entity(CypherNode, _query("MATCH (n) WHERE ID(n) = #{neo_id} RETURN n"))
end

#load_relationship(neo_id) ⇒ Object



120
121
122
# File 'lib/neo4j-server/cypher_session.rb', line 120

def load_relationship(neo_id)
  load_entity(CypherRelationship, _query("MATCH (n)-[r]-() WHERE ID(r) = #{neo_id} RETURN r"))
end

#map_column(key, map, data) ⇒ Object



244
245
246
247
248
249
250
251
252
# File 'lib/neo4j-server/cypher_session.rb', line 244

def map_column(key, map, data)
  if map[key] == :node
    CypherNode.new(self, data).wrapper
  elsif map[key] == :rel || map[:key] || :relationship
    CypherRelationship.new(self, data)
  else
    data
  end
end

#query(*args) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
# File 'lib/neo4j-server/cypher_session.rb', line 174

def query(*args)
  if [[String], [String, Hash]].include?(args.map(&:class))
    query, params = args[0, 2]
    response = _query(query, params)
    response.raise_error if response.error?
    response.to_node_enumeration(query)
  else
    options = args[0] || {}
    Neo4j::Core::Query.new(options.merge(session: self))
  end
end

#schema_properties(query_string) ⇒ Object



153
154
155
156
157
# File 'lib/neo4j-server/cypher_session.rb', line 153

def schema_properties(query_string)
  response = @connection.get(query_string)
  expect_response_code(response, 200)
  {property_keys: response.body.map { |row| row['property_keys'].map(&:to_sym) }}
end

#search_result_to_enumerable_first_column(response) ⇒ Object



217
218
219
220
221
222
223
224
# File 'lib/neo4j-server/cypher_session.rb', line 217

def search_result_to_enumerable_first_column(response)
  return [] unless response.data
  if Neo4j::Transaction.current
    search_result_to_enumerable_first_column_with_tx(response)
  else
    search_result_to_enumerable_first_column_without_tx(response)
  end
end

#search_result_to_enumerable_first_column_with_tx(response) ⇒ Object



226
227
228
229
230
231
232
233
234
# File 'lib/neo4j-server/cypher_session.rb', line 226

def search_result_to_enumerable_first_column_with_tx(response)
  Enumerator.new do |yielder|
    response.data.each do |data|
      data['row'].each do |id|
        yielder << CypherNode.new(self, id).wrapper
      end
    end
  end
end

#search_result_to_enumerable_first_column_without_tx(response) ⇒ Object



236
237
238
239
240
241
242
# File 'lib/neo4j-server/cypher_session.rb', line 236

def search_result_to_enumerable_first_column_without_tx(response)
  Enumerator.new do |yielder|
    response.data.each do |data|
      yielder << CypherNode.new(self, data[0]).wrapper
    end
  end
end

#super_queryObject



12
# File 'lib/neo4j-server/cypher_session.rb', line 12

alias_method :super_query, :query

#to_sObject



74
75
76
# File 'lib/neo4j-server/cypher_session.rb', line 74

def to_s
  "#{self.class} url: '#{@resource_url}'"
end

#uniqueness_constraints(label) ⇒ Object



145
146
147
# File 'lib/neo4j-server/cypher_session.rb', line 145

def uniqueness_constraints(label)
  schema_properties("#{@resource_url}schema/constraint/#{label}/uniqueness")
end

#versionObject



82
83
84
# File 'lib/neo4j-server/cypher_session.rb', line 82

def version
  resource_data ? resource_data['neo4j_version'] : ''
end