Skip to content

Commit 47b4968

Browse files
author
peco-engineer-bot[bot]
committed
Merge main into ai/issue-901
Signed-off-by: peco-engineer-bot[bot] <peco-engineer-bot[bot]@users.noreply.github.com>
2 parents d3ed2c7 + 75a0d5d commit 47b4968

5 files changed

Lines changed: 213 additions & 21 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Release History
22

33
# Unreleased
4-
4+
- Speed up `fetchone()`, `fetchmany()` and `fetchall()` by building each result `Row` with fewer Python calls. The rows are unchanged. Large results and many concurrent cursors in one process benefit most.
55
- **Behaviour change:** `DecimalParameter` now binds `DECIMAL(precision, scale)`, matching SQL: `precision` is the total number of digits and `scale` the number of fractional digits (earlier docs described them the other way round). Calls written for the old convention (`scale > precision`, e.g. `scale=10, precision=2`) still bind `DECIMAL(10,2)` but emit a `FutureWarning`; swap your arguments, as this will raise `ValueError` in a future release. A declared `scale` equal to or less than `precision` is now interpreted with the SQL meaning, and a declared `scale` smaller than the value's own scale is widened (growing the precision by the same amount) so fractional digits are not lost (e.g. `DecimalParameter(Decimal("123.4567"), precision=10, scale=2)` binds `DECIMAL(12,4)`). The declared integer room (`precision - scale`) is not widened, so a value with more integer digits is still rejected by the server as out of range. Widening is capped at the 38-digit DECIMAL maximum; a value needing more digits than that still has its excess fractional digits rounded. The constructor now also raises `ValueError` for inputs it previously accepted: a `precision` outside 0..38, a negative `scale`, and `bool` values for `scale` or `precision`. `precision=0` (e.g. `scale=5, precision=0`) still falls back to an inferred type as before, but now emits a `FutureWarning`; it will raise `ValueError` in a future release. `scale=0` (previously also treated as unset) is now honoured as `DECIMAL(precision, 0)`, except that when the value has more integer digits than `precision` (which earlier releases accepted via the inferred type) it falls back to the inferred type with a `FutureWarning`; this will raise `ValueError` in a future release.
66

77
# 4.10.0 (2026-11-24)

‎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: 16 additions & 13 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,10 @@ 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+
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):
@@ -293,14 +296,14 @@ def _fill_results_buffer(self):
293296
def _convert_columnar_table(self, table):
294297
column_names = [c[0] for c in self.description]
295298
ResultRow = Row(*column_names)
296-
result = []
297-
for row_index in range(table.num_rows):
298-
curr_row = []
299-
for col_index in range(table.num_columns):
300-
curr_row.append(table.get_item(col_index, row_index))
301-
result.append(ResultRow(*curr_row))
302-
303-
return result
299+
rows = (
300+
[
301+
table.get_item(col_index, row_index)
302+
for col_index in range(table.num_columns)
303+
]
304+
for row_index in range(table.num_rows)
305+
)
306+
return _create_rows(ResultRow, rows)
304307

305308
def fetchmany_arrow(self, size: int) -> "pyarrow.Table":
306309
"""

‎src/databricks/sql/types.py‎

Lines changed: 31 additions & 5 deletions
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
@@ -253,10 +253,7 @@ def __contains__(self, item: Any) -> bool:
253253
def __call__(self, *args: Any) -> "Row":
254254
"""create new Row object"""
255255
if len(args) > len(self):
256-
raise ValueError(
257-
"Can not create Row with fields %s, expected %d values "
258-
"but got %s" % (self, len(self), args)
259-
)
256+
raise _too_many_values_error(self, args)
260257
return _create_row(self, args)
261258

262259
def __getitem__(self, item: Any) -> Any:
@@ -315,3 +312,32 @@ def _create_row(
315312
row = Row(*values)
316313
row.__fields__ = fields
317314
return row
315+
316+
317+
def _too_many_values_error(fields: "Row", values: Tuple[Any, ...]) -> ValueError:
318+
return ValueError(
319+
"Can not create Row with fields %s, expected %d values "
320+
"but got %s" % (fields, len(fields), values)
321+
)
322+
323+
324+
def _create_rows(fields: "Row", rows: Iterable[Sequence[Any]]) -> List["Row"]:
325+
"""Return ``[fields(*values) for values in rows]``, built without per-row Python calls.
326+
327+
``fields(*values)`` creates the row through ``Row.__call__``, ``_create_row``,
328+
``Row.__new__`` and ``Row.__setattr__``. Result fetches build one row per result row,
329+
so this builds the same object directly: the values as a ``Row`` tuple, with
330+
``__fields__`` stored where ``Row.__setattr__`` stores it. A row with more values than
331+
``fields`` raises the same ``ValueError`` as ``fields(*values)``.
332+
"""
333+
width = len(fields)
334+
new_row = tuple.__new__
335+
result: List[Row] = []
336+
append = result.append
337+
for values in rows:
338+
if len(values) > width:
339+
raise _too_many_values_error(fields, tuple(values))
340+
row = new_row(Row, values)
341+
row.__dict__["__fields__"] = fields
342+
append(row)
343+
return result

‎tests/unit/test_create_rows.py‎

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
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+
@pytest.mark.parametrize(
76+
"extra_row",
77+
[
78+
(1, "a", None, "extra"),
79+
[1, "a", None, "extra"],
80+
numpy.array([1, "a", None, "extra"], dtype="object"),
81+
],
82+
ids=["tuple", "list", "numpy_object_row"],
83+
)
84+
def test_create_rows_rejects_more_values_than_fields_like_row_factory(extra_row):
85+
with pytest.raises(ValueError) as expected:
86+
FIELDS(*extra_row)
87+
with pytest.raises(ValueError) as actual:
88+
_create_rows(FIELDS, [(1, "a", None), extra_row])
89+
assert str(actual.value) == str(expected.value)
90+
91+
92+
def test_create_rows_keeps_rows_read_only():
93+
(row,) = _create_rows(FIELDS, [(1, "a", None)])
94+
with pytest.raises(RuntimeError):
95+
row.id = 2
96+
97+
98+
DESCRIPTION = [
99+
("id", "bigint", None, None, None, None, None),
100+
("name", "string", None, None, None, None, None),
101+
]
102+
EXPECTED_VALUES = [(1, "a"), (None, None), (3, "c")]
103+
104+
105+
def _assert_rows_for_description(rows):
106+
expected = [Row("id", "name")(*values) for values in EXPECTED_VALUES]
107+
assert rows == expected
108+
assert all(type(row) is Row for row in rows)
109+
assert {id(row.__fields__) for row in rows} == {id(rows[0].__fields__)}
110+
assert rows[0].__fields__ == Row("id", "name")
111+
assert [row.name for row in rows] == ["a", None, "c"]
112+
113+
114+
@pytest.mark.skipif(pa is None, reason="PyArrow is not installed")
115+
@pytest.mark.parametrize("disable_pandas", [False, True])
116+
def test_convert_arrow_table_builds_rows(disable_pandas):
117+
table = pa.table(
118+
{
119+
"id": pa.array([1, None, 3], pa.int64()),
120+
"name": pa.array(["a", None, "c"], pa.string()),
121+
}
122+
)
123+
result_set = SimpleNamespace(
124+
description=DESCRIPTION,
125+
connection=SimpleNamespace(disable_pandas=disable_pandas),
126+
)
127+
_assert_rows_for_description(ResultSet._convert_arrow_table(result_set, table))
128+
129+
130+
@pytest.mark.skipif(pa is None, reason="PyArrow is not installed")
131+
@pytest.mark.parametrize("num_rows", [1023, 1024, 1025, 2049])
132+
def test_convert_arrow_table_keeps_every_row_across_chunks(num_rows):
133+
ids = [None if i % 5 == 0 else i for i in range(num_rows)]
134+
names = [f"name-{i}" for i in range(num_rows)]
135+
table = pa.table(
136+
{"id": pa.array(ids, pa.int64()), "name": pa.array(names, pa.string())}
137+
)
138+
result_set = SimpleNamespace(
139+
description=DESCRIPTION, connection=SimpleNamespace(disable_pandas=False)
140+
)
141+
142+
rows = ResultSet._convert_arrow_table(result_set, table)
143+
144+
assert rows == [Row("id", "name")(*values) for values in zip(ids, names)]
145+
assert all(type(row) is Row for row in rows)
146+
assert {id(row.__fields__) for row in rows} == {id(rows[0].__fields__)}
147+
148+
149+
def test_convert_columnar_table_builds_rows():
150+
table = ColumnTable([[1, None, 3], ["a", None, "c"]], ["id", "name"])
151+
result_set = SimpleNamespace(description=DESCRIPTION)
152+
_assert_rows_for_description(
153+
ThriftResultSet._convert_columnar_table(result_set, table)
154+
)
155+
156+
157+
def test_create_json_table_builds_rows():
158+
result_set = SimpleNamespace(
159+
description=DESCRIPTION, _convert_json_types=lambda row: list(row)
160+
)
161+
_assert_rows_for_description(
162+
SeaResultSet._create_json_table(result_set, [list(v) for v in EXPECTED_VALUES])
163+
)

0 commit comments

Comments
 (0)