From ac758873a1134e6841bb60d0e6423f01b39af1de Mon Sep 17 00:00:00 2001 From: Ferenc Lombai Date: Fri, 25 Sep 2026 11:56:20 +0200 Subject: [PATCH] Add parseArrowToTables for parsing concatenated multi-stream Arrow IPC buffers Walks a buffer of concatenated Arrow IPC streams and returns one kdb table per logical stream found, since a single IPC reader only consumes the stream at the head of its input. Supports the same DECIMAL128_AS_DOUBLE and WITH_NULL_BITMAP options as parseArrowData. --- src/ArrowKdb.cpp | 2 +- src/TableData.cpp | 118 ++++++++++++++++++++++++++++++++++++++++++++++ src/TableData.h | 37 +++++++++++++++ 3 files changed, 156 insertions(+), 1 deletion(-) diff --git a/src/ArrowKdb.cpp b/src/ArrowKdb.cpp index 390f2b6..03d1f40 100644 --- a/src/ArrowKdb.cpp +++ b/src/ArrowKdb.cpp @@ -131,7 +131,7 @@ K kexport(K _) REG((char*)"pq",F(writeParquet,4)F(readParquetSchema,1)F(readParquetData,2)F(readParquetColumn,3)F(readParquetNumRowGroups,1)F(readParquetRowGroups,4)) - REG((char*)"ipc",F(writeArrow,4)F(readArrowSchema,1)F(readArrowData,2)F(serializeArrow,3)F(parseArrowSchema,1)F(parseArrowData,2)) + REG((char*)"ipc",F(writeArrow,4)F(readArrowSchema,1)F(readArrowData,2)F(serializeArrow,3)F(parseArrowSchema,1)F(parseArrowData,2)F(parseArrowToTables,2)) REG((char*)"util",F(buildInfo,1)F(init,1)) diff --git a/src/TableData.cpp b/src/TableData.cpp index 7ec03e8..2b0f79c 100644 --- a/src/TableData.cpp +++ b/src/TableData.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #if !defined(_WIN32) && !defined(DISABLE_ORC) #include @@ -920,6 +921,123 @@ K parseArrowData(K char_array, K options) KDB_EXCEPTION_CATCH; } +// Amalgamates each column's arrays across all the record batches available +// on an already-opened arrow IPC reader into a chunked array, then converts +// straight into a kdb table, keyed by the schema field names. Used by +// parseArrowToTables once per logical stream reader. +// +// Returns (data table; null bitmap table). The second item is only +// populated (non-null) when with_null_bitmap is set. +static std::pair BuildKdbTableFromReader( + std::shared_ptr reader + , kx::arrowkdb::TypeMappingOverride& type_overrides + , bool with_null_bitmap ) +{ + std::vector> all_batches; + PARQUET_ASSIGN_OR_THROW(all_batches, reader->ToRecordBatches()); + + const auto schema = reader->schema(); + SchemaContainsNullable(schema); + const auto col_num = schema->num_fields(); + + K field_names = ktn(KS, col_num); + K columns = ktn(0, col_num); + K bitmap_columns = with_null_bitmap ? ktn(0, col_num) : nullptr; + + for (auto i = 0; i < col_num; ++i) { + kS(field_names)[i] = ss((S)schema->field(i)->name().c_str()); + + arrow::ArrayVector column_arrays; + for (auto batch : all_batches) + column_arrays.push_back(batch->column(i)); + auto chunked_array = std::make_shared(column_arrays); + + kK(columns)[i] = kx::arrowkdb::ReadChunkedArray(chunked_array, type_overrides); + if (with_null_bitmap) + kK(bitmap_columns)[i] = kx::arrowkdb::ReadChunkedArrayNullBitmap(chunked_array, type_overrides); + } + + K table = xT(xD(field_names, columns)); + if (!table) + throw std::runtime_error("failed to construct kdb table from parsed arrow stream"); + + if (!with_null_bitmap) + return std::make_pair(table, (K)nullptr); + + // Field names are consumed by xD so a fresh copy is needed for the bitmap table + K bitmap_field_names = ktn(KS, col_num); + for (auto i = 0; i < col_num; ++i) + kS(bitmap_field_names)[i] = ss((S)schema->field(i)->name().c_str()); + + K bitmap_table = xT(xD(bitmap_field_names, bitmap_columns)); + if (!bitmap_table) + throw std::runtime_error("failed to construct kdb null bitmap table from parsed arrow stream"); + + return std::make_pair(table, bitmap_table); +} + +K parseArrowToTables(K char_array, K options) +{ + KDB_EXCEPTION_TRY; + + if (char_array->t != KG && char_array->t != KC) + return krr((S)"char_array not 4|10h"); + + // Parse the options + auto read_options = kx::arrowkdb::KdbOptions(options, kx::arrowkdb::Options::string_options, kx::arrowkdb::Options::int_options); + + // Type mapping overrides + kx::arrowkdb::TypeMappingOverride type_overrides{ read_options }; + + int64_t with_null_bitmap = 0; + read_options.GetIntOption(kx::arrowkdb::Options::WITH_NULL_BITMAP, with_null_bitmap); + + auto buffer = std::make_shared(kG(char_array), char_array->n); + const int64_t total_size = buffer->size(); + + std::vector tables; + std::vector bitmap_tables; + + int64_t offset = 0; + while (offset < total_size) { + auto slice = arrow::SliceBuffer(buffer, offset); + auto buf_reader = std::make_shared(slice); + + auto open_result = arrow::ipc::RecordBatchStreamReader::Open(buf_reader); + if (!open_result.ok()) + break; + + auto built = BuildKdbTableFromReader(*open_result, type_overrides, with_null_bitmap != 0); + tables.push_back(built.first); + if (with_null_bitmap) + bitmap_tables.push_back(built.second); + + int64_t consumed; + PARQUET_ASSIGN_OR_THROW(consumed, buf_reader->Tell()); + if (consumed <= 0) + break; // defensive: avoid looping forever if nothing was consumed + offset += consumed; + } + + K result = ktn(0, (int)tables.size()); + for (size_t i = 0; i < tables.size(); ++i) + kK(result)[i] = tables[i]; + + if (!with_null_bitmap) + return result; + + K bitmap_result = ktn(0, (int)bitmap_tables.size()); + for (size_t i = 0; i < bitmap_tables.size(); ++i) + kK(bitmap_result)[i] = bitmap_tables[i]; + + K combined = ktn(0, 2); + kK(combined)[0] = result; + kK(combined)[1] = bitmap_result; + return combined; + + KDB_EXCEPTION_CATCH; +} + K readORCData(K orc_file, K options) { KDB_EXCEPTION_TRY; diff --git a/src/TableData.h b/src/TableData.h index 09cfee9..57da237 100644 --- a/src/TableData.h +++ b/src/TableData.h @@ -318,6 +318,43 @@ extern "C" */ K parseArrowData(K char_array, K options); + /** + * @brief Parses a buffer which concatenates one or more arrow IPC record + * batch streams back to back (each a self-contained Schema [+ + * DictionaryBatch(es)] + RecordBatch(es) + EOS sequence) and returns each + * as its own kdb table. + * + * A single arrow IPC stream reader only ever consumes the one logical + * stream at the head of its input, so a buffer produced by concatenating + * several such streams (for example the output of repeated calls to + * serializeArrow joined together, or a source which batches multiple + * tables into one payload) cannot be parsed by a single + * parseArrowData/readArrowData call. This function instead walks the + * buffer, opening a fresh reader at each offset and advancing by exactly + * what that reader consumed until no further valid stream can be opened, + * at which point any remaining bytes are treated as trailing padding + * rather than an error. + * + * Supported options: + * + * DECIMAL128_AS_DOUBLE (long) - Flag indicating whether to override the + * default type mapping for the arrow decimal128 datatype and instead + * represent it as a double (9h). Default 0. + * + * WITH_NULL_BITMAP (long) - Flag indicating whether to return the data + * values and the null bitmap as separate kdb tables. Default 0. + * + * @param char_array KG list containing the concatenated serialized + * stream data + * @options Dictionary of options or generic null (::) to use + * defaults. Dictionary key must be a 11h list. Values list can be 7h, 11h or + * mixed list of -7|-11|4h. + * @return Mixed list of kdb tables, one per logical stream + * found in the buffer, or a 2 item mixed list of (data tables;null bitmap + * tables) if WITH_NULL_BITMAP is set + */ + K parseArrowToTables(K char_array, K options); + /** * @brief Reads the arrow array data from the specified ORC file *