diff --git a/CHANGELOG.md b/CHANGELOG.md index 62cd94fe6..43fda3bed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Release History +# Unreleased +- 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. + # 4.10.0 (2026-11-24) - Upgrade Databricks SQL Kernel to 1.5.0, with lower overhead for buffered fetches and closing drained cursors, and Arrow and Quinn security updates. - Kernel TLS certificate errors fail after one attempt and report the underlying cause, including for CloudFetch. diff --git a/src/databricks/sql/backend/sea/result_set.py b/src/databricks/sql/backend/sea/result_set.py index 17838ed81..9680bdcb4 100644 --- a/src/databricks/sql/backend/sea/result_set.py +++ b/src/databricks/sql/backend/sea/result_set.py @@ -15,7 +15,7 @@ if TYPE_CHECKING: from databricks.sql.client import Connection from databricks.sql.backend.sea.backend import SeaDatabricksClient -from databricks.sql.types import Row +from databricks.sql.types import Row, _create_rows from databricks.sql.backend.sea.queue import JsonQueue, SeaResultSetQueueFactory from databricks.sql.backend.types import ExecuteResponse from databricks.sql.result_set import ResultSet @@ -141,7 +141,7 @@ def _create_json_table(self, rows: List[List[str]]) -> List[Row]: """ ResultRow = Row(*[col[0] for col in self.description]) - return [ResultRow(*self._convert_json_types(row)) for row in rows] + return _create_rows(ResultRow, (self._convert_json_types(row) for row in rows)) def fetchmany_json(self, size: int) -> List[List[str]]: """ diff --git a/src/databricks/sql/result_set.py b/src/databricks/sql/result_set.py index f24a07505..5a6cdd981 100644 --- a/src/databricks/sql/result_set.py +++ b/src/databricks/sql/result_set.py @@ -15,7 +15,7 @@ from databricks.sql.backend.thrift_backend import ThriftDatabricksClient from databricks.sql.client import Connection from databricks.sql.backend.databricks_client import DatabricksClient -from databricks.sql.types import Row +from databricks.sql.types import Row, _create_rows from databricks.sql.exc import RequestError, CursorAlreadyClosedError from databricks.sql.utils import ( ColumnTable, @@ -99,9 +99,9 @@ def _convert_arrow_table(self, table): ResultRow = Row(*column_names) if self.connection.disable_pandas is True: - return [ - ResultRow(*[v.as_py() for v in r]) for r in zip(*table.itercolumns()) - ] + return _create_rows( + ResultRow, ([v.as_py() for v in r] for r in zip(*table.itercolumns())) + ) # Need to use nullable types, as otherwise type can change when there are missing values. # See https://arrow.apache.org/docs/python/pandas.html#nullable-types @@ -130,7 +130,10 @@ def _convert_arrow_table(self, table): ) res = df.to_numpy(na_value=None, dtype="object") - return [ResultRow(*v) for v in res] + rows = [] + for start in range(0, len(res), 1024): + rows += _create_rows(ResultRow, res[start : start + 1024].tolist()) + return rows @property def rownumber(self): @@ -293,14 +296,14 @@ def _fill_results_buffer(self): def _convert_columnar_table(self, table): column_names = [c[0] for c in self.description] ResultRow = Row(*column_names) - result = [] - for row_index in range(table.num_rows): - curr_row = [] - for col_index in range(table.num_columns): - curr_row.append(table.get_item(col_index, row_index)) - result.append(ResultRow(*curr_row)) - - return result + rows = ( + [ + table.get_item(col_index, row_index) + for col_index in range(table.num_columns) + ] + for row_index in range(table.num_rows) + ) + return _create_rows(ResultRow, rows) def fetchmany_arrow(self, size: int) -> "pyarrow.Table": """ diff --git a/src/databricks/sql/types.py b/src/databricks/sql/types.py index 2d1ddc42a..2ed5079da 100644 --- a/src/databricks/sql/types.py +++ b/src/databricks/sql/types.py @@ -16,7 +16,7 @@ # # Row class was taken from Apache Spark pyspark. -from typing import Any, Dict, List, Optional, Tuple, Union, TypeVar +from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union, TypeVar import datetime import decimal from ssl import SSLContext, CERT_NONE, CERT_REQUIRED, create_default_context @@ -253,10 +253,7 @@ def __contains__(self, item: Any) -> bool: def __call__(self, *args: Any) -> "Row": """create new Row object""" if len(args) > len(self): - raise ValueError( - "Can not create Row with fields %s, expected %d values " - "but got %s" % (self, len(self), args) - ) + raise _too_many_values_error(self, args) return _create_row(self, args) def __getitem__(self, item: Any) -> Any: @@ -315,3 +312,32 @@ def _create_row( row = Row(*values) row.__fields__ = fields return row + + +def _too_many_values_error(fields: "Row", values: Tuple[Any, ...]) -> ValueError: + return ValueError( + "Can not create Row with fields %s, expected %d values " + "but got %s" % (fields, len(fields), values) + ) + + +def _create_rows(fields: "Row", rows: Iterable[Sequence[Any]]) -> List["Row"]: + """Return ``[fields(*values) for values in rows]``, built without per-row Python calls. + + ``fields(*values)`` creates the row through ``Row.__call__``, ``_create_row``, + ``Row.__new__`` and ``Row.__setattr__``. Result fetches build one row per result row, + so this builds the same object directly: the values as a ``Row`` tuple, with + ``__fields__`` stored where ``Row.__setattr__`` stores it. A row with more values than + ``fields`` raises the same ``ValueError`` as ``fields(*values)``. + """ + width = len(fields) + new_row = tuple.__new__ + result: List[Row] = [] + append = result.append + for values in rows: + if len(values) > width: + raise _too_many_values_error(fields, tuple(values)) + row = new_row(Row, values) + row.__dict__["__fields__"] = fields + append(row) + return result diff --git a/tests/unit/test_create_rows.py b/tests/unit/test_create_rows.py new file mode 100644 index 000000000..c85712bf3 --- /dev/null +++ b/tests/unit/test_create_rows.py @@ -0,0 +1,163 @@ +"""Tests for _create_rows and the result conversions that build rows with it.""" + +import pickle +from decimal import Decimal +from types import SimpleNamespace + +import numpy +import pytest + +try: + import pyarrow as pa +except ImportError: + pa = None + +from databricks.sql.backend.sea.result_set import SeaResultSet +from databricks.sql.result_set import ResultSet, ThriftResultSet +from databricks.sql.types import Row, _create_rows +from databricks.sql.utils import ColumnTable + +FIELDS = Row("id", "name", "amount") + +ROW_INPUTS = { + "tuples": lambda: [(1, "a", Decimal("1.10")), (2, None, None)], + "lists": lambda: [[1, "a", Decimal("1.10")], [2, None, None]], + "numpy_object_rows": lambda: numpy.array( + [[1, "a", Decimal("1.10")], [2, None, 3.5]], dtype="object" + ), + "generator": lambda: ([i, str(i), None] for i in range(3)), + "fewer_values_than_fields": lambda: [(1,), (2, "b")], + "no_rows": lambda: [], +} + + +def _outcome(function): + try: + return ("value", function()) + except Exception as error: + return ("error", type(error)) + + +def _assert_same_rows(expected, actual): + assert len(actual) == len(expected) + for want, got in zip(expected, actual): + assert type(got) is Row + assert tuple(got) == tuple(want) + assert [type(value) for value in got] == [type(value) for value in want] + assert got.__fields__ is want.__fields__ + assert repr(got) == repr(want) + assert got.asDict() == want.asDict() + assert got == want + for name in want.__fields__: + assert _outcome(lambda: getattr(got, name)) == _outcome( + lambda: getattr(want, name) + ) + assert _outcome(lambda: got[name]) == _outcome(lambda: want[name]) + assert (name in got) == (name in want) + + +@pytest.mark.parametrize("make_rows", ROW_INPUTS.values(), ids=ROW_INPUTS.keys()) +def test_create_rows_matches_row_factory(make_rows): + _assert_same_rows( + [FIELDS(*values) for values in make_rows()], _create_rows(FIELDS, make_rows()) + ) + + +def test_create_rows_pickles_like_row_factory(): + want = FIELDS(1, "a", None) + (got,) = _create_rows(FIELDS, [(1, "a", None)]) + assert pickle.dumps(got) == pickle.dumps(want) + restored = pickle.loads(pickle.dumps(got)) + assert restored == want + assert restored.asDict() == want.asDict() + + +@pytest.mark.parametrize( + "extra_row", + [ + (1, "a", None, "extra"), + [1, "a", None, "extra"], + numpy.array([1, "a", None, "extra"], dtype="object"), + ], + ids=["tuple", "list", "numpy_object_row"], +) +def test_create_rows_rejects_more_values_than_fields_like_row_factory(extra_row): + with pytest.raises(ValueError) as expected: + FIELDS(*extra_row) + with pytest.raises(ValueError) as actual: + _create_rows(FIELDS, [(1, "a", None), extra_row]) + assert str(actual.value) == str(expected.value) + + +def test_create_rows_keeps_rows_read_only(): + (row,) = _create_rows(FIELDS, [(1, "a", None)]) + with pytest.raises(RuntimeError): + row.id = 2 + + +DESCRIPTION = [ + ("id", "bigint", None, None, None, None, None), + ("name", "string", None, None, None, None, None), +] +EXPECTED_VALUES = [(1, "a"), (None, None), (3, "c")] + + +def _assert_rows_for_description(rows): + expected = [Row("id", "name")(*values) for values in EXPECTED_VALUES] + assert rows == expected + assert all(type(row) is Row for row in rows) + assert {id(row.__fields__) for row in rows} == {id(rows[0].__fields__)} + assert rows[0].__fields__ == Row("id", "name") + assert [row.name for row in rows] == ["a", None, "c"] + + +@pytest.mark.skipif(pa is None, reason="PyArrow is not installed") +@pytest.mark.parametrize("disable_pandas", [False, True]) +def test_convert_arrow_table_builds_rows(disable_pandas): + table = pa.table( + { + "id": pa.array([1, None, 3], pa.int64()), + "name": pa.array(["a", None, "c"], pa.string()), + } + ) + result_set = SimpleNamespace( + description=DESCRIPTION, + connection=SimpleNamespace(disable_pandas=disable_pandas), + ) + _assert_rows_for_description(ResultSet._convert_arrow_table(result_set, table)) + + +@pytest.mark.skipif(pa is None, reason="PyArrow is not installed") +@pytest.mark.parametrize("num_rows", [1023, 1024, 1025, 2049]) +def test_convert_arrow_table_keeps_every_row_across_chunks(num_rows): + ids = [None if i % 5 == 0 else i for i in range(num_rows)] + names = [f"name-{i}" for i in range(num_rows)] + table = pa.table( + {"id": pa.array(ids, pa.int64()), "name": pa.array(names, pa.string())} + ) + result_set = SimpleNamespace( + description=DESCRIPTION, connection=SimpleNamespace(disable_pandas=False) + ) + + rows = ResultSet._convert_arrow_table(result_set, table) + + assert rows == [Row("id", "name")(*values) for values in zip(ids, names)] + assert all(type(row) is Row for row in rows) + assert {id(row.__fields__) for row in rows} == {id(rows[0].__fields__)} + + +def test_convert_columnar_table_builds_rows(): + table = ColumnTable([[1, None, 3], ["a", None, "c"]], ["id", "name"]) + result_set = SimpleNamespace(description=DESCRIPTION) + _assert_rows_for_description( + ThriftResultSet._convert_columnar_table(result_set, table) + ) + + +def test_create_json_table_builds_rows(): + result_set = SimpleNamespace( + description=DESCRIPTION, _convert_json_types=lambda row: list(row) + ) + _assert_rows_for_description( + SeaResultSet._create_json_table(result_set, [list(v) for v in EXPECTED_VALUES]) + )