Skip to content

Commit aaf6719

Browse files
committed
ResultSet.one() fails if the row_factory is using a generator
1 parent 590f150 commit aaf6719

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

CHANGELOG.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ Bug Fixes
66
* Improve and fix socket error-catching code in nonblocking-socket reactors (PYTHON-1024)
77
* Non-ASCII characters in schema break CQL string generation (PYTHON-1008)
88
* Fix OSS driver's virtual table support against DSE 6.0.X and future server releases (PYTHON-1020)
9+
* ResultSet.one() fails if the row_factory is using a generator (PYTHON-1026)
910

1011
Other
1112
-----

cassandra/cluster.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4244,7 +4244,14 @@ def one(self):
42444244
you know a query returns a single row. Consider using an iterator if the
42454245
ResultSet contains more than one row.
42464246
"""
4247-
return self._current_rows[0] if self._current_rows else None
4247+
row = None
4248+
if self._current_rows:
4249+
try:
4250+
row = self._current_rows[0]
4251+
except TypeError: # generator object is not subscriptable, PYTHON-1026
4252+
row = next(iter(self._current_rows))
4253+
4254+
return row
42484255

42494256
def __iter__(self):
42504257
if self._list_mode:

tests/integration/standard/test_row_factories.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,32 @@ def test_ordered_dict_factory(self):
181181
self.assertEqual(result[1]['k'], result[1]['v'])
182182
self.assertEqual(result[1]['k'], 2)
183183

184+
def test_generator_row_factory(self):
185+
"""
186+
Test that ResultSet.one() works with a row_factory that contains a generator.
187+
188+
@since 3.16
189+
@jira_ticket PYTHON-1026
190+
@expected_result one() returns the first row
191+
192+
@test_category queries
193+
"""
194+
def generator_row_factory(column_names, rows):
195+
return _gen_row_factory(rows)
196+
197+
def _gen_row_factory(rows):
198+
for r in rows:
199+
yield r
200+
201+
session = self.session
202+
session.row_factory = generator_row_factory
203+
204+
session.execute(self.insert1)
205+
result = session.execute(self.select)
206+
self.assertIsInstance(result, ResultSet)
207+
first_row = result.one()
208+
self.assertEqual(first_row[0], first_row[1])
209+
184210

185211
class NamedTupleFactoryAndNumericColNamesTests(unittest.TestCase):
186212
"""

0 commit comments

Comments
 (0)