Skip to content

Commit 721ea92

Browse files
aakash-saravanan-dbIsaac
andcommitted
perf: build result rows without per-row Python calls
Every fetch builds one Row per result row, and each one goes through Row.__call__, _create_row, Row.__new__ and Row.__setattr__. Add _create_rows, which builds the same Row objects directly, and use it in the Arrow (pandas and disable_pandas), Thrift columnar and SEA JSON conversions. A row with more values than fields still raises the same ValueError. Signed-off-by: Aakash Saravanan <aakash.saravanan@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 087b2bf commit 721ea92

5 files changed

Lines changed: 168 additions & 10 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
- Fix inline parameters (`use_inline_params=True`) so a sequence directly after `IN` renders as a list again: `x IN %(ids)s` renders as `x IN (1,2,3)` instead of `x IN ARRAY(1,2,3)`, which Spark rejects. Inside the list, tuples render as rows for a multi-column `IN`, and a `set` or `frozenset` is accepted again. Sequences anywhere else still render as `ARRAY(...)` ([#629](https://github.com/databricks/databricks-sql-python/issues/629))
77
- Speed up Thrift response handling: read replies in 1 MiB chunks and decode them with Thrift's C-accelerated protocol, and stop stringifying every request/response for the default no-op debug logger. Wide result schemas, metadata calls with many rows, and inline Arrow results benefit most.
88
- Report `cursor.rowcount` after asynchronous DML completes on both the Thrift and kernel backends, preserving zero counts and fetched result rows.
9+
- Speed up `fetchone()`, `fetchmany()` and `fetchall()`: each result `Row` is now built directly instead of through several Python calls per row. The rows are unchanged. Large results and many concurrent cursors in one process benefit most.
910

1011
# 4.9.0 (2026-11-04)
1112
- Upgrade Databricks SQL Kernel to 1.4.0, which keeps Lakehouse Real-Time session affinity and flushes shared telemetry only after the final session closes.

‎src/databricks/sql/backend/sea/result_set.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
if TYPE_CHECKING:
1616
from databricks.sql.client import Connection
1717
from databricks.sql.backend.sea.backend import SeaDatabricksClient
18-
from databricks.sql.types import Row
18+
from databricks.sql.types import Row, _create_rows
1919
from databricks.sql.backend.sea.queue import JsonQueue, SeaResultSetQueueFactory
2020
from databricks.sql.backend.types import ExecuteResponse
2121
from databricks.sql.result_set import ResultSet
@@ -141,7 +141,7 @@ def _create_json_table(self, rows: List[List[str]]) -> List[Row]:
141141
"""
142142

143143
ResultRow = Row(*[col[0] for col in self.description])
144-
return [ResultRow(*self._convert_json_types(row)) for row in rows]
144+
return _create_rows(ResultRow, (self._convert_json_types(row) for row in rows))
145145

146146
def fetchmany_json(self, size: int) -> List[List[str]]:
147147
"""

‎src/databricks/sql/result_set.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from databricks.sql.backend.thrift_backend import ThriftDatabricksClient
1616
from databricks.sql.client import Connection
1717
from databricks.sql.backend.databricks_client import DatabricksClient
18-
from databricks.sql.types import Row
18+
from databricks.sql.types import Row, _create_rows
1919
from databricks.sql.exc import RequestError, CursorAlreadyClosedError
2020
from databricks.sql.utils import (
2121
ColumnTable,
@@ -99,9 +99,9 @@ def _convert_arrow_table(self, table):
9999
ResultRow = Row(*column_names)
100100

101101
if self.connection.disable_pandas is True:
102-
return [
103-
ResultRow(*[v.as_py() for v in r]) for r in zip(*table.itercolumns())
104-
]
102+
return _create_rows(
103+
ResultRow, ([v.as_py() for v in r] for r in zip(*table.itercolumns()))
104+
)
105105

106106
# Need to use nullable types, as otherwise type can change when there are missing values.
107107
# See https://arrow.apache.org/docs/python/pandas.html#nullable-types
@@ -130,7 +130,7 @@ def _convert_arrow_table(self, table):
130130
)
131131

132132
res = df.to_numpy(na_value=None, dtype="object")
133-
return [ResultRow(*v) for v in res]
133+
return _create_rows(ResultRow, res)
134134

135135
@property
136136
def rownumber(self):
@@ -298,9 +298,9 @@ def _convert_columnar_table(self, table):
298298
curr_row = []
299299
for col_index in range(table.num_columns):
300300
curr_row.append(table.get_item(col_index, row_index))
301-
result.append(ResultRow(*curr_row))
301+
result.append(curr_row)
302302

303-
return result
303+
return _create_rows(ResultRow, result)
304304

305305
def fetchmany_arrow(self, size: int) -> "pyarrow.Table":
306306
"""

‎src/databricks/sql/types.py‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
#
1717
# Row class was taken from Apache Spark pyspark.
1818

19-
from typing import Any, Dict, List, Optional, Tuple, Union, TypeVar
19+
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union, TypeVar
2020
import datetime
2121
import decimal
2222
from ssl import SSLContext, CERT_NONE, CERT_REQUIRED, create_default_context
@@ -315,3 +315,25 @@ def _create_row(
315315
row = Row(*values)
316316
row.__fields__ = fields
317317
return row
318+
319+
320+
def _create_rows(fields: "Row", rows: Iterable[Sequence[Any]]) -> List["Row"]:
321+
"""Return ``[fields(*values) for values in rows]``, built without per-row Python calls.
322+
323+
``fields(*values)`` creates the row through ``Row.__call__``, ``_create_row``,
324+
``Row.__new__`` and ``Row.__setattr__``. Result fetches build one row per result row,
325+
so this builds the same object directly: the values as a ``Row`` tuple, with
326+
``__fields__`` stored where ``Row.__setattr__`` stores it. A row with more values than
327+
``fields`` goes through ``fields(*values)`` to raise the same ``ValueError``.
328+
"""
329+
width = len(fields)
330+
new_row = tuple.__new__
331+
result: List[Row] = []
332+
append = result.append
333+
for values in rows:
334+
if len(values) > width:
335+
fields(*values)
336+
row = new_row(Row, values)
337+
row.__dict__["__fields__"] = fields
338+
append(row)
339+
return result

‎tests/unit/test_create_rows.py‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
"""Tests for _create_rows and the result conversions that build rows with it."""
2+
3+
import pickle
4+
from decimal import Decimal
5+
from types import SimpleNamespace
6+
7+
import numpy
8+
import pytest
9+
10+
try:
11+
import pyarrow as pa
12+
except ImportError:
13+
pa = None
14+
15+
from databricks.sql.backend.sea.result_set import SeaResultSet
16+
from databricks.sql.result_set import ResultSet, ThriftResultSet
17+
from databricks.sql.types import Row, _create_rows
18+
from databricks.sql.utils import ColumnTable
19+
20+
FIELDS = Row("id", "name", "amount")
21+
22+
ROW_INPUTS = {
23+
"tuples": lambda: [(1, "a", Decimal("1.10")), (2, None, None)],
24+
"lists": lambda: [[1, "a", Decimal("1.10")], [2, None, None]],
25+
"numpy_object_rows": lambda: numpy.array(
26+
[[1, "a", Decimal("1.10")], [2, None, 3.5]], dtype="object"
27+
),
28+
"generator": lambda: ([i, str(i), None] for i in range(3)),
29+
"fewer_values_than_fields": lambda: [(1,), (2, "b")],
30+
"no_rows": lambda: [],
31+
}
32+
33+
34+
def _outcome(function):
35+
try:
36+
return ("value", function())
37+
except Exception as error:
38+
return ("error", type(error))
39+
40+
41+
def _assert_same_rows(expected, actual):
42+
assert len(actual) == len(expected)
43+
for want, got in zip(expected, actual):
44+
assert type(got) is Row
45+
assert tuple(got) == tuple(want)
46+
assert [type(value) for value in got] == [type(value) for value in want]
47+
assert got.__fields__ is want.__fields__
48+
assert repr(got) == repr(want)
49+
assert got.asDict() == want.asDict()
50+
assert got == want
51+
for name in want.__fields__:
52+
assert _outcome(lambda: getattr(got, name)) == _outcome(
53+
lambda: getattr(want, name)
54+
)
55+
assert _outcome(lambda: got[name]) == _outcome(lambda: want[name])
56+
assert (name in got) == (name in want)
57+
58+
59+
@pytest.mark.parametrize("make_rows", ROW_INPUTS.values(), ids=ROW_INPUTS.keys())
60+
def test_create_rows_matches_row_factory(make_rows):
61+
_assert_same_rows(
62+
[FIELDS(*values) for values in make_rows()], _create_rows(FIELDS, make_rows())
63+
)
64+
65+
66+
def test_create_rows_pickles_like_row_factory():
67+
want = FIELDS(1, "a", None)
68+
(got,) = _create_rows(FIELDS, [(1, "a", None)])
69+
assert pickle.dumps(got) == pickle.dumps(want)
70+
restored = pickle.loads(pickle.dumps(got))
71+
assert restored == want
72+
assert restored.asDict() == want.asDict()
73+
74+
75+
def test_create_rows_rejects_more_values_than_fields_like_row_factory():
76+
with pytest.raises(ValueError) as expected:
77+
FIELDS(1, "a", None, "extra")
78+
with pytest.raises(ValueError) as actual:
79+
_create_rows(FIELDS, [(1, "a", None), (1, "a", None, "extra")])
80+
assert str(actual.value) == str(expected.value)
81+
82+
83+
def test_create_rows_keeps_rows_read_only():
84+
(row,) = _create_rows(FIELDS, [(1, "a", None)])
85+
with pytest.raises(RuntimeError):
86+
row.id = 2
87+
88+
89+
DESCRIPTION = [
90+
("id", "bigint", None, None, None, None, None),
91+
("name", "string", None, None, None, None, None),
92+
]
93+
EXPECTED_VALUES = [(1, "a"), (None, None), (3, "c")]
94+
95+
96+
def _assert_rows_for_description(rows):
97+
expected = [Row("id", "name")(*values) for values in EXPECTED_VALUES]
98+
assert rows == expected
99+
assert all(type(row) is Row for row in rows)
100+
assert {id(row.__fields__) for row in rows} == {id(rows[0].__fields__)}
101+
assert rows[0].__fields__ == Row("id", "name")
102+
assert [row.name for row in rows] == ["a", None, "c"]
103+
104+
105+
@pytest.mark.skipif(pa is None, reason="PyArrow is not installed")
106+
@pytest.mark.parametrize("disable_pandas", [False, True])
107+
def test_convert_arrow_table_builds_rows(disable_pandas):
108+
table = pa.table(
109+
{
110+
"id": pa.array([1, None, 3], pa.int64()),
111+
"name": pa.array(["a", None, "c"], pa.string()),
112+
}
113+
)
114+
result_set = SimpleNamespace(
115+
description=DESCRIPTION,
116+
connection=SimpleNamespace(disable_pandas=disable_pandas),
117+
)
118+
_assert_rows_for_description(ResultSet._convert_arrow_table(result_set, table))
119+
120+
121+
def test_convert_columnar_table_builds_rows():
122+
table = ColumnTable([[1, None, 3], ["a", None, "c"]], ["id", "name"])
123+
result_set = SimpleNamespace(description=DESCRIPTION)
124+
_assert_rows_for_description(
125+
ThriftResultSet._convert_columnar_table(result_set, table)
126+
)
127+
128+
129+
def test_create_json_table_builds_rows():
130+
result_set = SimpleNamespace(
131+
description=DESCRIPTION, _convert_json_types=lambda row: list(row)
132+
)
133+
_assert_rows_for_description(
134+
SeaResultSet._create_json_table(result_set, [list(v) for v in EXPECTED_VALUES])
135+
)

0 commit comments

Comments
 (0)