From b534a8aac116a824544d63a24e38f3d484e0d207 Mon Sep 17 00:00:00 2001 From: Astha Mohta <35952883+asthamohta@users.noreply.github.com> Date: Wed, 25 Oct 2023 11:19:04 +0530 Subject: [PATCH] feat: return list of dictionaries for execute streaming sql (#1003) * changes * adding tests * comment changes --- google/cloud/spanner_v1/streamed.py | 21 +++++++++++++++++++++ tests/system/test_session_api.py | 13 +++++++++++++ 2 files changed, 34 insertions(+) diff --git a/google/cloud/spanner_v1/streamed.py b/google/cloud/spanner_v1/streamed.py index 80a452d558..ac8fc71ce6 100644 --- a/google/cloud/spanner_v1/streamed.py +++ b/google/cloud/spanner_v1/streamed.py @@ -190,6 +190,27 @@ def one_or_none(self): except StopIteration: return answer + def to_dict_list(self): + """Return the result of a query as a list of dictionaries. + In each dictionary the key is the column name and the value is the + value of the that column in a given row. + + :rtype: + :class:`list of dict` + :returns: result rows as a list of dictionaries + """ + rows = [] + for row in self: + rows.append( + { + column: value + for column, value in zip( + [column.name for column in self._metadata.row_type.fields], row + ) + } + ) + return rows + class Unmergeable(ValueError): """Unable to merge two values. diff --git a/tests/system/test_session_api.py b/tests/system/test_session_api.py index c4ea2ded40..4a2ce5f495 100644 --- a/tests/system/test_session_api.py +++ b/tests/system/test_session_api.py @@ -1913,6 +1913,19 @@ def test_execute_sql_w_manual_consume(sessions_database): assert streamed._pending_chunk is None +def test_execute_sql_w_to_dict_list(sessions_database): + sd = _sample_data + row_count = 40 + _set_up_table(sessions_database, row_count) + + with sessions_database.snapshot() as snapshot: + rows = snapshot.execute_sql(sd.SQL).to_dict_list() + all_data_rows = list(_row_data(row_count)) + row_data = [list(row.values()) for row in rows] + sd._check_row_data(row_data, all_data_rows) + assert all(set(row.keys()) == set(sd.COLUMNS) for row in rows) + + def _check_sql_results( database, sql,