New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add a generic data type converter to the Cursor
object
#442
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
[tool.mypy] | ||
|
||
# Needed until `mypy-0.990` for `ConverterDefinition` in `converter.py`. | ||
# https://github.com/python/mypy/issues/731#issuecomment-1260976955 | ||
enable_recursive_aliases = true |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
# -*- coding: utf-8; -*- | ||
# | ||
# Licensed to CRATE Technology GmbH ("Crate") under one or more contributor | ||
# license agreements. See the NOTICE file distributed with this work for | ||
# additional information regarding copyright ownership. Crate licenses | ||
# this file to you under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. You may | ||
# obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | ||
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | ||
# License for the specific language governing permissions and limitations | ||
# under the License. | ||
# | ||
# However, if you have executed another commercial license agreement | ||
# with Crate these terms will supersede the license and you may use the | ||
# software solely pursuant to the terms of the relevant commercial agreement. | ||
""" | ||
Machinery for converting CrateDB database types to native Python data types. | ||
|
||
https://crate.io/docs/crate/reference/en/latest/interfaces/http.html#column-types | ||
""" | ||
import ipaddress | ||
from copy import deepcopy | ||
from datetime import datetime | ||
from enum import Enum | ||
from typing import Any, Callable, Dict, List, Optional, Union | ||
|
||
ConverterFunction = Callable[[Optional[Any]], Optional[Any]] | ||
ColTypesDefinition = Union[int, List[Union[int, "ColTypesDefinition"]]] | ||
|
||
|
||
def _to_ipaddress(value: Optional[str]) -> Optional[Union[ipaddress.IPv4Address, ipaddress.IPv6Address]]: | ||
""" | ||
https://docs.python.org/3/library/ipaddress.html | ||
""" | ||
if value is None: | ||
return None | ||
return ipaddress.ip_address(value) | ||
|
||
|
||
def _to_datetime(value: Optional[float]) -> Optional[datetime]: | ||
""" | ||
https://docs.python.org/3/library/datetime.html | ||
""" | ||
if value is None: | ||
return None | ||
return datetime.utcfromtimestamp(value / 1e3) | ||
|
||
|
||
def _to_default(value: Optional[Any]) -> Optional[Any]: | ||
return value | ||
|
||
|
||
# Symbolic aliases for the numeric data type identifiers defined by the CrateDB HTTP interface. | ||
# https://crate.io/docs/crate/reference/en/latest/interfaces/http.html#column-types | ||
class DataType(Enum): | ||
NULL = 0 | ||
NOT_SUPPORTED = 1 | ||
CHAR = 2 | ||
BOOLEAN = 3 | ||
TEXT = 4 | ||
IP = 5 | ||
DOUBLE = 6 | ||
REAL = 7 | ||
SMALLINT = 8 | ||
INTEGER = 9 | ||
BIGINT = 10 | ||
TIMESTAMP_WITH_TZ = 11 | ||
OBJECT = 12 | ||
GEOPOINT = 13 | ||
GEOSHAPE = 14 | ||
TIMESTAMP_WITHOUT_TZ = 15 | ||
UNCHECKED_OBJECT = 16 | ||
REGPROC = 19 | ||
TIME = 20 | ||
OIDVECTOR = 21 | ||
NUMERIC = 22 | ||
REGCLASS = 23 | ||
DATE = 24 | ||
BIT = 25 | ||
JSON = 26 | ||
CHARACTER = 27 | ||
ARRAY = 100 | ||
|
||
|
||
ConverterMapping = Dict[DataType, ConverterFunction] | ||
|
||
|
||
# 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, | ||
} | ||
|
||
|
||
class Converter: | ||
def __init__( | ||
self, | ||
mappings: Optional[ConverterMapping] = None, | ||
default: ConverterFunction = _to_default, | ||
) -> None: | ||
self._mappings = mappings or {} | ||
self._default = default | ||
|
||
def get(self, type_: ColTypesDefinition) -> ConverterFunction: | ||
if isinstance(type_, int): | ||
return self._mappings.get(DataType(type_), self._default) | ||
type_, inner_type = type_ | ||
if DataType(type_) is not DataType.ARRAY: | ||
raise ValueError(f"Data type {type_} is not implemented as collection type") | ||
|
||
inner_convert = self.get(inner_type) | ||
|
||
def convert(value: Any) -> Optional[List[Any]]: | ||
if value is None: | ||
return None | ||
return [inner_convert(x) for x in value] | ||
|
||
return convert | ||
|
||
|
||
class DefaultTypeConverter(Converter): | ||
def __init__(self, more_mappings: Optional[ConverterMapping] = None) -> None: | ||
mappings: ConverterMapping = {} | ||
mappings.update(deepcopy(_DEFAULT_CONVERTERS)) | ||
if more_mappings: | ||
mappings.update(deepcopy(more_mappings)) | ||
super().__init__( | ||
mappings=mappings, default=_to_default | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Dear @mfussenegger, @matriv, and @seut,
regarding @mfussenegger's proposal to let the user optionally specify a time zone, and make the machinery return a timezone-aware datetime object, I see two options here.
Let's assume the user defines a custom timezone object like
and a timestamp in Epoch like
On this spot, which variant would be semantically the right one? Note that
datetime.utcfromtimestamp
does not accept thetz
keyword argument, it will always return a naive datetime object withtzinfo=None
.We can either use
datetime.fromtimestamp
, which does accept thetz
keyword argument.Or we can replace the
tzinfo
on the naive datetime object returned byutcfromtimestamp
, making it timezone-aware.I think option 1. is the right choice. So the implementation would look like something along the lines of:
What do you think?
With kind regards,
Andreas.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Another implementation could look like this, it is always using
datetime.fromtimestamp(value / 1e3, tz=self.timezone)
, whereself.timezone
would bedatetime.timezone.utc
by default, i.e. it will always return timezone-aware datetime objects.While definitively easier and more straight-forward, it could be less performant when not aiming to use timezone-aware datetime objects and stay in "naive" land on purpose.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When thinking about it once more, I think I would prefer the implementation variant outlined in my latest post. In this way, it is always consistent that timezone-aware datetime objects are returned from the data converter machinery.
I think when users are aiming for raw speed, they would completely opt out of the data type converter machinery at all.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi again. Talk is cheap. I've converged a few more thoughts about this into a proposed patch at #445, completely separating the topic of timezone-aware
datetime
handling from this one.