Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
singlestore-labs
GitHub Repository: singlestore-labs/singlestoredb-python
Path: blob/main/singlestoredb/utils/convert_rows.py
469 views
1
#!/usr/bin/env python
2
"""Data value conversion utilities."""
3
from typing import Any
4
from typing import List
5
from typing import Optional
6
from typing import Tuple
7
from typing import Union
8
9
10
def convert_row(
11
values: Optional[Union[List[Any], Tuple[Any, ...]]],
12
converters: List[Any],
13
) -> Optional[Tuple[Any, ...]]:
14
"""
15
Convert a row of data values.
16
17
Parameters
18
----------
19
values : tuple or None
20
Tuple containing values in a row of data
21
converters : list[tuple]
22
List of two-element tuples containing a column index and a converter
23
function. The column index specifies which column to apply the function to.
24
25
Returns
26
-------
27
tuple or None
28
29
"""
30
if values is None:
31
return None
32
if not converters:
33
return tuple(values)
34
values = list(values)
35
for i, conv in enumerate(converters):
36
idx, encoding, func = conv
37
value = values[idx]
38
if encoding is not None and value is not None:
39
value = value.decode(encoding)
40
if func is not None:
41
values[idx] = func(value)
42
else:
43
values[idx] = value
44
return tuple(values)
45
46
47
def convert_rows(rows: List[Any], converters: List[Any]) -> List[Any]:
48
"""
49
Convert rows of data values.
50
51
Parameters
52
----------
53
rows : list of tuples or None
54
Rows of data from a query
55
converters : list[tuple]
56
List of two-element tuples containing a column index and a converter
57
function. The column index specifies which column to apply the function to.
58
59
Returns
60
-------
61
list of tuples
62
63
"""
64
if not rows or not converters:
65
return rows
66
rows = list(rows)
67
for i, row in enumerate(rows):
68
rows[i] = convert_row(row, converters=converters)
69
return rows
70
71