Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ Changes for crate
Unreleased
================

- Breaking change: ``DefaultTypeConverter`` now decodes ``DataType.UUID``
columns to Python ``uuid.UUID`` objects instead of returning the raw string.

- Added CrateDB column type identifiers to ``DataType``: ``INTERVAL`` (17),
``ROW`` (18), ``FLOAT_VECTOR`` (28), ``UUID`` (29), and ``REGTYPE`` (30).
Fixed ``Converter.get()`` raising ``ValueError`` for column type identifiers
it does not know. Unknown identifiers now fall back to the default converter.

- Breaking change: ``connect()`` now raises ``ConnectionError`` immediately if
no configured server node responds.

Expand Down
25 changes: 24 additions & 1 deletion docs/by-example/cursor.rst
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ Python data type conversion

The cursor object can optionally convert database types to native Python data
types. Currently, this is implemented for the CrateDB data types ``IP``,
``TIMESTAMP``, ``TIMETZ``, and ``BIT`` on behalf of the
``TIMESTAMP``, ``TIMETZ``, ``BIT``, and ``UUID`` on behalf of the
``DefaultTypeConverter``.

>>> cursor = connection.cursor(converter=DefaultTypeConverter())
Expand Down Expand Up @@ -403,6 +403,29 @@ Executing the query and fetching the decoded result:
['0110']


CrateDB's ``UUID`` type is returned over HTTP as a string. It is decoded to a
Python ``uuid.UUID`` object.

>>> cursor = connection.cursor(converter=DefaultTypeConverter())

.. hide: set up the mocked response::

>>> connection.client.set_next_response({
... "col_types": [29],
... "rows":[ [ "a5b3c1e0-1b7f-4f3e-9a2d-6c4e8f0a1b2c" ] ],
... "cols":[ "id" ],
... "rowcount":1,
... "duration":1
... })

Executing the query and fetching the decoded result:

>>> cursor.execute("select 'a5b3c1e0-1b7f-4f3e-9a2d-6c4e8f0a1b2c'::uuid")

>>> cursor.fetchone()
[UUID('a5b3c1e0-1b7f-4f3e-9a2d-6c4e8f0a1b2c')]


Custom data type conversion
===========================

Expand Down
35 changes: 33 additions & 2 deletions src/crate/client/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import datetime as dt
import ipaddress
import re
import uuid
from copy import deepcopy
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Union
Expand Down Expand Up @@ -89,6 +90,17 @@ def _to_bit_string(value: Optional[str]) -> Optional[str]:
return match.group(1)


def _to_uuid(value: Optional[str]) -> Optional[uuid.UUID]:
"""
Convert a CrateDB UUID wire value to a Python ``uuid.UUID``.

https://docs.python.org/3/library/uuid.html
"""
if value is None:
return None
return uuid.UUID(value)


def _to_default(value: Optional[Any]) -> Optional[Any]:
return value

Expand All @@ -113,6 +125,8 @@ class DataType(Enum):
GEOSHAPE = 14
TIMESTAMP_WITHOUT_TZ = 15
UNCHECKED_OBJECT = 16
INTERVAL = 17
ROW = 18
REGPROC = 19
TIME = 20
OIDVECTOR = 21
Expand All @@ -122,19 +136,33 @@ class DataType(Enum):
BIT = 25
JSON = 26
CHARACTER = 27
FLOAT_VECTOR = 28
UUID = 29
REGTYPE = 30
ARRAY = 100


ConverterMapping = Dict[DataType, ConverterFunction]


def _resolve(type_: Any) -> Optional[DataType]:
"""
Map a wire type identifier to a `DataType`.
"""
try:
return DataType(type_)
except ValueError:
return None


# Map data type identifier to converter function.
_DEFAULT_CONVERTERS: ConverterMapping = {
DataType.IP: _to_ipaddress,
DataType.TIMESTAMP_WITH_TZ: _to_datetime,
DataType.TIMESTAMP_WITHOUT_TZ: _to_datetime,
DataType.TIME: _to_time,
DataType.BIT: _to_bit_string,
DataType.UUID: _to_uuid,
}


Expand All @@ -149,9 +177,12 @@ def __init__(

def get(self, type_: ColTypesDefinition) -> ConverterFunction:
if isinstance(type_, int):
return self._mappings.get(DataType(type_), self._default)
data_type = _resolve(type_)
if data_type is None:
return self._default
return self._mappings.get(data_type, self._default)
type_, inner_type = type_
if DataType(type_) is not DataType.ARRAY:
if _resolve(type_) is not DataType.ARRAY:
raise ValueError(
f"Data type {type_} is not implemented as collection type"
)
Expand Down
Loading
Loading