diff --git a/iotdb-client/client-py/iotdb/Session.py b/iotdb-client/client-py/iotdb/Session.py index b9bccd0509786..8c9cc87a7a920 100644 --- a/iotdb-client/client-py/iotdb/Session.py +++ b/iotdb-client/client-py/iotdb/Session.py @@ -65,6 +65,7 @@ from .tsfile.utils.date_utils import parse_date_to_int from .utils import rpc_utils from .utils.exception import IoTDBConnectionException, RedirectException +from .utils.IoTDBConstants import TSDataType logger = logging.getLogger("IoTDB") warnings.simplefilter("always", DeprecationWarning) @@ -1723,33 +1724,27 @@ def value_to_bytes(data_types, values): format_str_list = [">"] values_tobe_packed = [] for data_type, value in zip(data_types, values): - # BOOLEAN - if data_type == 0: + if data_type == TSDataType.BOOLEAN: format_str_list.append("c?") - values_tobe_packed.append(b"\x00") + values_tobe_packed.append(bytes([TSDataType.BOOLEAN])) values_tobe_packed.append(value) - # INT32 - elif data_type == 1: + elif data_type == TSDataType.INT32: format_str_list.append("ci") - values_tobe_packed.append(b"\x01") + values_tobe_packed.append(bytes([TSDataType.INT32])) values_tobe_packed.append(value) - # INT64 - elif data_type == 2: + elif data_type == TSDataType.INT64: format_str_list.append("cq") - values_tobe_packed.append(b"\x02") + values_tobe_packed.append(bytes([TSDataType.INT64])) values_tobe_packed.append(value) - # FLOAT - elif data_type == 3: + elif data_type == TSDataType.FLOAT: format_str_list.append("cf") - values_tobe_packed.append(b"\x03") + values_tobe_packed.append(bytes([TSDataType.FLOAT])) values_tobe_packed.append(value) - # DOUBLE - elif data_type == 4: + elif data_type == TSDataType.DOUBLE: format_str_list.append("cd") - values_tobe_packed.append(b"\x04") + values_tobe_packed.append(bytes([TSDataType.DOUBLE])) values_tobe_packed.append(value) - # TEXT - elif data_type == 5: + elif data_type == TSDataType.TEXT: if isinstance(value, str): value_bytes = bytes(value, "utf-8") else: @@ -1757,29 +1752,25 @@ def value_to_bytes(data_types, values): format_str_list.append("ci") format_str_list.append(str(len(value_bytes))) format_str_list.append("s") - values_tobe_packed.append(b"\x05") + values_tobe_packed.append(bytes([TSDataType.TEXT])) values_tobe_packed.append(len(value_bytes)) values_tobe_packed.append(value_bytes) - # TIMESTAMP - elif data_type == 8: + elif data_type == TSDataType.TIMESTAMP: format_str_list.append("cq") - values_tobe_packed.append(b"\x08") + values_tobe_packed.append(bytes([TSDataType.TIMESTAMP])) values_tobe_packed.append(value) - # DATE - elif data_type == 9: + elif data_type == TSDataType.DATE: format_str_list.append("ci") - values_tobe_packed.append(b"\x09") + values_tobe_packed.append(bytes([TSDataType.DATE])) values_tobe_packed.append(parse_date_to_int(value)) - # BLOB - elif data_type == 10: + elif data_type == TSDataType.BLOB: format_str_list.append("ci") format_str_list.append(str(len(value))) format_str_list.append("s") - values_tobe_packed.append(b"\x0a") + values_tobe_packed.append(bytes([TSDataType.BLOB])) values_tobe_packed.append(len(value)) values_tobe_packed.append(value) - # STRING - elif data_type == 11: + elif data_type == TSDataType.STRING: if isinstance(value, str): value_bytes = bytes(value, "utf-8") else: @@ -1787,7 +1778,15 @@ def value_to_bytes(data_types, values): format_str_list.append("ci") format_str_list.append(str(len(value_bytes))) format_str_list.append("s") - values_tobe_packed.append(b"\x0b") + values_tobe_packed.append(bytes([TSDataType.STRING])) + values_tobe_packed.append(len(value_bytes)) + values_tobe_packed.append(value_bytes) + elif data_type == TSDataType.OBJECT: + value_bytes = value if isinstance(value, bytes) else bytes(value) + format_str_list.append("ci") + format_str_list.append(str(len(value_bytes))) + format_str_list.append("s") + values_tobe_packed.append(bytes([TSDataType.OBJECT])) values_tobe_packed.append(len(value_bytes)) values_tobe_packed.append(value_bytes) else: diff --git a/iotdb-client/client-py/iotdb/tsfile/utils/tsblock_serde.py b/iotdb-client/client-py/iotdb/tsfile/utils/tsblock_serde.py index cc5577e885c62..94dac4a2bfe00 100644 --- a/iotdb-client/client-py/iotdb/tsfile/utils/tsblock_serde.py +++ b/iotdb-client/client-py/iotdb/tsfile/utils/tsblock_serde.py @@ -16,8 +16,12 @@ # under the License. # +from enum import IntEnum, unique + import numpy as np +from iotdb.utils.IoTDBConstants import TS_BLOCK_VALUE_TYPES, TSDataType + # Serialized tsBlock: # +-------------+---------------+---------+------------+-----------+----------+ # | val col cnt | val col types | pos cnt | encodings | time col | val col | @@ -26,6 +30,26 @@ # +-------------+---------------+---------+------------+-----------+----------+ +@unique +class TsBlockColumnEncoding(IntEnum): + """ + TsBlock column serialization encoding id on the wire. + Not the same enum as TSEncoding in IoTDBConstants (series encoding in schema). + """ + + PLAIN_BOOLEAN = 0 + PLAIN_INT32 = 1 + PLAIN_INT64 = 2 + PLAIN_BINARY = 3 + RUN_LENGTH = 4 + DICTIONARY = 5 + + +_TS_BLOCK_VALUE_TYPE_ARRAY = np.array( + [int(t) for t in TS_BLOCK_VALUE_TYPES], dtype=np.uint8 +) + + def deserialize(buffer): value_column_count, buffer = read_int_from_buffer(buffer) data_types, buffer = read_column_types(buffer, value_column_count) @@ -34,7 +58,7 @@ def deserialize(buffer): column_encodings, buffer = read_column_encoding(buffer, value_column_count + 1) time_column_values, _, buffer = read_column( - column_encodings[0], buffer, 2, position_count + column_encodings[0], buffer, TSDataType.INT64, position_count ) column_values = [] null_indicators = [] @@ -73,7 +97,7 @@ def read_from_buffer(buffer, size): def read_column_types(buffer, value_column_count): data_types = np.frombuffer(buffer, dtype=np.uint8, count=value_column_count) new_buffer = buffer[value_column_count:] - if not np.all(np.isin(data_types, (0, 1, 2, 3, 4, 5, 8, 9, 10, 11))): + if not np.all(np.isin(data_types, _TS_BLOCK_VALUE_TYPE_ARRAY)): raise Exception("Invalid data type encountered: " + str(data_types)) return data_types, new_buffer @@ -113,9 +137,9 @@ def read_int64_column(buffer, data_type, position_count): else: size = np.count_nonzero(~null_indicators) - if data_type == 2: + if data_type == TSDataType.INT64: dtype = ">i8" - elif data_type == 4: + elif data_type == TSDataType.DOUBLE: dtype = ">f8" else: raise Exception("Invalid data type: " + str(data_type)) @@ -139,9 +163,9 @@ def read_int32_column(buffer, data_type, position_count): else: size = np.count_nonzero(~null_indicators) - if (data_type == 1) or (data_type == 9): + if data_type in (TSDataType.INT32, TSDataType.DATE): dtype = ">i4" - elif data_type == 3: + elif data_type == TSDataType.FLOAT: dtype = ">f4" else: raise Exception("Invalid data type: " + str(data_type)) @@ -159,8 +183,8 @@ def read_int32_column(buffer, data_type, position_count): def read_byte_column(buffer, data_type, position_count): - if data_type != 0: - raise Exception("Invalid data type: " + data_type) + if data_type != TSDataType.BOOLEAN: + raise Exception("Invalid data type: " + str(data_type)) null_indicators, buffer = deserialize_null_indicators(buffer, position_count) res, buffer = deserialize_from_boolean_array(buffer, position_count) return res, null_indicators, buffer @@ -190,8 +214,8 @@ def deserialize_from_boolean_array(buffer, size): def read_binary_column(buffer, data_type, position_count): - if data_type != 5: - raise Exception("Invalid data type: " + data_type) + if data_type not in (TSDataType.TEXT, TSDataType.OBJECT): + raise Exception("Invalid data type: " + str(data_type)) null_indicators, buffer = deserialize_null_indicators(buffer, position_count) if null_indicators is None: @@ -229,10 +253,12 @@ def read_run_length_column(buffer, data_type, position_count): def repeat(column, data_type, position_count): - if data_type in (0, 5): + if data_type in (TSDataType.BOOLEAN, TSDataType.TEXT, TSDataType.OBJECT): if column.size == 1: return np.full( - position_count, column[0], dtype=(bool if data_type == 0 else object) + position_count, + column[0], + dtype=(bool if data_type == TSDataType.BOOLEAN else object), ) else: return np.array(column * position_count, dtype=object) @@ -248,18 +274,19 @@ def read_dictionary_column(buffer, data_type, position_count): ENCODING_FUNC_MAP = { - 0: read_byte_column, - 1: read_int32_column, - 2: read_int64_column, - 3: read_binary_column, - 4: read_run_length_column, - 5: read_dictionary_column, + TsBlockColumnEncoding.PLAIN_BOOLEAN: read_byte_column, + TsBlockColumnEncoding.PLAIN_INT32: read_int32_column, + TsBlockColumnEncoding.PLAIN_INT64: read_int64_column, + TsBlockColumnEncoding.PLAIN_BINARY: read_binary_column, + TsBlockColumnEncoding.RUN_LENGTH: read_run_length_column, + TsBlockColumnEncoding.DICTIONARY: read_dictionary_column, } def read_column(encoding, buffer, data_type, position_count): try: - func = ENCODING_FUNC_MAP[encoding] - except KeyError: + enc = TsBlockColumnEncoding(int(encoding)) + func = ENCODING_FUNC_MAP[enc] + except (ValueError, KeyError): raise Exception("Unsupported encoding: " + str(encoding)) return func(buffer, data_type, position_count) diff --git a/iotdb-client/client-py/iotdb/utils/Field.py b/iotdb-client/client-py/iotdb/utils/Field.py index d9a0ee77776ec..88f2c159d295f 100644 --- a/iotdb-client/client-py/iotdb/utils/Field.py +++ b/iotdb-client/client-py/iotdb/utils/Field.py @@ -60,6 +60,8 @@ def copy(field): or output.get_data_type() == TSDataType.BLOB ): output.set_binary_value(field.get_binary_value()) + elif output.get_data_type() == TSDataType.OBJECT: + output.value = field.value else: raise Exception( "unsupported data type {}".format(output.get_data_type()) @@ -150,6 +152,10 @@ def set_binary_value(self, value: bytes): def get_binary_value(self): if self.__data_type is None: raise Exception("Null Field Exception!") + if self.__data_type == TSDataType.OBJECT: + raise RuntimeError( + "OBJECT type only supports get_string_value / get_object_value, not get_binary_value" + ) if ( self.__data_type != TSDataType.TEXT and self.__data_type != TSDataType.STRING @@ -185,14 +191,11 @@ def get_date_value(self): def get_string_value(self): if self.__data_type is None or self.value is None or self.value is pd.NA: return "None" - # TEXT, STRING - if self.__data_type == 5 or self.__data_type == 11: + if self.__data_type in (TSDataType.TEXT, TSDataType.STRING): return self.value.decode("utf-8") - # BLOB - elif self.__data_type == 10: + elif self.__data_type == TSDataType.BLOB: return str(hex(int.from_bytes(self.value, byteorder="big"))) - # TIMESTAMP - elif self.__data_type == 8: + elif self.__data_type == TSDataType.TIMESTAMP: return isoformat( convert_to_timestamp(self.value, self.__precision, self.__timezone), self.__precision, @@ -206,27 +209,29 @@ def __str__(self): def get_object_value(self, data_type): """ + OBJECT values are returned as raw query-result bytes. + :param data_type: TSDataType """ if self.__data_type is None or self.value is None or self.value is pd.NA: return None - if data_type == 0: + if data_type == TSDataType.BOOLEAN: return bool(self.value) - elif data_type == 1: + elif data_type == TSDataType.INT32: return np.int32(self.value) - elif data_type == 2: + elif data_type == TSDataType.INT64: return np.int64(self.value) - elif data_type == 3: + elif data_type == TSDataType.FLOAT: return np.float32(self.value) - elif data_type == 4: + elif data_type == TSDataType.DOUBLE: return np.float64(self.value) - elif data_type == 8: + elif data_type == TSDataType.TIMESTAMP: return convert_to_timestamp(self.value, self.__precision, self.__timezone) - elif data_type == 9: + elif data_type == TSDataType.DATE: return parse_int_to_date(self.value) - elif data_type == 5 or data_type == 11: + elif data_type in (TSDataType.TEXT, TSDataType.STRING): return self.value.decode("utf-8") - elif data_type == 10: + elif data_type in (TSDataType.BLOB, TSDataType.OBJECT): return self.value else: raise RuntimeError("Unsupported data type:" + str(data_type)) diff --git a/iotdb-client/client-py/iotdb/utils/IoTDBConstants.py b/iotdb-client/client-py/iotdb/utils/IoTDBConstants.py index 4b9082b5353fd..fb569eaa7ad7d 100644 --- a/iotdb-client/client-py/iotdb/utils/IoTDBConstants.py +++ b/iotdb-client/client-py/iotdb/utils/IoTDBConstants.py @@ -32,6 +32,7 @@ class TSDataType(IntEnum): DATE = 9 BLOB = 10 STRING = 11 + OBJECT = 12 def np_dtype(self): return { @@ -45,9 +46,76 @@ def np_dtype(self): TSDataType.DATE: date, TSDataType.BLOB: bytes, TSDataType.STRING: str, + TSDataType.OBJECT: np.dtype("O"), }[self] +# --- Groupings for tablet serialization and TsBlock / RPC result handling (protocol type bytes) --- + +TS_TABLET_NUMERIC_FIXED = frozenset( + { + TSDataType.BOOLEAN, + TSDataType.INT32, + TSDataType.INT64, + TSDataType.FLOAT, + TSDataType.DOUBLE, + TSDataType.TIMESTAMP, + } +) + +TS_TABLET_LENGTH_PREFIXED = frozenset( + { + TSDataType.TEXT, + TSDataType.STRING, + TSDataType.BLOB, + TSDataType.OBJECT, + } +) + +TS_BLOCK_VALUE_TYPES = frozenset( + { + TSDataType.BOOLEAN, + TSDataType.INT32, + TSDataType.INT64, + TSDataType.FLOAT, + TSDataType.DOUBLE, + TSDataType.TEXT, + TSDataType.TIMESTAMP, + TSDataType.DATE, + TSDataType.BLOB, + TSDataType.STRING, + TSDataType.OBJECT, + } +) + +TS_RPC_BUFFER_AS_NUMPY = frozenset( + { + TSDataType.BOOLEAN, + TSDataType.INT32, + TSDataType.INT64, + TSDataType.FLOAT, + TSDataType.DOUBLE, + TSDataType.BLOB, + TSDataType.OBJECT, + } +) + +TS_RPC_BUFFER_UTF8_STRING = frozenset({TSDataType.TEXT, TSDataType.STRING}) + +TS_RPC_NO_BYTESWAP = frozenset({TSDataType.BLOB, TSDataType.OBJECT}) + +TS_RPC_NULLABLE_OBJECT_COLUMNS = frozenset( + { + TSDataType.TEXT, + TSDataType.STRING, + TSDataType.BLOB, + TSDataType.OBJECT, + TSDataType.DATE, + TSDataType.TIMESTAMP, + } +) + + @unique class TSEncoding(IntEnum): PLAIN = 0 diff --git a/iotdb-client/client-py/iotdb/utils/NumpyTablet.py b/iotdb-client/client-py/iotdb/utils/NumpyTablet.py index f293c1ce12c6e..40e8633b3cbc6 100644 --- a/iotdb-client/client-py/iotdb/utils/NumpyTablet.py +++ b/iotdb-client/client-py/iotdb/utils/NumpyTablet.py @@ -23,8 +23,13 @@ from typing import List from iotdb.tsfile.utils.date_utils import parse_date_to_int -from iotdb.utils.IoTDBConstants import TSDataType +from iotdb.utils.IoTDBConstants import ( + TSDataType, + TS_TABLET_LENGTH_PREFIXED, + TS_TABLET_NUMERIC_FIXED, +) from iotdb.utils.BitMap import BitMap +from iotdb.utils.object_column import encode_object_cell from iotdb.utils.Tablet import ColumnType @@ -59,6 +64,7 @@ def __init__( For BLOB columns, use np.array(blobs, dtype=object) on the original Python bytes to preserve trailing zeros. Fixed-width byte arrays treat trailing zeros as padding. + Use object dtype for pre-encoded OBJECT cells to preserve all bytes. :param timestamps: ndarray, contains the timestamps :param bitmaps: BitMap list, one bitmap records the position of none value in a column :param column_types: ColumnType List, marking the type of each column, can be none for tree-view interfaces. @@ -110,6 +116,30 @@ def __init__( else: self.__column_types = column_types + def add_value_object( + self, + row_index: int, + column_index: int, + is_eof: bool, + offset: int, + content: bytes, + ): + """ + Same semantics as Tablet.add_value_object; NumpyTablet stores one ndarray per column. + """ + if row_index < 0 or row_index >= self.__row_number: + raise IndexError("row_index out of range") + if column_index < 0 or column_index >= self.__column_number: + raise IndexError("column_index out of range") + if self.__data_types[column_index] != TSDataType.OBJECT: + raise TypeError( + "add_value_object requires TSDataType.OBJECT column, got %s" + % self.__data_types[column_index] + ) + self.__values[column_index][row_index] = encode_object_cell( + is_eof, offset, content + ) + @staticmethod def _copy_blob_column(column): # Object dtype preserves the length of each BLOB, including trailing zeros. @@ -176,23 +206,30 @@ def get_binary_timestamps(self): def get_binary_values(self): bs_len = 0 bs_list = [] - for data_type, value in zip(self.__data_types, self.__values): - # BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TIMESTAMP - if ( - data_type == 0 - or data_type == 1 - or data_type == 2 - or data_type == 3 - or data_type == 4 - or data_type == 8 - ): + for column_index, (data_type, value) in enumerate( + zip(self.__data_types, self.__values) + ): + if data_type in TS_TABLET_NUMERIC_FIXED: bs = value.tobytes() - # TEXT, STRING, BLOB - elif data_type == 5 or data_type == 11 or data_type == 10: + elif data_type in TS_TABLET_LENGTH_PREFIXED: format_str_list = [">"] values_tobe_packed = [] - for cell in value: - if isinstance(cell, str): + for row_index, cell in enumerate(value): + if data_type == TSDataType.OBJECT: + if isinstance(cell, (bytes, bytearray)): + value_bytes = bytes(cell) + elif ( + cell is None + and self.bitmaps is not None + and self.bitmaps[column_index] is not None + and self.bitmaps[column_index].is_marked(row_index) + ): + value_bytes = b"" + else: + raise TypeError( + "OBJECT column must be bytes or a marked null" + ) + elif isinstance(cell, str): value_bytes = bytes(cell, "utf-8") else: value_bytes = cell @@ -203,8 +240,7 @@ def get_binary_values(self): values_tobe_packed.append(value_bytes) format_str = "".join(format_str_list) bs = struct.pack(format_str, *values_tobe_packed) - # DATE - elif data_type == 9: + elif data_type == TSDataType.DATE: bs = ( np.vectorize(parse_date_to_int)(value) .astype(np.dtype(">i4")) diff --git a/iotdb-client/client-py/iotdb/utils/SessionDataSet.py b/iotdb-client/client-py/iotdb/utils/SessionDataSet.py index 3f92c78fb6a48..e2033cfa93fe3 100644 --- a/iotdb-client/client-py/iotdb/utils/SessionDataSet.py +++ b/iotdb-client/client-py/iotdb/utils/SessionDataSet.py @@ -70,7 +70,7 @@ def __init__( self.__field_list = [ ( Field(data_type, timezone=zone_id, precision=time_precision) - if data_type == 8 + if data_type == TSDataType.TIMESTAMP else Field(data_type) ) for data_type in self.iotdb_rpc_data_set.get_column_types() @@ -79,7 +79,7 @@ def __init__( self.__field_list = [ ( Field(data_type, timezone=zone_id, precision=time_precision) - if data_type == 8 + if data_type == TSDataType.TIMESTAMP else Field(data_type) ) for data_type in self.iotdb_rpc_data_set.get_column_types()[1:] diff --git a/iotdb-client/client-py/iotdb/utils/Tablet.py b/iotdb-client/client-py/iotdb/utils/Tablet.py index 1239972486ba5..f7442838924ef 100644 --- a/iotdb-client/client-py/iotdb/utils/Tablet.py +++ b/iotdb-client/client-py/iotdb/utils/Tablet.py @@ -22,7 +22,11 @@ from iotdb.tsfile.utils.date_utils import parse_date_to_int from iotdb.utils.BitMap import BitMap -from iotdb.utils.IoTDBConstants import TSDataType +from iotdb.utils.IoTDBConstants import ( + TSDataType, + TS_TABLET_LENGTH_PREFIXED, +) +from iotdb.utils.object_column import encode_object_cell @unique @@ -93,6 +97,44 @@ def __init__( else: self.__column_types = column_types + def add_value_object( + self, + row_index: int, + column_index: int, + is_eof: bool, + offset: int, + content: bytes, + ): + """ + Write one OBJECT column cell, same semantics as Java/C++ Tablet.addValue( + rowIndex, columnIndex, isEOF, offset, content). + """ + if row_index < 0 or row_index >= self.__row_number: + raise IndexError("row_index out of range") + if column_index < 0 or column_index >= self.__column_number: + raise IndexError("column_index out of range") + if self.__data_types[column_index] != TSDataType.OBJECT: + raise TypeError( + "add_value_object requires TSDataType.OBJECT column, got %s" + % self.__data_types[column_index] + ) + self.__values[row_index][column_index] = encode_object_cell( + is_eof, offset, content + ) + + def add_value_object_by_name( + self, + column_name: str, + row_index: int, + is_eof: bool, + offset: int, + content: bytes, + ): + if column_name not in self.__measurements: + raise KeyError("column %r not found" % column_name) + column_index = self.__measurements.index(column_name) + self.add_value_object(row_index, column_index, is_eof, offset, content) + @staticmethod def check_sorted(timestamps): for i in range(1, len(timestamps)): @@ -141,7 +183,7 @@ def get_binary_values(self): bitmaps.append(bitmap) data_type = self.__data_types[i] # BOOLEAN - if data_type == 0: + if data_type == TSDataType.BOOLEAN: format_str_list.append(str(self.__row_number)) format_str_list.append("?") for j in range(self.__row_number): @@ -152,7 +194,7 @@ def get_binary_values(self): self.__mark_none_value(bitmaps, i, j) has_none = True # INT32 - elif data_type == 1: + elif data_type == TSDataType.INT32: format_str_list.append(str(self.__row_number)) format_str_list.append("i") for j in range(self.__row_number): @@ -163,7 +205,7 @@ def get_binary_values(self): self.__mark_none_value(bitmaps, i, j) has_none = True # INT64 or TIMESTAMP - elif data_type == 2 or data_type == 8: + elif data_type in (TSDataType.INT64, TSDataType.TIMESTAMP): format_str_list.append(str(self.__row_number)) format_str_list.append("q") for j in range(self.__row_number): @@ -174,7 +216,7 @@ def get_binary_values(self): self.__mark_none_value(bitmaps, i, j) has_none = True # FLOAT - elif data_type == 3: + elif data_type == TSDataType.FLOAT: format_str_list.append(str(self.__row_number)) format_str_list.append("f") for j in range(self.__row_number): @@ -185,7 +227,7 @@ def get_binary_values(self): self.__mark_none_value(bitmaps, i, j) has_none = True # DOUBLE - elif data_type == 4: + elif data_type == TSDataType.DOUBLE: format_str_list.append(str(self.__row_number)) format_str_list.append("d") for j in range(self.__row_number): @@ -195,11 +237,18 @@ def get_binary_values(self): values_tobe_packed.append(0) self.__mark_none_value(bitmaps, i, j) has_none = True - # TEXT, STRING, BLOB - elif data_type == 5 or data_type == 11 or data_type == 10: + # TEXT, STRING, BLOB, OBJECT (OBJECT cells are already encoded bytes) + elif data_type in TS_TABLET_LENGTH_PREFIXED: for j in range(self.__row_number): if self.__values[j][i] is not None: - if isinstance(self.__values[j][i], str): + if data_type == TSDataType.OBJECT: + value_bytes = self.__values[j][i] + if not isinstance(value_bytes, (bytes, bytearray)): + raise TypeError( + "OBJECT column must be bytes (use add_value_object)" + ) + value_bytes = bytes(value_bytes) + elif isinstance(self.__values[j][i], str): value_bytes = bytes(self.__values[j][i], "utf-8") else: value_bytes = self.__values[j][i] @@ -218,7 +267,7 @@ def get_binary_values(self): self.__mark_none_value(bitmaps, i, j) has_none = True # DATE - elif data_type == 9: + elif data_type == TSDataType.DATE: format_str_list.append(str(self.__row_number)) format_str_list.append("i") for j in range(self.__row_number): diff --git a/iotdb-client/client-py/iotdb/utils/iotdb_rpc_dataset.py b/iotdb-client/client-py/iotdb/utils/iotdb_rpc_dataset.py index bcb259c6f4263..768c64f361a28 100644 --- a/iotdb-client/client-py/iotdb/utils/iotdb_rpc_dataset.py +++ b/iotdb-client/client-py/iotdb/utils/iotdb_rpc_dataset.py @@ -23,13 +23,20 @@ import numpy as np import pandas as pd +from thrift.transport import TTransport + from iotdb.thrift.rpc.IClientRPCService import TSCloseOperationReq, TSFetchResultsReq from iotdb.tsfile.utils.date_utils import parse_int_to_date from iotdb.tsfile.utils.tsblock_serde import deserialize from iotdb.utils.exception import IoTDBConnectionException -from iotdb.utils.IoTDBConstants import TSDataType +from iotdb.utils.IoTDBConstants import ( + TSDataType, + TS_RPC_BUFFER_AS_NUMPY, + TS_RPC_BUFFER_UTF8_STRING, + TS_RPC_NO_BYTESWAP, + TS_RPC_NULLABLE_OBJECT_COLUMNS, +) from iotdb.utils.rpc_utils import convert_to_timestamp, verify_success -from thrift.transport import TTransport logger = logging.getLogger("IoTDB") TIMESTAMP_STR = "Time" @@ -247,30 +254,26 @@ def construct_one_data_frame(self): column_array = column_arrays[location] null_indicator = null_indicators[location] if len(column_array) < array_length or ( - data_type == 0 and null_indicator is not None + data_type == TSDataType.BOOLEAN and null_indicator is not None ): tmp_array = np.full(array_length, None, dtype=object) if null_indicator is not None: indexes = [not v for v in null_indicator] - if data_type == 0: + if data_type == TSDataType.BOOLEAN: tmp_array[indexes] = column_array[indexes] elif len(column_array) != 0: tmp_array[indexes] = column_array - # INT32, DATE - if data_type == 1 or data_type == 9: + if data_type in (TSDataType.INT32, TSDataType.DATE): tmp_array = pd.Series(tmp_array, dtype="Int32") has_pd_series[i] = True - # INT64, TIMESTAMP - elif data_type == 2 or data_type == 8: + elif data_type in (TSDataType.INT64, TSDataType.TIMESTAMP): tmp_array = pd.Series(tmp_array, dtype="Int64") has_pd_series[i] = True - # BOOLEAN - elif data_type == 0: + elif data_type == TSDataType.BOOLEAN: tmp_array = pd.Series(tmp_array, dtype="boolean") has_pd_series[i] = True - # FLOAT, DOUBLE - elif data_type == 3 or data_type == 4: + elif data_type in (TSDataType.FLOAT, TSDataType.DOUBLE): tmp_array = pd.Series(tmp_array) has_pd_series[i] = True column_array = tmp_array @@ -392,22 +395,19 @@ def _process_buffer(self): continue data_type = self.__data_type_for_tsblock_column[location] column_array = column_arrays[location] - # BOOLEAN, INT32, INT64, FLOAT, DOUBLE, BLOB - if data_type in (0, 1, 2, 3, 4, 10): + if data_type in TS_RPC_BUFFER_AS_NUMPY: data_array = column_array if ( - data_type != 10 + data_type not in TS_RPC_NO_BYTESWAP and len(data_array) > 0 and data_array.dtype.byteorder == ">" ): data_array = data_array.byteswap().view( data_array.dtype.newbyteorder("<") ) - # TEXT, STRING - elif data_type in (5, 11): + elif data_type in TS_RPC_BUFFER_UTF8_STRING: data_array = np.array([x.decode("utf-8") for x in column_array]) - # TIMESTAMP - elif data_type == 8: + elif data_type == TSDataType.TIMESTAMP: data_array = pd.Series( [ convert_to_timestamp( @@ -417,47 +417,41 @@ def _process_buffer(self): ], dtype=object, ) - # DATE - elif data_type == 9: + elif data_type == TSDataType.DATE: data_array = pd.Series(column_array).apply(parse_int_to_date) else: raise RuntimeError("unsupported data type {}.".format(data_type)) null_indicator = null_indicators[location] if len(data_array) < array_length or ( - data_type == 0 and null_indicator is not None + data_type == TSDataType.BOOLEAN and null_indicator is not None ): tmp_array = [] - # BOOLEAN, INT32, INT64 - if data_type == 0 or data_type == 1 or data_type == 2: + if data_type in ( + TSDataType.BOOLEAN, + TSDataType.INT32, + TSDataType.INT64, + ): tmp_array = np.full(array_length, pd.NA, dtype=object) - # FLOAT, DOUBLE - elif data_type == 3 or data_type == 4: + elif data_type in (TSDataType.FLOAT, TSDataType.DOUBLE): tmp_array = np.full( array_length, np.nan, dtype=data_type.np_dtype() ) - # TEXT, STRING, BLOB, DATE, TIMESTAMP - elif ( - data_type == 5 - or data_type == 11 - or data_type == 10 - or data_type == 9 - or data_type == 8 - ): + elif data_type in TS_RPC_NULLABLE_OBJECT_COLUMNS: tmp_array = np.full(array_length, None, dtype=object) if null_indicator is not None: indexes = [not v for v in null_indicator] - if data_type == 0: + if data_type == TSDataType.BOOLEAN: tmp_array[indexes] = data_array[indexes] elif len(data_array) != 0: tmp_array[indexes] = data_array - if data_type == 1: + if data_type == TSDataType.INT32: tmp_array = pd.Series(tmp_array).astype("Int32") - elif data_type == 2: + elif data_type == TSDataType.INT64: tmp_array = pd.Series(tmp_array).astype("Int64") - elif data_type == 0: + elif data_type == TSDataType.BOOLEAN: tmp_array = pd.Series(tmp_array).astype("boolean") data_array = tmp_array diff --git a/iotdb-client/client-py/iotdb/utils/object_column.py b/iotdb-client/client-py/iotdb/utils/object_column.py new file mode 100644 index 0000000000000..f69a5366c356f --- /dev/null +++ b/iotdb-client/client-py/iotdb/utils/object_column.py @@ -0,0 +1,41 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF 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. +# +"""Encode/decode OBJECT column cell payloads (aligned with Java/C++ Tablet.addValue).""" + +import struct +from typing import Tuple + + +def encode_object_cell(is_eof: bool, offset: int, content: bytes) -> bytes: + """ + OBJECT cell on the wire (before length-prefix in tablet column buffer): + [is_eof: 1 byte 0/1][offset: 8 bytes big-endian int64][payload...] + """ + if not isinstance(content, (bytes, bytearray)): + raise TypeError("content must be bytes") + flag = b"\x01" if is_eof else b"\x00" + return flag + struct.pack(">q", offset) + bytes(content) + + +def decode_object_cell(cell: bytes) -> Tuple[bool, int, bytes]: + """Inverse of encode_object_cell.""" + if len(cell) < 9: + raise ValueError("OBJECT cell too short") + is_eof = cell[0] != 0 + offset = struct.unpack(">q", cell[1:9])[0] + return is_eof, offset, cell[9:] diff --git a/iotdb-client/client-py/tests/unit/test_object_column.py b/iotdb-client/client-py/tests/unit/test_object_column.py new file mode 100644 index 0000000000000..1f4941c32e6fc --- /dev/null +++ b/iotdb-client/client-py/tests/unit/test_object_column.py @@ -0,0 +1,159 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF 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. +# + +import struct +from unittest.mock import Mock + +import numpy as np +import pytest + +from iotdb.Session import Session +from iotdb.table_session import TableSession +from iotdb.thrift.common.ttypes import TSStatus +from iotdb.tsfile.utils.tsblock_serde import read_binary_column +from iotdb.utils.Field import Field +from iotdb.utils.IoTDBConstants import TSDataType +from iotdb.utils.NumpyTablet import NumpyTablet +from iotdb.utils.Tablet import Tablet, ColumnType +from iotdb.utils.object_column import decode_object_cell, encode_object_cell + + +def test_encode_decode_object_cell_roundtrip(): + payload = b"hello-object" + cell = encode_object_cell(True, 0, payload) + is_eof, offset, body = decode_object_cell(cell) + assert is_eof is True + assert offset == 0 + assert body == payload + + +def test_encode_object_cell_segment(): + cell = encode_object_cell(False, 512, b"ab") + is_eof, offset, body = decode_object_cell(cell) + assert is_eof is False + assert offset == 512 + assert body == b"ab" + + +def test_tablet_add_value_object_and_pack(): + column_names = ["region_id", "plant_id", "device_id", "temperature", "file"] + data_types = [ + TSDataType.STRING, + TSDataType.STRING, + TSDataType.STRING, + TSDataType.FLOAT, + TSDataType.OBJECT, + ] + column_types = [ + ColumnType.TAG, + ColumnType.TAG, + ColumnType.TAG, + ColumnType.FIELD, + ColumnType.FIELD, + ] + timestamps = [1] + values = [["1", "5", "3", 37.6, None]] + tablet = Tablet( + "object_table", column_names, data_types, values, timestamps, column_types + ) + tablet.add_value_object(0, 4, True, 0, b"payload-bytes") + assert tablet.get_binary_values() == struct.pack( + ">i1si1si1sfi?q13s", + 1, + b"1", + 1, + b"5", + 1, + b"3", + 37.6, + 22, + True, + 0, + b"payload-bytes", + ) + + +def test_tablet_add_value_object_wrong_column(): + column_names = ["a"] + data_types = [TSDataType.STRING] + tablet = Tablet("t", column_names, data_types, [["x"]], [1]) + with pytest.raises(TypeError): + tablet.add_value_object(0, 0, True, 0, b"x") + + +@pytest.mark.parametrize( + "field_type, field_value", + [(TSDataType.INT32, 42), (TSDataType.OBJECT, encode_object_cell(True, 0, b"x"))], +) +def test_insert_multidevice_tablet_on_one_connection(field_type, field_value): + tablet = Tablet( + "t", + ["tag", "value"], + [TSDataType.STRING, field_type], + [["a", field_value], ["b", field_value]], + [1, 2], + [ColumnType.TAG, ColumnType.FIELD], + ) + session = Session("localhost", 6667) + connection = Mock(session_id=1) + connection.client.insertTablet.return_value = TSStatus(code=200) + session.get_connection = Mock(return_value=connection) + TableSession(session_pool=Mock(get_session=Mock(return_value=session))).insert( + tablet + ) + + connection.client.insertTablet.assert_called_once() + request = connection.client.insertTablet.call_args[0][0] + assert request.size == 2 + assert request.columnCategories == [ColumnType.TAG, ColumnType.FIELD] + assert request.values == tablet.get_binary_values() + + +def test_read_object_query_result(): + value = struct.pack(">q", 255) + b"\x00\x00\x00\x80" + serialized = memoryview(struct.pack(">Bi", 0, len(value)) + value) + values, nulls, remaining = read_binary_column(serialized, TSDataType.OBJECT, 1) + + assert values.tolist() == [value] + assert nulls is None + assert not remaining + field = Field.get_field(values[0], TSDataType.OBJECT) + assert field.get_object_value(TSDataType.OBJECT) == value + assert str(field) == repr(value) + + +def test_numpy_tablet_object_with_marked_null(): + tablet = NumpyTablet( + "t", ["obj"], [TSDataType.OBJECT], [np.array([None, None])], np.array([1, 2]) + ) + tablet.add_value_object(0, 0, True, 0, b"x") + with pytest.raises(TypeError, match="OBJECT column must be bytes"): + tablet.get_binary_values() + + tablet.mark_none_value(0, 1) + assert tablet.get_binary_values() == struct.pack( + ">i?q1si?B", 10, True, 0, b"x", 0, True, 2 + ) + + +def test_numpy_tablet_object_with_fixed_width_array(): + tablet = NumpyTablet( + "t", ["obj"], [TSDataType.OBJECT], [np.array([b""], dtype="S1")], np.array([1]) + ) + tablet.add_value_object(0, 0, True, 256, b"x\x00") + assert tablet.get_binary_values() == struct.pack(">i?q2s", 11, True, 256, b"x\x00")