Skip to content

Commit 9d5bf40

Browse files
committed
Merge remote-tracking branch 'upstream/main' into allow-dateutil-3-and-4
# Conflicts: # CHANGELOG.md # poetry.lock
2 parents fb35f2e + 75a0d5d commit 9d5bf40

9 files changed

Lines changed: 242 additions & 38 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,23 @@
22

33
# Unreleased
44
- Allow python-dateutil 3.x and 4.x (the dependency was capped at `<3`).
5-
- Honor `max_download_threads` on kernel connections, with a default download window of 16 and explicit chunk-setting overrides. Invalid values raise `ValueError` when connecting with `use_kernel=True`.
6-
- Fix the kernel backend ignoring `use_cloud_fetch=False`, so complete results can be fetched without cloud-storage downloads.
7-
- 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))
8-
- 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.
9-
- Report `cursor.rowcount` after asynchronous DML completes on both the Thrift and kernel backends, preserving zero counts and fetched result rows.
5+
- 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.
6+
7+
# 4.10.0 (2026-11-24)
8+
- Upgrade Databricks SQL Kernel to 1.5.0, with lower overhead for buffered fetches and closing drained cursors, and Arrow and Quinn security updates.
9+
- Kernel TLS certificate errors fail after one attempt and report the underlying cause, including for CloudFetch.
10+
- A failed OAuth token request fails kernel connections immediately instead of authenticating again.
11+
- Fix file-descriptor leaks when closing kernel connections, including OAuth connections.
12+
- Kernel CloudFetch downloads keep progressing across result pages and respond to cancellation.
13+
- Fix the kernel backend ignoring `use_cloud_fetch=False`.
14+
- Omit presigned CloudFetch URL query strings from kernel errors and debug logs.
15+
- Preserve affected-row counts from immediately completed kernel statements.
16+
- Honor `max_download_threads` on kernel connections; invalid values raise `ValueError` with `use_kernel=True`.
17+
- Forward `telemetry_flush_interval_ms` to the kernel, which previously ignored it.
18+
- Report `cursor.rowcount` after asynchronous DML completes on the Thrift and kernel backends.
19+
- Fix `use_inline_params=True` rendering a sequence after `IN` as `ARRAY(...)`, which Spark rejects ([#629](https://github.com/databricks/databricks-sql-python/issues/629)).
20+
- Speed up Thrift response handling for wide results and metadata calls.
21+
- Update oauthlib to 4.0.1 to address security findings.
1022

1123
# 4.9.0 (2026-11-04)
1224
- 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.

‎KERNEL_REV‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
0b5d0edfed32c0745d5abc2468fc3070e2eb2a17
1+
5c3a909771f749174567af074bfe18c24a335f5c

‎poetry.lock‎

Lines changed: 8 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pyproject.toml‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "databricks-sql-connector"
3-
version = "4.9.0"
3+
version = "4.10.0"
44
description = "Databricks SQL Connector for Python"
55
authors = ["Databricks <databricks-sql-connector-maintainers@databricks.com>"]
66
license = "Apache-2.0"
@@ -67,10 +67,10 @@ requests-kerberos = {version = "^0.15.0", optional = true}
6767
# is ``abi3`` with ``Requires-Python: >=3.9`` (built ``abi3-py39``); the
6868
# dependency remains gated to the connector's Python >= 3.10 support floor.
6969
#
70-
# Floor is 1.4.0 (``^1.4.0`` == ``>=1.4.0,<2.0.0``), allowing compatible
70+
# Floor is 1.5.0 (``^1.5.0`` == ``>=1.5.0,<2.0.0``), allowing compatible
7171
# 1.x releases while keeping the next major upgrade deliberate. The kernel's
7272
# pyarrow constraint remains >=23.0.1,<24.
73-
databricks-sql-kernel = {version = "^1.4.0", optional = true, python = ">=3.10"}
73+
databricks-sql-kernel = {version = "^1.5.0", optional = true, python = ">=3.10"}
7474

7575

7676
[tool.poetry.extras]

‎src/databricks/sql/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def __repr__(self):
7171
DATE = DBAPITypeObject("date")
7272
ROWID = DBAPITypeObject()
7373

74-
__version__ = "4.9.0"
74+
__version__ = "4.10.0"
7575
USER_AGENT_NAME = "PyDatabricksSqlConnector"
7676

7777
# These two functions are pyhive legacy

‎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)