Class: Neo4j::Server::CypherSession

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

Constant Summary collapse

DEFAULT_RETRY_COUNT =
ENV['NEO4J_RETRY_COUNT'].nil? ? 10 : ENV['NEO4J_RETRY_COUNT'].to_i
EMPTY =
''

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?, clear_listeners, create_session, current, current!, inspect, named, on_session_available, query, register, register_db, #running, set_current, #shutdown, #start, unregister, user_agent_string, validate_session_num!

Constructor Details

#initialize(data_url, connection) ⇒ CypherSession

Returns a new instance of CypherSession.



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

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.



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

def connection
  @connection
end

Class Method Details

.create_connection(params, url = nil) ⇒ Faraday

Parameters:

  • params (Hash)

    could be empty or contain basic authentication user and password

Returns:

  • (Faraday)

See Also:



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

def self.create_connection(params, url = nil)
  init_params = params[:initialize] && params.delete(:initialize)
  conn = Faraday.new(url, init_params) do |b|
    b.request :basic_auth, params[:basic_auth][:username], params[:basic_auth][:password] if params[:basic_auth]
    b.request :multi_json
    # b.response :logger

    b.response :multi_json, symbolize_keys: true, 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

.log_withObject



238
239
240
241
242
243
244
245
# File 'lib/neo4j-server/cypher_session.rb', line 238

def self.log_with
  clear, yellow, cyan = %W(\e[0m \e[33m \e[36m)
  ActiveSupport::Notifications.subscribe('neo4j.cypher_query') do |_, start, finish, _id, payload|
    ms = (finish - start) * 1000
    params_string = (payload[:params].size > 0 ? "| #{payload[:params].inspect}" : EMPTY)
    yield(" #{cyan}#{payload[:context]}#{clear} #{yellow}#{ms.round}ms#{clear} #{payload[:cypher]} #{params_string}")
  end
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)
  url = endpoint_url || 'http://localhost:7474'
  connection = params[:connection] || create_connection(params, url)
  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(query, params = {}) ⇒ Object



207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/neo4j-server/cypher_session.rb', line 207

def _query(query, params = {})
  query, params = query_and_params(query, params)

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

#_query_data(query) ⇒ Object



165
166
167
168
# File 'lib/neo4j-server/cypher_session.rb', line 165

def _query_data(query)
  r = _query_or_fail(query, true)
  Neo4j::Transaction.current ? r : r[:data]
end

#_query_entity_data(query, id = nil, params = {}) ⇒ Object



197
198
199
# File 'lib/neo4j-server/cypher_session.rb', line 197

def _query_entity_data(query, id = nil, params = {})
  _query_response(query, params).entity_data(id)
end

#_query_or_fail(query, single_row = false, params = {}, retry_count = DEFAULT_RETRY_COUNT) ⇒ Object



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

def _query_or_fail(query, single_row = false, params = {}, retry_count = DEFAULT_RETRY_COUNT)
  query, params = query_and_params(query, params)

  response = _query(query, params)
  if response.error?
    _retry_or_raise(query, params, single_row, retry_count, response)
  else
    single_row ? response.first_data : response
  end
end

#_query_response(query, params = {}) ⇒ Object



201
202
203
204
205
# File 'lib/neo4j-server/cypher_session.rb', line 201

def _query_response(query, params = {})
  _query(query, params).tap do |response|
    response.raise_error if response.error?
  end
end

#_retry_or_raise(query, params, single_row, retry_count, response) ⇒ Object



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

def _retry_or_raise(query, params, single_row, retry_count, response)
  response.raise_error unless response.retryable_error?
  retry_count > 0 ? _query_or_fail(query, single_row, params, retry_count - 1) : response.raise_error
end

#begin_txObject



97
98
99
100
# File 'lib/neo4j-server/cypher_session.rb', line 97

def begin_tx
  Neo4j::Transaction.current ? Neo4j::Transaction.current.push_nested! : wrap_resource(@connection)
  Neo4j::Transaction.current
end

#closeObject



92
93
94
95
# File 'lib/neo4j-server/cypher_session.rb', line 92

def close
  super
  Neo4j::Transaction.unregister_current
end

#create_label(name) ⇒ Object



122
123
124
# File 'lib/neo4j-server/cypher_session.rb', line 122

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

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



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

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



67
68
69
# File 'lib/neo4j-server/cypher_session.rb', line 67

def db_type
  :server_db
end

#find_all_nodes(label_name) ⇒ Object



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

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



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

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

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

#indexes(label) ⇒ Object



130
131
132
# File 'lib/neo4j-server/cypher_session.rb', line 130

def indexes(label)
  schema_properties("/db/data/schema/index/#{label}")
end

#initialize_resource(data_url) ⇒ Object



83
84
85
86
87
88
89
90
# File 'lib/neo4j-server/cypher_session.rb', line 83

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



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

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

#load_node(neo_id) ⇒ Object



108
109
110
# File 'lib/neo4j-server/cypher_session.rb', line 108

def load_node(neo_id)
  query.unwrapped.match(:n).where(n: {neo_id: neo_id}).pluck(:n).first
end

#load_relationship(neo_id) ⇒ Object



112
113
114
115
116
117
118
119
120
# File 'lib/neo4j-server/cypher_session.rb', line 112

def load_relationship(neo_id)
  query.unwrapped.optional_match('(n)-[r]-()').where(r: {neo_id: neo_id}).pluck(:r).first
rescue Neo4j::Session::CypherError => cypher_error
  if cypher_error.message.match(/not found$/)
    nil
  else
    raise cypher_error
  end
end

#query(*args) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/neo4j-server/cypher_session.rb', line 151

def query(*args)
  if [[String], [String, Hash]].include?(args.map(&:class))
    query = args[0]
    params = args[1]

    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

#query_and_params(query_or_query_string, params) ⇒ Object



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

def query_and_params(query_or_query_string, params)
  if query_or_query_string.is_a?(::Neo4j::Core::Query)
    cypher = query_or_query_string.to_cypher
    [cypher, query_or_query_string.send(:merge_params).merge(params)]
  else
    [query_or_query_string, params]
  end
end

#schema_properties(query_string) ⇒ Object



134
135
136
137
138
# File 'lib/neo4j-server/cypher_session.rb', line 134

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



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/neo4j-server/cypher_session.rb', line 221

def search_result_to_enumerable_first_column(response)
  return [] unless response.data

  Enumerator.new do |yielder|
    response.data.each do |data|
      if Neo4j::Transaction.current
        data[:row].each do |id|
          yielder << CypherNode.new(self, id).wrapper
        end
      else
        yielder << CypherNode.new(self, data[0]).wrapper
      end
    end
  end
end

#super_queryObject



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

alias_method :super_query, :query

#to_sObject



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

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

#uniqueness_constraints(label) ⇒ Object



126
127
128
# File 'lib/neo4j-server/cypher_session.rb', line 126

def uniqueness_constraints(label)
  schema_properties("/db/data/schema/constraint/#{label}/uniqueness")
end

#versionObject



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

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