Skip to content

Commit b534a8a

Browse files
authored
feat: return list of dictionaries for execute streaming sql (#1003)
* changes * adding tests * comment changes
1 parent 4d490cf commit b534a8a

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

google/cloud/spanner_v1/streamed.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,27 @@ def one_or_none(self):
190190
except StopIteration:
191191
return answer
192192

193+
def to_dict_list(self):
194+
"""Return the result of a query as a list of dictionaries.
195+
In each dictionary the key is the column name and the value is the
196+
value of the that column in a given row.
197+
198+
:rtype:
199+
:class:`list of dict`
200+
:returns: result rows as a list of dictionaries
201+
"""
202+
rows = []
203+
for row in self:
204+
rows.append(
205+
{
206+
column: value
207+
for column, value in zip(
208+
[column.name for column in self._metadata.row_type.fields], row
209+
)
210+
}
211+
)
212+
return rows
213+
193214

194215
class Unmergeable(ValueError):
195216
"""Unable to merge two values.

tests/system/test_session_api.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1913,6 +1913,19 @@ def test_execute_sql_w_manual_consume(sessions_database):
19131913
assert streamed._pending_chunk is None
19141914

19151915

1916+
def test_execute_sql_w_to_dict_list(sessions_database):
1917+
sd = _sample_data
1918+
row_count = 40
1919+
_set_up_table(sessions_database, row_count)
1920+
1921+
with sessions_database.snapshot() as snapshot:
1922+
rows = snapshot.execute_sql(sd.SQL).to_dict_list()
1923+
all_data_rows = list(_row_data(row_count))
1924+
row_data = [list(row.values()) for row in rows]
1925+
sd._check_row_data(row_data, all_data_rows)
1926+
assert all(set(row.keys()) == set(sd.COLUMNS) for row in rows)
1927+
1928+
19161929
def _check_sql_results(
19171930
database,
19181931
sql,

0 commit comments

Comments
 (0)