Skip to content

Commit b21c38e

Browse files
committed
Data type converter: Support converting elements of collections (ARRAY)
1 parent d483667 commit b21c38e

File tree

2 files changed

+54
-4
lines changed

2 files changed

+54
-4
lines changed

src/crate/client/converter.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,7 @@
2727
from copy import deepcopy
2828
from datetime import datetime
2929
from enum import Enum
30-
from typing import Any, Callable, Dict, Optional, Union
31-
30+
from typing import Any, Callable, Dict, Optional, Union, List
3231

3332
InputVal = Any
3433

@@ -128,8 +127,17 @@ def get_mapping_key(type_: Union[CrateDatatypeIdentifier, int]) -> int:
128127
return type_
129128

130129
def convert(self, type_: int, value: Optional[Any]) -> Optional[Any]:
131-
converter = self.get(type_)
132-
return converter(value)
130+
if isinstance(type_, List):
131+
type_, inner_type = type_
132+
assert type_ == 100, f"Type {type_} not implemented as collection type"
133+
if value is None:
134+
result = self.convert(inner_type, None)
135+
else:
136+
result = [self.convert(inner_type, item) for item in value]
137+
else:
138+
converter = self.get(type_)
139+
result = converter(value)
140+
return result
133141

134142

135143
class DefaultTypeConverter(Converter):

src/crate/client/test_cursor.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,45 @@ def test_execute_with_converter(self):
9292
self.assertEqual(result, ['foo', '10.10.10.1', 1658167836758, "B'0110'"])
9393

9494
conn.close()
95+
96+
def test_execute_array_with_converter(self):
97+
client = ClientMocked()
98+
conn = connect(client=client)
99+
converter = Cursor.get_default_converter()
100+
cursor = conn.cursor(converter=converter)
101+
102+
conn.client.set_next_response({
103+
"col_types": [4, [100, 5]],
104+
"cols": ["name", "address"],
105+
"rows": [["foo", ["10.10.10.1", "10.10.10.2"]]],
106+
"rowcount": 1,
107+
"duration": 123
108+
})
109+
110+
cursor.execute("")
111+
result = cursor.fetchone()
112+
self.assertEqual(result, [
113+
'foo',
114+
[IPv4Address('10.10.10.1'), IPv4Address('10.10.10.2')],
115+
])
116+
117+
def test_execute_nested_array_with_converter(self):
118+
client = ClientMocked()
119+
conn = connect(client=client)
120+
converter = Cursor.get_default_converter()
121+
cursor = conn.cursor(converter=converter)
122+
123+
conn.client.set_next_response({
124+
"col_types": [4, [100, [100, 5]]],
125+
"cols": ["name", "address_buckets"],
126+
"rows": [["foo", [["10.10.10.1", "10.10.10.2"], ["10.10.10.3"], [], None]]],
127+
"rowcount": 1,
128+
"duration": 123
129+
})
130+
131+
cursor.execute("")
132+
result = cursor.fetchone()
133+
self.assertEqual(result, [
134+
'foo',
135+
[[IPv4Address('10.10.10.1'), IPv4Address('10.10.10.2')], [IPv4Address('10.10.10.3')], [], None],
136+
])

0 commit comments

Comments
 (0)