Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/ArrowKdb.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
118 changes: 118 additions & 0 deletions src/TableData.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include <vector>
#include <memory>
#include <iostream>
#include <utility>

#if !defined(_WIN32) && !defined(DISABLE_ORC)
#include <arrow/adapters/orc/adapter.h>
Expand Down Expand Up @@ -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<K, K> BuildKdbTableFromReader(
std::shared_ptr<arrow::ipc::RecordBatchReader> reader
, kx::arrowkdb::TypeMappingOverride& type_overrides
, bool with_null_bitmap )
{
std::vector<std::shared_ptr<arrow::RecordBatch>> 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<arrow::ChunkedArray>(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<arrow::Buffer>(kG(char_array), char_array->n);
const int64_t total_size = buffer->size();

std::vector<K> tables;
std::vector<K> bitmap_tables;

int64_t offset = 0;
while (offset < total_size) {
auto slice = arrow::SliceBuffer(buffer, offset);
auto buf_reader = std::make_shared<arrow::io::BufferReader>(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;
Expand Down
37 changes: 37 additions & 0 deletions src/TableData.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down