Skip to content

Commit 6db3195

Browse files
aakash-saravanan-dbvuanhphungIsaac
committed
perf: convert pandas result rows in chunks with tolist()
Iterating the object array from to_numpy() creates a numpy view per row. Convert 1024 rows at a time with tolist() instead, which returns the same value objects as plain lists and keeps peak memory where it was. Signed-off-by: Aakash Saravanan <aakash.saravanan@databricks.com> Co-authored-by: vuanhphung <313058935+vuanhphung@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 0167cfd commit 6db3195

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎src/databricks/sql/result_set.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,10 @@ def _convert_arrow_table(self, table):
130130
)
131131

132132
res = df.to_numpy(na_value=None, dtype="object")
133-
return _create_rows(ResultRow, res)
133+
rows = []
134+
for start in range(0, len(res), 1024):
135+
rows += _create_rows(ResultRow, res[start : start + 1024].tolist())
136+
return rows
134137

135138
@property
136139
def rownumber(self):

‎tests/unit/test_create_rows.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,25 @@ def test_convert_arrow_table_builds_rows(disable_pandas):
118118
_assert_rows_for_description(ResultSet._convert_arrow_table(result_set, table))
119119

120120

121+
@pytest.mark.skipif(pa is None, reason="PyArrow is not installed")
122+
@pytest.mark.parametrize("num_rows", [1023, 1024, 1025, 2049])
123+
def test_convert_arrow_table_keeps_every_row_across_chunks(num_rows):
124+
ids = [None if i % 5 == 0 else i for i in range(num_rows)]
125+
names = [f"name-{i}" for i in range(num_rows)]
126+
table = pa.table(
127+
{"id": pa.array(ids, pa.int64()), "name": pa.array(names, pa.string())}
128+
)
129+
result_set = SimpleNamespace(
130+
description=DESCRIPTION, connection=SimpleNamespace(disable_pandas=False)
131+
)
132+
133+
rows = ResultSet._convert_arrow_table(result_set, table)
134+
135+
assert rows == [Row("id", "name")(*values) for values in zip(ids, names)]
136+
assert all(type(row) is Row for row in rows)
137+
assert {id(row.__fields__) for row in rows} == {id(rows[0].__fields__)}
138+
139+
121140
def test_convert_columnar_table_builds_rows():
122141
table = ColumnTable([[1, None, 3], ["a", None, "c"]], ["id", "name"])
123142
result_set = SimpleNamespace(description=DESCRIPTION)

0 commit comments

Comments
 (0)