@@ -12,33 +12,47 @@ def self.default
1212 @default ||= new ( Neo4j ::Http . config )
1313 end
1414
15- def initialize ( configuration )
15+ def initialize ( configuration , injected_connection = nil )
1616 @configuration = configuration
17+ @injected_connection = injected_connection
1718 end
1819
20+ # Executes a cypher query, passing in the cypher statement, with parameters as an optional hash
21+ # e.g. Neo4j::Http::Cypherclient.execute_cypher("MATCH (n { foo: $foo }) LIMIT 1 RETURN n", { foo: "bar" })
1922 def execute_cypher ( cypher , parameters = { } )
23+ # By default the access mode is set to "WRITE", but can be set to "READ"
24+ # for improved routing performance on read only queries
25+ access_mode = parameters . delete ( :access_mode ) || @configuration . access_mode
26+
2027 request_body = {
2128 statements : [
22- { statement : cypher ,
23- parameters : parameters . as_json }
29+ {
30+ statement : cypher ,
31+ parameters : parameters . as_json
32+ }
2433 ]
2534 }
2635
27- response = connection . post ( transaction_path , request_body )
36+ @connection = @injected_connection || connection ( access_mode )
37+ response = @connection . post ( transaction_path , request_body )
2838 results = check_errors! ( cypher , response , parameters )
2939
3040 Neo4j ::Http ::Results . parse ( results &.first || { } )
3141 end
3242
33- def connection
34- build_connection
43+ def connection ( access_mode )
44+ build_connection ( access_mode )
3545 end
3646
3747 protected
3848
3949 delegate :auth_token , :transaction_path , to : :@configuration
4050 def check_errors! ( cypher , response , parameters )
4151 raise Neo4j ::Http ::Errors ::InvalidConnectionUrl , response . status if response . status == 404
52+ if response . body [ "errors" ] . any? { |error | error [ "message" ] [ /Routing WRITE queries is not supported/ ] }
53+ raise Neo4j ::Http ::Errors ::ReadOnlyError
54+ end
55+
4256 body = response . body || { }
4357 errors = body . fetch ( "errors" , [ ] )
4458 return body . fetch ( "results" , { } ) unless errors . present?
@@ -61,8 +75,10 @@ def find_error_class(code)
6175 Neo4j ::Http ::Errors ::Neo4jCodedError
6276 end
6377
64- def build_connection
65- Faraday . new ( url : @configuration . uri , headers : build_http_headers , request : build_request_options ) do |f |
78+ def build_connection ( access_mode )
79+ # https://neo4j.com/docs/http-api/current/actions/transaction-configuration/
80+ headers = build_http_headers . merge ( { "access-mode" => access_mode } )
81+ Faraday . new ( url : @configuration . uri , headers : headers , request : build_request_options ) do |f |
6682 f . request :json # encode req bodies as JSON
6783 f . request :retry # retry transient failures
6884 f . response :json # decode response bodies as JSON
0 commit comments