diff --git a/CHANGES.rst b/CHANGES.rst index a671407a..5f8c92cf 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 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. - 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..227577c7 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 tuple 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 tuple, 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..6d9a2a18 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 tuple 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..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 @@ -305,14 +312,24 @@ 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 tuple 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): + 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 239f58a0..35ab8eb9 100644 --- a/tests/client/test_cursor.py +++ b/tests/client/test_cursor.py @@ -83,6 +83,156 @@ 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 through as nested tuples.""" + 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 description is empty after executemany.""" + cursor = mocked_connection.cursor() + response = { + "cols": [], + "duration": 123, + "results": [{"rowcount": 1}], + } + with mock.patch.object( + mocked_connection.client, "sql", return_value=response + ): + cursor.executemany("", [["foo"]]) + assert cursor.description == () + + +@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_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()