Skip to content

Commit 3da0b99

Browse files
add type hints for issues.py and types.py
1 parent 32e7784 commit 3da0b99

File tree

2 files changed

+109
-25
lines changed

2 files changed

+109
-25
lines changed

ydb/issues.py

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,13 @@
22
from google.protobuf import text_format
33
import enum
44
import queue
5+
import typing
56

67
from . import _apis
78

9+
if typing.TYPE_CHECKING:
10+
from _grpc.v4.protos import ydb_issue_message_pb2, ydb_operation_pb2
11+
812

913
_TRANSPORT_STATUSES_FIRST = 401000
1014
_CLIENT_STATUSES_FIRST = 402000
@@ -43,10 +47,26 @@ class StatusCode(enum.IntEnum):
4347
SESSION_POOL_EMPTY = _CLIENT_STATUSES_FIRST + 40
4448

4549

50+
# TODO: convert from proto IssueMessage
51+
class _IssueMessage:
52+
53+
def __init__(
54+
self,
55+
message: str,
56+
issue_code: int,
57+
severity: int,
58+
issues
59+
) -> None:
60+
self.message = message
61+
self.issue_code = issue_code
62+
self.severity = severity
63+
self.issues = issues
64+
65+
4666
class Error(Exception):
4767
status = None
4868

49-
def __init__(self, message, issues=None):
69+
def __init__(self, message: str, issues=None):
5070
super(Error, self).__init__(message)
5171
self.issues = issues
5272
self.message = message
@@ -161,14 +181,14 @@ def __init__(self, message: str):
161181
super().__init__(message)
162182

163183

164-
def _format_issues(issues):
184+
def _format_issues(issues: typing.Iterable[ydb_issue_message_pb2.IssueMessage]) -> str:
165185
if not issues:
166186
return ""
167187

168188
return " ,".join(text_format.MessageToString(issue, as_utf8=False, as_one_line=True) for issue in issues)
169189

170190

171-
def _format_response(response):
191+
def _format_response(response: ydb_operation_pb2.Operation) -> str:
172192
fmt_issues = _format_issues(response.issues)
173193
return f"{fmt_issues} (server_code: {response.status})"
174194

@@ -196,7 +216,7 @@ def _format_response(response):
196216
}
197217

198218

199-
def _process_response(response_proto):
219+
def _process_response(response_proto: ydb_operation_pb2.Operation) -> None:
200220
if response_proto.status not in _success_status_codes:
201221
exc_obj = _server_side_error_map.get(response_proto.status)
202222
raise exc_obj(_format_response(response_proto), response_proto.issues)

ydb/types.py

Lines changed: 85 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -4,73 +4,101 @@
44
import json
55
from . import _utilities, _apis
66
from datetime import date, datetime, timedelta
7+
import typing
78
import uuid
89
import struct
910
from google.protobuf import struct_pb2
1011

12+
from .table import TableClientSettings
13+
14+
15+
if typing.TYPE_CHECKING:
16+
from ._grpc.v4.protos import ydb_value_pb2
17+
1118

1219
_SECONDS_IN_DAY = 60 * 60 * 24
1320
_EPOCH = datetime(1970, 1, 1)
1421

1522

16-
def _from_date(x, table_client_settings):
23+
def _from_date(
24+
x: ydb_value_pb2.Value,
25+
table_client_settings: TableClientSettings
26+
) -> typing.Union[date, int]:
1727
if table_client_settings is not None and table_client_settings._native_date_in_result_sets:
1828
return _EPOCH.date() + timedelta(days=x.uint32_value)
1929
return x.uint32_value
2030

2131

22-
def _to_date(pb, value):
32+
def _to_date(pb: ydb_value_pb2.Value, value: typing.Union[date, int]) -> None:
2333
if isinstance(value, date):
2434
pb.uint32_value = (value - _EPOCH.date()).days
2535
else:
2636
pb.uint32_value = value
2737

2838

29-
def _from_datetime_number(x, table_client_settings):
39+
def _from_datetime_number(
40+
x: typing.Union[float, datetime],
41+
table_client_settings: TableClientSettings
42+
) -> datetime:
3043
if table_client_settings is not None and table_client_settings._native_datetime_in_result_sets:
3144
return datetime.utcfromtimestamp(x)
3245
return x
3346

3447

35-
def _from_json(x, table_client_settings):
48+
def _from_json(
49+
x: typing.Union[str, bytearray, bytes],
50+
table_client_settings: TableClientSettings
51+
):
3652
if table_client_settings is not None and table_client_settings._native_json_in_result_sets:
3753
return json.loads(x)
3854
return x
3955

4056

41-
def _to_uuid(value_pb, table_client_settings):
57+
def _to_uuid(
58+
value_pb: ydb_value_pb2.Value,
59+
table_client_settings: TableClientSettings
60+
) -> uuid.UUID:
4261
return uuid.UUID(bytes_le=struct.pack("QQ", value_pb.low_128, value_pb.high_128))
4362

4463

45-
def _from_uuid(pb, value):
64+
def _from_uuid(pb: ydb_value_pb2.Value, value: uuid.UUID):
4665
pb.low_128 = struct.unpack("Q", value.bytes_le[0:8])[0]
4766
pb.high_128 = struct.unpack("Q", value.bytes_le[8:16])[0]
4867

4968

50-
def _from_interval(value_pb, table_client_settings):
69+
def _from_interval(
70+
value_pb: ydb_value_pb2.Value,
71+
table_client_settings: TableClientSettings
72+
) -> typing.Union[timedelta, int]:
5173
if table_client_settings is not None and table_client_settings._native_interval_in_result_sets:
5274
return timedelta(microseconds=value_pb.int64_value)
5375
return value_pb.int64_value
5476

5577

56-
def _timedelta_to_microseconds(value):
78+
def _timedelta_to_microseconds(value: timedelta) -> int:
5779
return (value.days * _SECONDS_IN_DAY + value.seconds) * 1000000 + value.microseconds
5880

5981

60-
def _to_interval(pb, value):
82+
def _to_interval(pb: ydb_value_pb2.Value, value: typing.Union[timedelta, int]) -> int:
6183
if isinstance(value, timedelta):
6284
pb.int64_value = _timedelta_to_microseconds(value)
6385
else:
6486
pb.int64_value = value
6587

6688

67-
def _from_timestamp(value_pb, table_client_settings):
89+
def _from_timestamp(
90+
value_pb: ydb_value_pb2.Value,
91+
table_client_settings: TableClientSettings
92+
) -> typing.Union[datetime, int]:
6893
if table_client_settings is not None and table_client_settings._native_timestamp_in_result_sets:
6994
return _EPOCH + timedelta(microseconds=value_pb.uint64_value)
7095
return value_pb.uint64_value
7196

7297

73-
def _to_timestamp(pb, value):
98+
def _to_timestamp(
99+
pb: ydb_value_pb2.Value,
100+
value: typing.Union[datetime, int]
101+
) -> int:
74102
if isinstance(value, datetime):
75103
pb.uint64_value = _timedelta_to_microseconds(value - _EPOCH)
76104
else:
@@ -129,13 +157,23 @@ class PrimitiveType(enum.Enum):
129157

130158
DyNumber = _apis.primitive_types.DYNUMBER, "text_value"
131159

132-
def __init__(self, idn, proto_field, to_obj=None, from_obj=None):
160+
def __init__(
161+
self,
162+
idn: ydb_value_pb2.Type.PrimitiveTypeId,
163+
proto_field: typing.Optional[str],
164+
to_obj=None,
165+
from_obj=None
166+
):
133167
self._idn_ = idn
134168
self._to_obj = to_obj
135169
self._from_obj = from_obj
136170
self._proto_field = proto_field
137171

138-
def get_value(self, value_pb, table_client_settings):
172+
def get_value(
173+
self,
174+
value_pb: ydb_value_pb2.Value,
175+
table_client_settings: TableClientSettings
176+
):
139177
"""
140178
Extracts value from protocol buffer
141179
:param value_pb: A protocol buffer
@@ -149,7 +187,7 @@ def get_value(self, value_pb, table_client_settings):
149187

150188
return getattr(value_pb, self._proto_field)
151189

152-
def set_value(self, pb, value):
190+
def set_value(self, pb: ydb_value_pb2.Value, value):
153191
"""
154192
Sets value in a protocol buffer
155193
:param pb: A protocol buffer
@@ -176,7 +214,12 @@ def proto(self):
176214
class DataQuery(object):
177215
__slots__ = ("yql_text", "parameters_types", "name")
178216

179-
def __init__(self, query_id, parameters_types, name=None):
217+
def __init__(
218+
self,
219+
query_id: str,
220+
parameters_types: "dict[str, ydb_value_pb2.Type]",
221+
name: typing.Optional[str] = None
222+
):
180223
self.yql_text = query_id
181224
self.parameters_types = parameters_types
182225
self.name = _utilities.get_query_hash(self.yql_text) if name is None else name
@@ -259,7 +302,10 @@ def __str__(self):
259302
class OptionalType(AbstractTypeBuilder):
260303
__slots__ = ("_repr", "_proto", "_item")
261304

262-
def __init__(self, optional_type):
305+
def __init__(
306+
self,
307+
optional_type: typing.Union[AbstractTypeBuilder, PrimitiveType]
308+
):
263309
"""
264310
Represents optional type that wraps inner type
265311
:param optional_type: An instance of an inner type
@@ -291,7 +337,10 @@ def __str__(self):
291337
class ListType(AbstractTypeBuilder):
292338
__slots__ = ("_repr", "_proto")
293339

294-
def __init__(self, list_type):
340+
def __init__(
341+
self,
342+
list_type: typing.Union[AbstractTypeBuilder, PrimitiveType]
343+
):
295344
"""
296345
:param list_type: List item type builder
297346
"""
@@ -313,7 +362,11 @@ def __str__(self):
313362
class DictType(AbstractTypeBuilder):
314363
__slots__ = ("__repr", "__proto")
315364

316-
def __init__(self, key_type, payload_type):
365+
def __init__(
366+
self,
367+
key_type: typing.Union[AbstractTypeBuilder, PrimitiveType],
368+
payload_type: typing.Union[AbstractTypeBuilder, PrimitiveType]
369+
):
317370
"""
318371
:param key_type: Key type builder
319372
:param payload_type: Payload type builder
@@ -341,7 +394,10 @@ def __init__(self):
341394
self.__elements_repr = []
342395
self.__proto = _apis.ydb_value.Type(tuple_type=_apis.ydb_value.TupleType())
343396

344-
def add_element(self, element_type):
397+
def add_element(
398+
self,
399+
element_type: typing.Union[AbstractTypeBuilder, PrimitiveType]
400+
):
345401
"""
346402
:param element_type: Adds additional element of tuple
347403
:return: self
@@ -366,7 +422,11 @@ def __init__(self):
366422
self.__members_repr = []
367423
self.__proto = _apis.ydb_value.Type(struct_type=_apis.ydb_value.StructType())
368424

369-
def add_member(self, name, member_type):
425+
def add_member(
426+
self,
427+
name: str,
428+
member_type: typing.Union[AbstractTypeBuilder, PrimitiveType]
429+
):
370430
"""
371431
:param name:
372432
:param member_type:
@@ -393,7 +453,11 @@ def __init__(self):
393453
self.__columns_repr = []
394454
self.__proto = _apis.ydb_value.Type(struct_type=_apis.ydb_value.StructType())
395455

396-
def add_column(self, name, column_type):
456+
def add_column(
457+
self,
458+
name: str,
459+
column_type: typing.Union[AbstractTypeBuilder, PrimitiveType]
460+
):
397461
"""
398462
:param name: A column name
399463
:param column_type: A column type

0 commit comments

Comments
 (0)