Skip to content

Commit e0b373d

Browse files
authored
feat: DB API cursors are now iterable (#618)
* feat: make DB API Cursors iterable * Raise error if obtaining iterator of closed Cursor
1 parent f75dcdf commit e0b373d

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

google/cloud/bigquery/dbapi/_helpers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ def decorate_public_methods(klass):
276276
"""Apply ``_raise_on_closed()`` decorator to public instance methods.
277277
"""
278278
for name in dir(klass):
279-
if name.startswith("_"):
279+
if name.startswith("_") and name != "__iter__":
280280
continue
281281

282282
member = getattr(klass, name)

google/cloud/bigquery/dbapi/cursor.py

+4
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,10 @@ def setinputsizes(self, sizes):
365365
def setoutputsize(self, size, column=None):
366366
"""No-op, but for consistency raise an error if cursor is closed."""
367367

368+
def __iter__(self):
369+
self._try_fetch()
370+
return iter(self._query_data)
371+
368372

369373
def _format_operation_list(operation, parameters):
370374
"""Formats parameters in operation in the way BigQuery expects.

tests/unit/test_dbapi_cursor.py

+24
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ def test_raises_error_if_closed(self):
178178
"fetchone",
179179
"setinputsizes",
180180
"setoutputsize",
181+
"__iter__",
181182
)
182183

183184
for method in method_names:
@@ -611,6 +612,29 @@ def test_executemany_w_dml(self):
611612
self.assertIsNone(cursor.description)
612613
self.assertEqual(cursor.rowcount, 12)
613614

615+
def test_is_iterable(self):
616+
from google.cloud.bigquery import dbapi
617+
618+
connection = dbapi.connect(
619+
self._mock_client(rows=[("hello", "there", 7), ("good", "bye", -3)])
620+
)
621+
cursor = connection.cursor()
622+
cursor.execute("SELECT foo, bar, baz FROM hello_world WHERE baz < 42;")
623+
624+
rows_iter = iter(cursor)
625+
626+
row = next(rows_iter)
627+
self.assertEqual(row, ("hello", "there", 7))
628+
row = next(rows_iter)
629+
self.assertEqual(row, ("good", "bye", -3))
630+
self.assertRaises(StopIteration, next, rows_iter)
631+
632+
self.assertEqual(
633+
list(cursor),
634+
[],
635+
"Iterating again over the same results should produce no rows.",
636+
)
637+
614638
def test__format_operation_w_dict(self):
615639
from google.cloud.bigquery.dbapi import cursor
616640

0 commit comments

Comments
 (0)