Skip to content

Commit 5a5b80a

Browse files
committed
Merge pull request #42 from neo4j/1.0-idiomatic-iteration
Idiomatic Iteration
2 parents 27c36d5 + c65d99b commit 5a5b80a

File tree

11 files changed

+186
-302
lines changed

11 files changed

+186
-302
lines changed

README.rst

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ Example Usage
2828
driver = GraphDatabase.driver("bolt://localhost")
2929
session = driver.session()
3030
session.run("CREATE (a:Person {name:'Bob'})")
31-
cursor = session.run("MATCH (a:Person) RETURN a.name AS name")
32-
while cursor.next()
33-
print(cursor["name"])
34-
cursor.close()
31+
result = session.run("MATCH (a:Person) RETURN a.name AS name")
32+
for record in result:
33+
print(record["name"])
34+
result.close()
3535
session.close()
3636
3737

docs/source/index.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ Session API
2626

2727
.. autofunction:: neo4j.v1.record
2828

29-
.. autoclass:: neo4j.v1.ResultCursor
29+
.. autoclass:: neo4j.v1.StatementResult
3030
:members:
3131

3232
.. autoclass:: neo4j.v1.ResultSummary

examples/test_examples.py

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ def test_minimal_working_example(self):
5353
session.run("CREATE (a:Person {name:'Arthur', title:'King'})", )
5454

5555
result = session.run("MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title")
56-
while result.next():
57-
print("%s %s" % (result["title"], result["name"]))
56+
for record in result:
57+
print("%s %s" % (record["title"], record["name"]))
5858

5959
session.close()
6060
# end::minimal-example[]
@@ -96,16 +96,18 @@ def test_statement(self):
9696
driver = GraphDatabase.driver("bolt://localhost", auth=auth_token)
9797
session = driver.session()
9898
# tag::statement[]
99-
session.run("CREATE (person:Person {name: {name}})", {"name": "Arthur"}).close()
99+
result = session.run("CREATE (person:Person {name: {name}})", {"name": "Arthur"})
100100
# end::statement[]
101+
result.discard()
101102
session.close()
102103

103104
def test_statement_without_parameters(self):
104105
driver = GraphDatabase.driver("bolt://localhost", auth=auth_token)
105106
session = driver.session()
106107
# tag::statement-without-parameters[]
107-
session.run("CREATE (person:Person {name: 'Arthur'})").close()
108+
result = session.run("CREATE (person:Person {name: 'Arthur'})")
108109
# end::statement-without-parameters[]
110+
result.discard()
109111
session.close()
110112

111113
def test_result_cursor(self):
@@ -116,8 +118,8 @@ def test_result_cursor(self):
116118
result = session.run("MATCH (tool:Tool) WHERE tool.name CONTAINS {term} "
117119
"RETURN tool.name", {"term": search_term})
118120
print("List of tools called %r:" % search_term)
119-
while result.next():
120-
print(result["tool.name"])
121+
for record in result:
122+
print(record["tool.name"])
121123
# end::result-cursor[]
122124
session.close()
123125

@@ -127,10 +129,10 @@ def test_cursor_nesting(self):
127129
# tag::retain-result-query[]
128130
result = session.run("MATCH (knight:Person:Knight) WHERE knight.castle = {castle} "
129131
"RETURN id(knight) AS knight_id", {"castle": "Camelot"})
130-
while result.next():
132+
for record in result:
131133
session.run("MATCH (knight) WHERE id(knight) = {id} "
132134
"MATCH (king:Person) WHERE king.name = {king} "
133-
"CREATE (knight)-[:DEFENDS]->(king)", {"id": result["knight_id"], "king": "Arthur"})
135+
"CREATE (knight)-[:DEFENDS]->(king)", {"id": record["knight_id"], "king": "Arthur"})
134136
# end::retain-result-query[]
135137
session.close()
136138

@@ -140,9 +142,8 @@ def test_result_retention(self):
140142
# tag::retain-result-process[]
141143
result = session.run("MATCH (knight:Person:Knight) WHERE knight.castle = {castle} "
142144
"RETURN id(knight) AS knight_id", {"castle": "Camelot"})
143-
id_records = list(result.stream())
144-
145-
for record in id_records:
145+
retained_result = list(result)
146+
for record in retained_result:
146147
session.run("MATCH (knight) WHERE id(knight) = {id} "
147148
"MATCH (king:Person) WHERE king.name = {king} "
148149
"CREATE (knight)-[:DEFENDS]->(king)", {"id": record["knight_id"], "king": "Arthur"})
@@ -158,9 +159,8 @@ def test_transaction_commit(self):
158159
tx.commit()
159160
# end::transaction-commit[]
160161
result = session.run("MATCH (p:Person {name: 'Guinevere'}) RETURN count(p)")
161-
assert result.next()
162-
assert result["count(p)"] == 1
163-
assert result.at_end
162+
record = next(result)
163+
assert record["count(p)"] == 1
164164
session.close()
165165

166166
def test_transaction_rollback(self):
@@ -172,9 +172,8 @@ def test_transaction_rollback(self):
172172
tx.rollback()
173173
# end::transaction-rollback[]
174174
result = session.run("MATCH (p:Person {name: 'Merlin'}) RETURN count(p)")
175-
assert result.next()
176-
assert result["count(p)"] == 0
177-
assert result.at_end
175+
record = next(result)
176+
assert record["count(p)"] == 0
178177
session.close()
179178

180179
def test_result_summary_query_profile(self):
@@ -183,8 +182,7 @@ def test_result_summary_query_profile(self):
183182
# tag::result-summary-query-profile[]
184183
result = session.run("PROFILE MATCH (p:Person {name: {name}}) "
185184
"RETURN id(p)", {"name": "Arthur"})
186-
while result.next():
187-
pass # skip the records to get to the summary
185+
list(result) # skip the records to get to the summary
188186
print(result.summary.statement_type)
189187
print(result.summary.profile)
190188
# end::result-summary-query-profile[]
@@ -195,8 +193,7 @@ def test_result_summary_notifications(self):
195193
session = driver.session()
196194
# tag::result-summary-notifications[]
197195
result = session.run("EXPLAIN MATCH (king), (queen) RETURN king, queen")
198-
while result.next():
199-
pass # skip the records to get to the summary
196+
list(result) # skip the records to get to the summary
200197
for notification in result.summary.notifications:
201198
print(notification)
202199
# end::result-summary-notifications[]

neo4j/__main__.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,19 +27,21 @@
2727
from sys import stdout, stderr
2828

2929
from .util import Watcher
30-
from .v1.session import GraphDatabase, CypherError
30+
from .v1.session import GraphDatabase, CypherError, basic_auth
3131

3232

3333
def main():
3434
parser = ArgumentParser(description="Execute one or more Cypher statements using Bolt.")
3535
parser.add_argument("statement", nargs="+")
36-
parser.add_argument("-u", "--url", default="bolt://localhost", metavar="CONNECTION_URL")
36+
parser.add_argument("-k", "--keys", action="store_true")
37+
parser.add_argument("-P", "--password")
3738
parser.add_argument("-p", "--parameter", action="append", metavar="NAME=VALUE")
3839
parser.add_argument("-q", "--quiet", action="store_true")
39-
parser.add_argument("-s", "--secure", action="store_true")
40+
parser.add_argument("-U", "--user", default="neo4j")
41+
parser.add_argument("-u", "--url", default="bolt://localhost", metavar="CONNECTION_URL")
4042
parser.add_argument("-v", "--verbose", action="count")
4143
parser.add_argument("-x", "--times", type=int, default=1)
42-
parser.add_argument("-z", "--summarize", action="store_true")
44+
parser.add_argument("-z", "--summary", action="store_true")
4345
args = parser.parse_args()
4446

4547
if args.verbose:
@@ -57,30 +59,26 @@ def main():
5759
except ValueError:
5860
parameters[name] = value
5961

60-
driver = GraphDatabase.driver(args.url, secure=args.secure)
62+
driver = GraphDatabase.driver(args.url, auth=basic_auth(args.user, args.password))
6163
session = driver.session()
6264
for _ in range(args.times):
6365
for statement in args.statement:
6466
try:
65-
cursor = session.run(statement, parameters)
67+
result = session.run(statement, parameters)
6668
except CypherError as error:
6769
stderr.write("%s: %s\r\n" % (error.code, error.message))
6870
else:
6971
if not args.quiet:
70-
has_results = False
71-
for i, record in enumerate(cursor.stream()):
72-
has_results = True
73-
if i == 0:
74-
stdout.write("%s\r\n" % "\t".join(record.keys()))
75-
stdout.write("%s\r\n" % "\t".join(map(repr, record)))
76-
if has_results:
77-
stdout.write("\r\n")
72+
if args.keys:
73+
stdout.write("%s\r\n" % "\t".join(result.keys()))
74+
for i, record in enumerate(result):
75+
stdout.write("%s\r\n" % "\t".join(map(repr, record.values())))
7876
if args.summary:
79-
summary = cursor.summary
77+
summary = result.summary
8078
stdout.write("Statement : %r\r\n" % summary.statement)
8179
stdout.write("Parameters : %r\r\n" % summary.parameters)
8280
stdout.write("Statement Type : %r\r\n" % summary.statement_type)
83-
stdout.write("Statistics : %r\r\n" % summary.statistics)
81+
stdout.write("Counters : %r\r\n" % summary.counters)
8482
stdout.write("\r\n")
8583
session.close()
8684

neo4j/v1/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,4 @@
2020

2121
from .constants import *
2222
from .session import *
23-
from .typesystem import *
23+
from .types import *

neo4j/v1/exceptions.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,3 @@ def __init__(self, data):
3838
for key, value in data.items():
3939
if not key.startswith("_"):
4040
setattr(self, key, value)
41-
42-
43-
class ResultError(Exception):
44-
""" Raised when the cursor encounters a problem.
45-
"""
46-
47-
pass

0 commit comments

Comments
 (0)