From f257d96b87eead345d4b35541b9d7411f71d9bc8 Mon Sep 17 00:00:00 2001 From: Roman Novatorov Date: Mon, 23 Nov 2026 22:32:43 +0100 Subject: [PATCH 1/3] Populate `cursor.description` type codes with raw wire values CrateDB reports the type of every result column in `col_types`, but `Cursor.description` always reported `None` for the type code, forcing consumers to read the private `cursor._result`. Pass the wire value through unchanged: an integer for scalar columns, a nested list for arrays, `None` when `col_types` is absent, null, or short. Unknown identifiers pass through rather than raise. Fixes #837 --- CHANGES.rst | 4 ++ docs/by-example/client.rst | 35 ++++++---- docs/query.rst | 37 +++++++--- src/crate/client/cursor.py | 14 +++- tests/client/test_cursor.py | 134 ++++++++++++++++++++++++++++++++++++ 5 files changed, 200 insertions(+), 24 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index a671407a..91b0b981 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -4,6 +4,10 @@ Changes for crate Unreleased ================ +- Added type codes to ``Cursor.description``: The second item of each column + is now the raw ``col_types`` value reported by CrateDB, an integer for + scalar columns and a nested list for array columns, instead of ``None``. + It degrades to ``None`` for columns where CrateDB does not report a type. - Breaking change: ``CrateLayer.start()`` now raises ``SystemError`` when CrateDB does not report its HTTP address. The startup timeout is raised from 30s to 90s. - Breaking change: ``CrateLayer`` can be used as a context manager, which starts and diff --git a/docs/by-example/client.rst b/docs/by-example/client.rst index 52897375..43307b66 100644 --- a/docs/by-example/client.rst +++ b/docs/by-example/client.rst @@ -238,8 +238,9 @@ Cursor Description ================== The ``description`` property of the cursor returns a sequence of 7-item -sequences containing the column name as first parameter. Just the name field is -supported, all other fields are 'None': +sequences containing the column name as first parameter, and the raw column +type as reported by CrateDB as second: an integer for scalar columns, a +nested list for array columns. All other fields are ``None``: >>> cursor.execute("SELECT * FROM locations order by name") >>> result = cursor.fetchone() @@ -260,17 +261,25 @@ supported, all other fields are 'None': >>> result = cursor.description >>> pprint(result) - (('name', None, None, None, None, None, None), - ('date', None, None, None, None, None, None), - ('datetime_tz', None, None, None, None, None, None), - ('datetime_notz', None, None, None, None, None, None), - ('nullable_datetime', None, None, None, None, None, None), - ('nullable_date', None, None, None, None, None, None), - ('kind', None, None, None, None, None, None), - ('flag', None, None, None, None, None, None), - ('position', None, None, None, None, None, None), - ('description', None, None, None, None, None, None), - ('details', None, None, None, None, None, None)) + (('name', 4, None, None, None, None, None), + ('date', 15, None, None, None, None, None), + ('datetime_tz', 11, None, None, None, None, None), + ('datetime_notz', 15, None, None, None, None, None), + ('nullable_datetime', 15, None, None, None, None, None), + ('nullable_date', 15, None, None, None, None, None), + ('kind', 4, None, None, None, None, None), + ('flag', 3, None, None, None, None, None), + ('position', 9, None, None, None, None, None), + ('description', 4, None, None, None, None, None), + ('details', [100, 12], None, None, None, None, None)) + +The type codes correspond to the ``DataType`` enumeration; identifiers the +client does not know pass through unchanged. ``ARRAY`` columns report their +element type as a nested list, recursively for nested arrays: + + >>> cursor.execute("select [[1, 2], [3]]") + >>> cursor.description + (('[[1, 2], [3]]', [100, [100, 9]], None, None, None, None, None),) Closing the Cursor ================== diff --git a/docs/query.rst b/docs/query.rst index f99c7801..c76e4678 100644 --- a/docs/query.rst +++ b/docs/query.rst @@ -235,8 +235,10 @@ column names for keys. If you want to access column names, you must use ``cursor.description``. The `Python Database API Specification v2.0`_ `defines`_ seven description -attributes per column, but only the first one (column name) is supported by -this library. All other attributes are ``None``. +attributes per column. This library supports the column name and the type +code, the raw value as reported by CrateDB: an integer for scalar columns, +a nested list for array columns, recursively. All other attributes are +``None``. Let's say you have a query like this: @@ -252,13 +254,13 @@ Let's say you have a query like this: The cursor ``description`` might look like this: >>> cursor.description - (('date', None, None, None, None, None, None), - ('datetime_tz', None, None, None, None, None, None), - ('datetime_notz', None, None, None, None, None, None), - ('description', None, None, None, None, None, None), + (('date', 15, None, None, None, None, None), + ('datetime_tz', 11, None, None, None, None, None), + ('datetime_notz', 15, None, None, None, None, None), + ('description', 4, None, None, None, None, None), ... - ('nullable_datetime', None, None, None, None, None, None), - ('position', None, None, None, None, None, None)) + ('nullable_datetime', 15, None, None, None, None, None), + ('position', 9, None, None, None, None, None)) You can turn this into something more manageable with :ref:`py:tut-listcomps`: @@ -266,6 +268,25 @@ You can turn this into something more manageable with :ref:`py:tut-listcomps`: ['date', 'datetime_tz', 'datetime_notz', ..., 'nullable_datetime', 'position'] +Accessing column types +====================== + +The type code can be used to find columns of a certain data type, for example +to process ``TIMESTAMP`` columns differently than numeric ones. Compare +against the ``DataType`` enum, using ``.value`` to obtain its integer: + + >>> from crate.client.converter import DataType + >>> tz_timestamp = DataType.TIMESTAMP_WITH_TZ.value + >>> for name, type_code, *_ in cursor.description: + ... if type_code == tz_timestamp: + ... print(name) + datetime_tz + +The type code is ``None`` when CrateDB does not report a type for the +column; identifiers unknown to this client pass through unchanged, so codes +without an enum member are possible. + + Data type conversion ==================== diff --git a/src/crate/client/cursor.py b/src/crate/client/cursor.py index 0e331223..0ddb8a18 100644 --- a/src/crate/client/cursor.py +++ b/src/crate/client/cursor.py @@ -305,14 +305,22 @@ def __next__(self): @property def description(self): """ - This read-only attribute is a sequence of 7-item sequences. + This read-only attribute is a sequence of 7-item sequences: + (name, type code, five unused fields). The type code is the raw + value CrateDB reports in ``col_types``, an integer for scalar + columns and a nested list for array columns, or ``None`` when + not reported. """ if self._closed: return None + cols = self._result["cols"] + col_types = self._result.get("col_types") or [] + description = [] - for col in self._result["cols"]: - description.append((col, None, None, None, None, None, None)) + for i, name in enumerate(cols): + col_type = col_types[i] if i < len(col_types) else None + description.append((name, col_type, None, None, None, None, None)) return tuple(description) @property diff --git a/tests/client/test_cursor.py b/tests/client/test_cursor.py index 239f58a0..b39bf871 100644 --- a/tests/client/test_cursor.py +++ b/tests/client/test_cursor.py @@ -83,6 +83,140 @@ def test_cursor_description(mocked_connection): assert cursor.description is None +def test_cursor_description_type_codes(mocked_connection): + """Verify raw type codes pass through, arrays as nested lists.""" + cursor = mocked_connection.cursor() + response = { + "col_types": [4, [100, 5]], + "cols": ["name", "addresses"], + "rows": [["foo", ["10.10.10.1"]]], + "rowcount": 1, + "duration": 123, + } + with mock.patch.object( + mocked_connection.client, "sql", return_value=response + ): + cursor.execute("") + assert [column[1] for column in cursor.description] == [4, [100, 5]] + + +def test_cursor_description_nested_array_type(mocked_connection): + """Verify nested arrays pass their type through unchanged.""" + cursor = mocked_connection.cursor() + response = { + "col_types": [[100, [100, 9]]], + "cols": ["matrix"], + "rows": [[[[1, 2], [3]]]], + "rowcount": 1, + "duration": 123, + } + with mock.patch.object( + mocked_connection.client, "sql", return_value=response + ): + cursor.execute("") + assert [column[1] for column in cursor.description] == [[100, [100, 9]]] + + +def test_cursor_description_extra_col_types(mocked_connection): + """Verify trailing entries beyond the column count are ignored.""" + cursor = mocked_connection.cursor() + response = { + "col_types": [4, 5, 6], + "cols": ["name", "address"], + "rows": [["foo", "10.10.10.1"]], + "rowcount": 1, + "duration": 123, + } + with mock.patch.object( + mocked_connection.client, "sql", return_value=response + ): + cursor.execute("") + assert [column[1] for column in cursor.description] == [4, 5] + + +def test_cursor_description_after_executemany(mocked_connection): + """Verify executemany keeps col_types for description.""" + cursor = mocked_connection.cursor() + response = { + "col_types": [4], + "cols": ["name"], + "rows": [["foo"]], + "rowcount": 1, + "duration": 123, + } + with mock.patch.object( + mocked_connection.client, "sql", return_value=response + ): + cursor.executemany("", [["foo"]]) + assert [column[1] for column in cursor.description] == [4] + + +@pytest.mark.parametrize( + "response, expected", + [ + pytest.param( + { + "cols": ["name", "address"], + "rows": [["foo", "10.10.10.1"]], + "rowcount": 1, + "duration": 123, + }, + [None, None], + id="col-types-absent", + ), + pytest.param( + { + "col_types": None, + "cols": ["name", "address"], + "rows": [["foo", "10.10.10.1"]], + "rowcount": 1, + "duration": 123, + }, + [None, None], + id="col-types-null", + ), + pytest.param( + { + "col_types": [4], + "cols": ["name", "address"], + "rows": [["foo", "10.10.10.1"]], + "rowcount": 1, + "duration": 123, + }, + [4, None], + id="col-types-short", + ), + ], +) +def test_cursor_description_degrades_type_codes( + mocked_connection, response, expected +): + """Verify type codes degrade per-column to None, never raise.""" + cursor = mocked_connection.cursor() + with mock.patch.object( + mocked_connection.client, "sql", return_value=response + ): + cursor.execute("") + assert [column[1] for column in cursor.description] == expected + + +def test_cursor_description_unknown_type_code(mocked_connection): + """Verify type codes this client does not know pass through unchanged.""" + cursor = mocked_connection.cursor() + response = { + "col_types": [999, 4], + "cols": ["foo", "name"], + "rows": [["n/a", "foo"]], + "rowcount": 1, + "duration": 123, + } + with mock.patch.object( + mocked_connection.client, "sql", return_value=response + ): + cursor.execute("") + assert [column[1] for column in cursor.description] == [999, 4] + + def test_cursor_rowcount(mocked_connection): """Verify the logic of cursor.rowcount""" cursor = mocked_connection.cursor() From 7ed4fcbbd6a0bf4ac4c016c1c8a1018331c50638 Mon Sep 17 00:00:00 2001 From: Roman Novatorov Date: Tue, 24 Nov 2026 16:08:31 +0100 Subject: [PATCH 2/3] Make description type codes hashable --- CHANGES.rst | 2 +- docs/by-example/client.rst | 8 ++++---- docs/query.rst | 2 +- src/crate/client/cursor.py | 15 ++++++++++++--- tests/client/test_cursor.py | 24 +++++++++++++++++++++--- 5 files changed, 39 insertions(+), 12 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 91b0b981..5f8c92cf 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -6,7 +6,7 @@ Unreleased ================ - Added type codes to ``Cursor.description``: The second item of each column is now the raw ``col_types`` value reported by CrateDB, an integer for - scalar columns and a nested list for array columns, instead of ``None``. + scalar columns and a nested tuple for array columns, instead of ``None``. It degrades to ``None`` for columns where CrateDB does not report a type. - Breaking change: ``CrateLayer.start()`` now raises ``SystemError`` when CrateDB does not report its HTTP address. The startup timeout is raised from 30s to 90s. diff --git a/docs/by-example/client.rst b/docs/by-example/client.rst index 43307b66..227577c7 100644 --- a/docs/by-example/client.rst +++ b/docs/by-example/client.rst @@ -240,7 +240,7 @@ Cursor Description The ``description`` property of the cursor returns a sequence of 7-item sequences containing the column name as first parameter, and the raw column type as reported by CrateDB as second: an integer for scalar columns, a -nested list for array columns. All other fields are ``None``: +nested tuple for array columns. All other fields are ``None``: >>> cursor.execute("SELECT * FROM locations order by name") >>> result = cursor.fetchone() @@ -271,15 +271,15 @@ nested list for array columns. All other fields are ``None``: ('flag', 3, None, None, None, None, None), ('position', 9, None, None, None, None, None), ('description', 4, None, None, None, None, None), - ('details', [100, 12], None, None, None, None, None)) + ('details', (100, 12), None, None, None, None, None)) The type codes correspond to the ``DataType`` enumeration; identifiers the client does not know pass through unchanged. ``ARRAY`` columns report their -element type as a nested list, recursively for nested arrays: +element type as a nested tuple, recursively for nested arrays: >>> cursor.execute("select [[1, 2], [3]]") >>> cursor.description - (('[[1, 2], [3]]', [100, [100, 9]], None, None, None, None, None),) + (('[[1, 2], [3]]', (100, (100, 9)), None, None, None, None, None),) Closing the Cursor ================== diff --git a/docs/query.rst b/docs/query.rst index c76e4678..6d9a2a18 100644 --- a/docs/query.rst +++ b/docs/query.rst @@ -237,7 +237,7 @@ column names for keys. If you want to access column names, you must use The `Python Database API Specification v2.0`_ `defines`_ seven description attributes per column. This library supports the column name and the type code, the raw value as reported by CrateDB: an integer for scalar columns, -a nested list for array columns, recursively. All other attributes are +a nested tuple for array columns, recursively. All other attributes are ``None``. Let's say you have a query like this: diff --git a/src/crate/client/cursor.py b/src/crate/client/cursor.py index 0ddb8a18..3ded3c05 100644 --- a/src/crate/client/cursor.py +++ b/src/crate/client/cursor.py @@ -113,6 +113,13 @@ def _convert_named_bulk_params( return converted_sql, bulk_args +def _lists_to_tuples(value: t.Any) -> t.Any: + """Recursively convert lists to tuples.""" + if isinstance(value, list): + return tuple(_lists_to_tuples(item) for item in value) + return value + + class Cursor: """ not thread-safe by intention @@ -308,7 +315,7 @@ def description(self): This read-only attribute is a sequence of 7-item sequences: (name, type code, five unused fields). The type code is the raw value CrateDB reports in ``col_types``, an integer for scalar - columns and a nested list for array columns, or ``None`` when + columns and a nested tuple for array columns, or ``None`` when not reported. """ if self._closed: @@ -319,8 +326,10 @@ def description(self): description = [] for i, name in enumerate(cols): - col_type = col_types[i] if i < len(col_types) else None - description.append((name, col_type, None, None, None, None, None)) + type_code = None + if i < len(col_types): + type_code = _lists_to_tuples(col_types[i]) + description.append((name, type_code, None, None, None, None, None)) return tuple(description) @property diff --git a/tests/client/test_cursor.py b/tests/client/test_cursor.py index b39bf871..b43e63d2 100644 --- a/tests/client/test_cursor.py +++ b/tests/client/test_cursor.py @@ -97,11 +97,11 @@ def test_cursor_description_type_codes(mocked_connection): mocked_connection.client, "sql", return_value=response ): cursor.execute("") - assert [column[1] for column in cursor.description] == [4, [100, 5]] + assert [column[1] for column in cursor.description] == [4, (100, 5)] def test_cursor_description_nested_array_type(mocked_connection): - """Verify nested arrays pass their type through unchanged.""" + """Verify nested arrays pass through as nested tuples.""" cursor = mocked_connection.cursor() response = { "col_types": [[100, [100, 9]]], @@ -114,7 +114,7 @@ def test_cursor_description_nested_array_type(mocked_connection): mocked_connection.client, "sql", return_value=response ): cursor.execute("") - assert [column[1] for column in cursor.description] == [[100, [100, 9]]] + assert [column[1] for column in cursor.description] == [(100, (100, 9))] def test_cursor_description_extra_col_types(mocked_connection): @@ -217,6 +217,24 @@ def test_cursor_description_unknown_type_code(mocked_connection): assert [column[1] for column in cursor.description] == [999, 4] +def test_cursor_description_is_hashable(mocked_connection): + """Verify cursor description is hashable.""" + cursor = mocked_connection.cursor() + response = { + "col_types": [4, [100, 5], [100, [100, 9]]], + "cols": ["name", "addresses", "matrix"], + "rows": [["foo", ["10.10.10.1"], [[1, 2], [3]]]], + "rowcount": 1, + "duration": 123, + } + with mock.patch.object( + mocked_connection.client, "sql", return_value=response + ): + cursor.execute("") + for column in cursor.description: + hash(column) + + def test_cursor_rowcount(mocked_connection): """Verify the logic of cursor.rowcount""" cursor = mocked_connection.cursor() From 4f1db04a670a45219fa1c3c2322196baa0a9a7dc Mon Sep 17 00:00:00 2001 From: Roman Novatorov Date: Tue, 24 Nov 2026 16:29:47 +0100 Subject: [PATCH 3/3] Use a real bulk response in the executemany description test --- tests/client/test_cursor.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/tests/client/test_cursor.py b/tests/client/test_cursor.py index b43e63d2..35ab8eb9 100644 --- a/tests/client/test_cursor.py +++ b/tests/client/test_cursor.py @@ -135,20 +135,18 @@ def test_cursor_description_extra_col_types(mocked_connection): def test_cursor_description_after_executemany(mocked_connection): - """Verify executemany keeps col_types for description.""" + """Verify description is empty after executemany.""" cursor = mocked_connection.cursor() response = { - "col_types": [4], - "cols": ["name"], - "rows": [["foo"]], - "rowcount": 1, + "cols": [], "duration": 123, + "results": [{"rowcount": 1}], } with mock.patch.object( mocked_connection.client, "sql", return_value=response ): cursor.executemany("", [["foo"]]) - assert [column[1] for column in cursor.description] == [4] + assert cursor.description == () @pytest.mark.parametrize(