From f671ba403a4d7e81b9ba07a2d6895f61bd4bd8b4 Mon Sep 17 00:00:00 2001 From: Phillip Cloud Date: Sun, 23 Apr 2017 15:06:44 -0400 Subject: [PATCH] ARROW-483: [C++/Python] Provide access to "custom_metadata" Field attribute in IPC setting --- cpp/CMakeLists.txt | 1 + cpp/src/arrow/array.cc | 2 +- cpp/src/arrow/builder.cc | 13 ++- cpp/src/arrow/ipc/metadata.cc | 30 +++++- cpp/src/arrow/type-test.cc | 34 +++++++ cpp/src/arrow/type.cc | 20 +++- cpp/src/arrow/type.h | 10 +- cpp/src/arrow/util/CMakeLists.txt | 2 + cpp/src/arrow/util/key-value-metadata-test.cc | 87 ++++++++++++++++ cpp/src/arrow/util/key_value_metadata.cc | 99 +++++++++++++++++++ cpp/src/arrow/util/key_value_metadata.h | 56 +++++++++++ format/Schema.fbs | 2 +- python/.gitignore | 1 + python/pyarrow/_array.pxd | 2 + python/pyarrow/_array.pyx | 7 ++ python/pyarrow/_table.pyx | 64 +++++++----- python/pyarrow/includes/common.pxd | 3 +- python/pyarrow/includes/libarrow.pxd | 11 ++- 18 files changed, 401 insertions(+), 43 deletions(-) create mode 100644 cpp/src/arrow/util/key-value-metadata-test.cc create mode 100644 cpp/src/arrow/util/key_value_metadata.cc create mode 100644 cpp/src/arrow/util/key_value_metadata.h diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 2d8c00fd8080..5abe5f1436ea 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -944,6 +944,7 @@ set(ARROW_SRCS src/arrow/util/bit-util.cc src/arrow/util/decimal.cc + src/arrow/util/key_value_metadata.cc ) if (ARROW_IPC) diff --git a/cpp/src/arrow/array.cc b/cpp/src/arrow/array.cc index e640bbd4a206..76dda2ca7b94 100644 --- a/cpp/src/arrow/array.cc +++ b/cpp/src/arrow/array.cc @@ -113,7 +113,7 @@ Status Array::Validate() const { static inline void ConformSliceParams( int64_t array_offset, int64_t array_length, int64_t* offset, int64_t* length) { DCHECK_LE(*offset, array_length); - DCHECK_GE(offset, 0); + DCHECK_NE(offset, nullptr); *length = std::min(array_length - *offset, *length); *offset = array_offset + *offset; } diff --git a/cpp/src/arrow/builder.cc b/cpp/src/arrow/builder.cc index d85eb32652c4..4ecb8d350098 100644 --- a/cpp/src/arrow/builder.cc +++ b/cpp/src/arrow/builder.cc @@ -363,8 +363,6 @@ ARROW_EXPORT Status DecimalBuilder::Append(const decimal::Decimal128& value) { return Status::OK(); } -template ARROW_EXPORT Status DecimalBuilder::Append(const decimal::Decimal128& val); - Status DecimalBuilder::Init(int64_t capacity) { RETURN_NOT_OK(FixedSizeBinaryBuilder::Init(capacity)); if (byte_width_ == 16) { @@ -408,16 +406,17 @@ Status DecimalBuilder::Finish(std::shared_ptr* out) { ListBuilder::ListBuilder(MemoryPool* pool, std::shared_ptr value_builder, const std::shared_ptr& type) - : ArrayBuilder( - pool, type ? type : std::static_pointer_cast( - std::make_shared(value_builder->type()))), + : ArrayBuilder(pool, + type ? type : std::static_pointer_cast( + std::make_shared(value_builder->type()))), offset_builder_(pool), value_builder_(value_builder) {} ListBuilder::ListBuilder(MemoryPool* pool, std::shared_ptr values, const std::shared_ptr& type) - : ArrayBuilder(pool, type ? type : std::static_pointer_cast( - std::make_shared(values->type()))), + : ArrayBuilder(pool, + type ? type : std::static_pointer_cast( + std::make_shared(values->type()))), offset_builder_(pool), values_(values) {} diff --git a/cpp/src/arrow/ipc/metadata.cc b/cpp/src/arrow/ipc/metadata.cc index 791948b50b0a..c0b518a0d8e5 100644 --- a/cpp/src/arrow/ipc/metadata.cc +++ b/cpp/src/arrow/ipc/metadata.cc @@ -45,6 +45,7 @@ namespace ipc { using FBB = flatbuffers::FlatBufferBuilder; using DictionaryOffset = flatbuffers::Offset; using FieldOffset = flatbuffers::Offset; +using KeyValueOffset = flatbuffers::Offset; using RecordBatchOffset = flatbuffers::Offset; using VectorLayoutOffset = flatbuffers::Offset; using Offset = flatbuffers::Offset; @@ -583,6 +584,7 @@ flatbuf::Endianness endianness() { static Status SchemaToFlatbuffer(FBB& fbb, const Schema& schema, DictionaryMemo* dictionary_memo, flatbuffers::Offset* out) { + /// Fields std::vector field_offsets; for (int i = 0; i < schema.num_fields(); ++i) { std::shared_ptr field = schema.field(i); @@ -591,7 +593,20 @@ static Status SchemaToFlatbuffer(FBB& fbb, const Schema& schema, field_offsets.push_back(offset); } - *out = flatbuf::CreateSchema(fbb, endianness(), fbb.CreateVector(field_offsets)); + /// Custom metadata + const auto& custom_metadata_ = schema.custom_metadata(); + std::vector key_value_offsets; + size_t metadata_size = custom_metadata_.size(); + key_value_offsets.reserve(metadata_size); + for (size_t i = 0; i < metadata_size; ++i) { + const auto& key = custom_metadata_.key(i); + const auto& value = custom_metadata_.value(i); + key_value_offsets.push_back( + flatbuf::CreateKeyValue(fbb, fbb.CreateString(key), fbb.CreateString(value))); + } + + *out = flatbuf::CreateSchema(fbb, endianness(), fbb.CreateVector(field_offsets), + fbb.CreateVector(key_value_offsets)); return Status::OK(); } @@ -939,7 +954,18 @@ Status GetSchema(const void* opaque_schema, const DictionaryMemo& dictionary_mem const flatbuf::Field* field = schema->fields()->Get(i); RETURN_NOT_OK(FieldFromFlatbuffer(field, dictionary_memo, &fields[i])); } - *out = std::make_shared(fields); + + KeyValueMetadata custom_metadata; + auto fb_metadata = schema->custom_metadata(); + if (fb_metadata != nullptr) { + custom_metadata.reserve(fb_metadata->size()); + + for (const auto& pair : *fb_metadata) { + custom_metadata.Append(pair->key()->str(), pair->value()->str()); + } + } + + *out = std::make_shared(fields, custom_metadata); return Status::OK(); } diff --git a/cpp/src/arrow/type-test.cc b/cpp/src/arrow/type-test.cc index dec7268a5a8b..8e2dfd50e431 100644 --- a/cpp/src/arrow/type-test.cc +++ b/cpp/src/arrow/type-test.cc @@ -117,6 +117,40 @@ TEST_F(TestSchema, GetFieldByName) { ASSERT_TRUE(result == nullptr); } +TEST_F(TestSchema, TestCustomMetadataConstruction) { + auto f0 = field("f0", int32()); + auto f1 = field("f1", uint8(), false); + auto f2 = field("f2", utf8()); + vector> fields = {f0, f1, f2}; + KeyValueMetadata metadata({"foo", "bar"}, {"bizz", "buzz"}); + auto schema = std::make_shared(fields, metadata); + ASSERT_TRUE(metadata.Equals(schema->custom_metadata())); +} + +TEST_F(TestSchema, TestAddCustomMetadata) { + auto f0 = field("f0", int32()); + auto f1 = field("f1", uint8(), false); + auto f2 = field("f2", utf8()); + vector> fields = {f0, f1, f2}; + KeyValueMetadata metadata({"foo", "bar"}, {"bizz", "buzz"}); + auto schema = std::make_shared(fields); + std::shared_ptr new_schema; + schema->AddCustomMetadata(metadata, &new_schema); + ASSERT_TRUE(metadata.Equals(new_schema->custom_metadata())); +} + +TEST_F(TestSchema, TestRemoveCustomMetadata) { + auto f0 = field("f0", int32()); + auto f1 = field("f1", uint8(), false); + auto f2 = field("f2", utf8()); + vector> fields = {f0, f1, f2}; + KeyValueMetadata metadata({"foo", "bar"}, {"bizz", "buzz"}); + auto schema = std::make_shared(fields); + std::shared_ptr new_schema; + schema->RemoveCustomMetadata(&new_schema); + ASSERT_EQ(0, new_schema->custom_metadata().size()); +} + #define PRIMITIVE_TEST(KLASS, ENUM, NAME) \ TEST(TypesTest, TestPrimitive_##ENUM) { \ KLASS tp; \ diff --git a/cpp/src/arrow/type.cc b/cpp/src/arrow/type.cc index 2e454ae81886..f59f8fb26c9b 100644 --- a/cpp/src/arrow/type.cc +++ b/cpp/src/arrow/type.cc @@ -24,6 +24,7 @@ #include "arrow/array.h" #include "arrow/compare.h" #include "arrow/status.h" +#include "arrow/util/key_value_metadata.h" #include "arrow/util/logging.h" #include "arrow/util/stl.h" #include "arrow/visitor.h" @@ -231,7 +232,9 @@ std::string NullType::ToString() const { // ---------------------------------------------------------------------- // Schema implementation -Schema::Schema(const std::vector>& fields) : fields_(fields) {} +Schema::Schema(const std::vector>& fields, + const KeyValueMetadata& custom_metadata) + : fields_(fields), custom_metadata_(custom_metadata) {} bool Schema::Equals(const Schema& other) const { if (this == &other) { return true; } @@ -263,7 +266,18 @@ Status Schema::AddField( DCHECK_GE(i, 0); DCHECK_LE(i, this->num_fields()); - *out = std::make_shared(AddVectorElement(fields_, i, field)); + *out = std::make_shared(AddVectorElement(fields_, i, field), custom_metadata_); + return Status::OK(); +} + +Status Schema::AddCustomMetadata( + const KeyValueMetadata& custom_metadata, std::shared_ptr* out) const { + *out = std::make_shared(fields_, custom_metadata); + return Status::OK(); +} + +Status Schema::RemoveCustomMetadata(std::shared_ptr* out) { + *out = std::make_shared(fields_, KeyValueMetadata()); return Status::OK(); } @@ -271,7 +285,7 @@ Status Schema::RemoveField(int i, std::shared_ptr* out) const { DCHECK_GE(i, 0); DCHECK_LT(i, this->num_fields()); - *out = std::make_shared(DeleteVectorElement(fields_, i)); + *out = std::make_shared(DeleteVectorElement(fields_, i), custom_metadata_); return Status::OK(); } diff --git a/cpp/src/arrow/type.h b/cpp/src/arrow/type.h index ea4ea03ff569..dc9456137030 100644 --- a/cpp/src/arrow/type.h +++ b/cpp/src/arrow/type.h @@ -28,6 +28,7 @@ #include "arrow/status.h" #include "arrow/type_fwd.h" +#include "arrow/util/key_value_metadata.h" #include "arrow/util/macros.h" #include "arrow/util/visibility.h" #include "arrow/visitor.h" @@ -677,7 +678,8 @@ class ARROW_EXPORT DictionaryType : public FixedWidthType { class ARROW_EXPORT Schema { public: - explicit Schema(const std::vector>& fields); + explicit Schema(const std::vector>& fields, + const KeyValueMetadata& custom_metadata = KeyValueMetadata()); // Returns true if all of the schema fields are equal bool Equals(const Schema& other) const; @@ -689,6 +691,7 @@ class ARROW_EXPORT Schema { std::shared_ptr GetFieldByName(const std::string& name); const std::vector>& fields() const { return fields_; } + const KeyValueMetadata& custom_metadata() const { return custom_metadata_; } // Render a string representation of the schema suitable for debugging std::string ToString() const; @@ -697,11 +700,16 @@ class ARROW_EXPORT Schema { int i, const std::shared_ptr& field, std::shared_ptr* out) const; Status RemoveField(int i, std::shared_ptr* out) const; + Status AddCustomMetadata( + const KeyValueMetadata& metadata, std::shared_ptr* out) const; + Status RemoveCustomMetadata(std::shared_ptr* out); + int num_fields() const { return static_cast(fields_.size()); } private: std::vector> fields_; std::unordered_map name_to_index_; + KeyValueMetadata custom_metadata_; }; // ---------------------------------------------------------------------- diff --git a/cpp/src/arrow/util/CMakeLists.txt b/cpp/src/arrow/util/CMakeLists.txt index b22c8aca11c5..ac7e86615eb4 100644 --- a/cpp/src/arrow/util/CMakeLists.txt +++ b/cpp/src/arrow/util/CMakeLists.txt @@ -26,6 +26,7 @@ install(FILES macros.h random.h visibility.h + key_value_metadata.h DESTINATION include/arrow/util) ####################################### @@ -52,3 +53,4 @@ endif() ADD_ARROW_TEST(bit-util-test) ADD_ARROW_TEST(stl-util-test) ADD_ARROW_TEST(decimal-test) +ADD_ARROW_TEST(key-value-metadata-test) diff --git a/cpp/src/arrow/util/key-value-metadata-test.cc b/cpp/src/arrow/util/key-value-metadata-test.cc new file mode 100644 index 000000000000..aadc989cb403 --- /dev/null +++ b/cpp/src/arrow/util/key-value-metadata-test.cc @@ -0,0 +1,87 @@ +// 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. + +#include "gtest/gtest.h" + +#include "arrow/util/key_value_metadata.h" + +#include "arrow/test-util.h" + +namespace arrow { + +TEST(KeyValueMetadataTest, SimpleConstruction) { + KeyValueMetadata metadata; + ASSERT_EQ(0, metadata.size()); +} + +TEST(KeyValueMetadataTest, StringVectorConstruction) { + std::vector keys = {"foo", "bar"}; + std::vector values = {"bizz", "buzz"}; + + KeyValueMetadata metadata(keys, values); + ASSERT_EQ("foo", metadata.key(0)); + ASSERT_EQ("bar", metadata.key(1)); + ASSERT_EQ("bizz", metadata.value(0)); + ASSERT_EQ("buzz", metadata.value(1)); + ASSERT_EQ(2, metadata.size()); +} + +TEST(KeyValueMetadataTest, StringMapConstruction) { + std::unordered_map pairs = {{"foo", "bizz"}, {"bar", "buzz"}}; + std::unordered_map result_map; + result_map.reserve(pairs.size()); + + KeyValueMetadata metadata(pairs); + metadata.ToUnorderedMap(&result_map); + ASSERT_EQ(pairs, result_map); + ASSERT_EQ(2, metadata.size()); +} + +TEST(KeyValueMetadataTest, StringAppend) { + std::vector keys = {"foo", "bar"}; + std::vector values = {"bizz", "buzz"}; + + KeyValueMetadata metadata(keys, values); + ASSERT_EQ("foo", metadata.key(0)); + ASSERT_EQ("bar", metadata.key(1)); + ASSERT_EQ("bizz", metadata.value(0)); + ASSERT_EQ("buzz", metadata.value(1)); + ASSERT_EQ(2, metadata.size()); + + metadata.Append("purple", "orange"); + metadata.Append("blue", "red"); + + ASSERT_EQ("purple", metadata.key(2)); + ASSERT_EQ("blue", metadata.key(3)); + + ASSERT_EQ("orange", metadata.value(2)); + ASSERT_EQ("red", metadata.value(3)); +} + +TEST(KeyValueMetadataTest, Equals) { + std::vector keys = {"foo", "bar"}; + std::vector values = {"bizz", "buzz"}; + + KeyValueMetadata metadata(keys, values); + KeyValueMetadata metadata2(keys, values); + KeyValueMetadata metadata3(keys, {"buzz", "bizz"}); + + ASSERT_TRUE(metadata.Equals(metadata2)); + ASSERT_FALSE(metadata.Equals(metadata3)); +} + +} // namespace arrow diff --git a/cpp/src/arrow/util/key_value_metadata.cc b/cpp/src/arrow/util/key_value_metadata.cc new file mode 100644 index 000000000000..c91478bd1acd --- /dev/null +++ b/cpp/src/arrow/util/key_value_metadata.cc @@ -0,0 +1,99 @@ +// 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. + +#include + +#include "arrow/util/key_value_metadata.h" +#include "arrow/util/logging.h" + +namespace arrow { + +static std::vector UnorderedMapKeys( + const std::unordered_map& map) { + std::vector keys; + keys.reserve(map.size()); + for (const auto& pair : map) { + keys.push_back(pair.first); + } + return keys; +} + +static std::vector UnorderedMapValues( + const std::unordered_map& map) { + std::vector values; + values.reserve(map.size()); + for (const auto& pair : map) { + values.push_back(pair.second); + } + return values; +} + +KeyValueMetadata::KeyValueMetadata() : keys_(), values_() {} + +KeyValueMetadata::KeyValueMetadata( + const std::unordered_map& map) + : keys_(UnorderedMapKeys(map)), values_(UnorderedMapValues(map)) {} + +KeyValueMetadata::KeyValueMetadata( + const std::vector& keys, const std::vector& values) + : keys_(keys), values_(values) { + DCHECK_EQ(keys.size(), values.size()); +} + +void KeyValueMetadata::ToUnorderedMap( + std::unordered_map* out) const { + DCHECK_NE(out, nullptr); + const int64_t n = size(); + out->reserve(n); + for (int64_t i = 0; i < n; ++i) { + out->insert(std::make_pair(key(i), value(i))); + } +} + +void KeyValueMetadata::Append(const std::string& key, const std::string& value) { + keys_.push_back(key); + values_.push_back(value); +} + +void KeyValueMetadata::reserve(int64_t n) { + DCHECK_GE(n, 0); + const auto m = static_cast(n); + keys_.reserve(m); + values_.reserve(m); +} + +int64_t KeyValueMetadata::size() const { + DCHECK_EQ(keys_.size(), values_.size()); + return static_cast(keys_.size()); +} + +std::string KeyValueMetadata::key(int64_t i) const { + DCHECK_GE(i, 0); + return keys_[static_cast(i)]; +} + +std::string KeyValueMetadata::value(int64_t i) const { + DCHECK_GE(i, 0); + return values_[static_cast(i)]; +} + +bool KeyValueMetadata::Equals(const KeyValueMetadata& other) const { + return size() == other.size() && + std::equal(keys_.cbegin(), keys_.cend(), other.keys_.cbegin()) && + std::equal(values_.cbegin(), values_.cend(), other.values_.cbegin()); +} +} // namespace arrow diff --git a/cpp/src/arrow/util/key_value_metadata.h b/cpp/src/arrow/util/key_value_metadata.h new file mode 100644 index 000000000000..713b2c0b0bcf --- /dev/null +++ b/cpp/src/arrow/util/key_value_metadata.h @@ -0,0 +1,56 @@ +// 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. + +#ifndef ARROW_UTIL_KEY_VALUE_METADATA_H +#define ARROW_UTIL_KEY_VALUE_METADATA_H + +#include +#include +#include +#include + +#include "arrow/util/visibility.h" + +namespace arrow { + +class ARROW_EXPORT KeyValueMetadata { + public: + KeyValueMetadata(); + KeyValueMetadata( + const std::vector& keys, const std::vector& values); + explicit KeyValueMetadata(const std::unordered_map& map); + + void ToUnorderedMap(std::unordered_map* out) const; + + void Append(const std::string& key, const std::string& value); + + void reserve(int64_t n); + int64_t size() const; + + std::string key(int64_t i) const; + std::string value(int64_t i) const; + + bool Equals(const KeyValueMetadata& other) const; + + private: + std::vector keys_; + std::vector values_; +}; + +} // namespace arrow + +#endif // ARROW_UTIL_KEY_VALUE_METADATA_H diff --git a/format/Schema.fbs b/format/Schema.fbs index b48859f50eea..8de5c6d466c3 100644 --- a/format/Schema.fbs +++ b/format/Schema.fbs @@ -200,7 +200,7 @@ table VectorLayout { table KeyValue { key: string; - value: [ubyte]; + value: string; } /// ---------------------------------------------------------------------- diff --git a/python/.gitignore b/python/.gitignore index ba40c3ea8888..6c0d5a93cd35 100644 --- a/python/.gitignore +++ b/python/.gitignore @@ -33,3 +33,4 @@ coverage.xml # benchmark working dir .asv +pyarrow/_table_api.h diff --git a/python/pyarrow/_array.pxd b/python/pyarrow/_array.pxd index 464de316f043..4d5db8618a37 100644 --- a/python/pyarrow/_array.pxd +++ b/python/pyarrow/_array.pxd @@ -81,6 +81,8 @@ cdef class Schema: cdef init(self, const vector[shared_ptr[CField]]& fields) cdef init_schema(self, const shared_ptr[CSchema]& schema) + cpdef dict custom_metadata(self) + cdef class Scalar: cdef readonly: diff --git a/python/pyarrow/_array.pyx b/python/pyarrow/_array.pyx index 1c571ba153df..2fb20b7553e9 100644 --- a/python/pyarrow/_array.pyx +++ b/python/pyarrow/_array.pyx @@ -244,6 +244,13 @@ cdef class Schema: self.schema = schema.get() self.sp_schema = schema + cpdef dict custom_metadata(self): + cdef: + CKeyValueMetadata metadata = self.schema.custom_metadata() + unordered_map[c_string, c_string] result + metadata.ToUnorderedMap(&result) + return result + def equals(self, other): """ Test if this schema is equal to the other diff --git a/python/pyarrow/_table.pyx b/python/pyarrow/_table.pyx index 78fec75cf3e7..ed0782bbba0a 100644 --- a/python/pyarrow/_table.pyx +++ b/python/pyarrow/_table.pyx @@ -34,7 +34,6 @@ from pyarrow._error import ArrowException from pyarrow._array import field from pyarrow.compat import frombytes, tobytes - from collections import OrderedDict @@ -273,15 +272,22 @@ cdef class Column: return chunked_array -cdef _schema_from_arrays(arrays, names, shared_ptr[CSchema]* schema): +cdef CKeyValueMetadata key_value_metadata_from_dict(dict metadata): + cdef: + unordered_map[c_string, c_string] unordered_metadata = metadata + CKeyValueMetadata c_metadata = CKeyValueMetadata(unordered_metadata) + return c_metadata + + +cdef int _schema_from_arrays( + arrays, names, dict metadata, shared_ptr[CSchema]* schema) except -1: cdef: Array arr Column col c_string c_name vector[shared_ptr[CField]] fields - cdef shared_ptr[CDataType] type_ - - cdef int K = len(arrays) + shared_ptr[CDataType] type_ + int K = len(arrays) fields.resize(K) @@ -306,15 +312,16 @@ cdef _schema_from_arrays(arrays, names, shared_ptr[CSchema]* schema): else: raise TypeError(type(arrays[0])) - schema.reset(new CSchema(fields)) - + schema.reset(new CSchema(fields, key_value_metadata_from_dict(metadata))) + return 0 -cdef _dataframe_to_arrays(df, timestamps_to_ms, Schema schema): +cdef tuple _dataframe_to_arrays(df, bint timestamps_to_ms, Schema schema): cdef: list names = [] list arrays = [] DataType type = None + dict metadata = {} for name in df.columns: col = df[name] @@ -326,7 +333,7 @@ cdef _dataframe_to_arrays(df, timestamps_to_ms, Schema schema): names.append(name) arrays.append(arr) - return names, arrays + return names, arrays, metadata cdef class RecordBatch: @@ -486,11 +493,11 @@ cdef class RecordBatch: ------- pyarrow.table.RecordBatch """ - names, arrays = _dataframe_to_arrays(df, False, schema) - return cls.from_arrays(arrays, names) + names, arrays, metadata = _dataframe_to_arrays(df, False, schema) + return cls.from_arrays(arrays, names, metadata) @staticmethod - def from_arrays(arrays, names): + def from_arrays(list arrays, list names, dict metadata=None): """ Construct a RecordBatch from multiple pyarrow.Arrays @@ -512,15 +519,17 @@ cdef class RecordBatch: shared_ptr[CRecordBatch] batch vector[shared_ptr[CArray]] c_arrays int64_t num_rows + int64_t i + int64_t number_of_arrays = len(arrays) - if len(arrays) == 0: + if not number_of_arrays: raise ValueError('Record batch cannot contain no arrays (for now)') num_rows = len(arrays[0]) - _schema_from_arrays(arrays, names, &schema) + _schema_from_arrays(arrays, names, metadata or {}, &schema) - for i in range(len(arrays)): - arr = arrays[i] + c_arrays.reserve(len(arrays)) + for arr in arrays: c_arrays.push_back(arr.sp_array) batch.reset(new CRecordBatch(schema, num_rows, c_arrays)) @@ -656,13 +665,13 @@ cdef class Table: >>> pa.Table.from_pandas(df) """ - names, arrays = _dataframe_to_arrays(df, + names, arrays, metadata = _dataframe_to_arrays(df, timestamps_to_ms=timestamps_to_ms, schema=schema) - return cls.from_arrays(arrays, names=names) + return cls.from_arrays(arrays, names=names, metadata=metadata) @staticmethod - def from_arrays(arrays, names=None): + def from_arrays(arrays, names=None, dict metadata=None): """ Construct a Table from Arrow arrays or columns @@ -680,22 +689,25 @@ cdef class Table: """ cdef: - vector[shared_ptr[CField]] fields vector[shared_ptr[CColumn]] columns shared_ptr[CSchema] schema shared_ptr[CTable] table + size_t K = len(arrays) - _schema_from_arrays(arrays, names, &schema) + _schema_from_arrays(arrays, names, metadata or {}, &schema) - cdef int K = len(arrays) - columns.resize(K) + columns.reserve(K) for i in range(K): if isinstance(arrays[i], Array): - columns[i].reset(new CColumn(schema.get().field(i), - ( arrays[i]).sp_array)) + columns.push_back( + make_shared[CColumn]( + schema.get().field(i), + ( arrays[i]).sp_array + ) + ) elif isinstance(arrays[i], Column): - columns[i] = ( arrays[i]).sp_column + columns.push_back(( arrays[i]).sp_column) else: raise ValueError(type(arrays[i])) diff --git a/python/pyarrow/includes/common.pxd b/python/pyarrow/includes/common.pxd index 44723faa7400..cc3b4b6fdaf9 100644 --- a/python/pyarrow/includes/common.pxd +++ b/python/pyarrow/includes/common.pxd @@ -19,9 +19,10 @@ from libc.stdint cimport * from libcpp cimport bool as c_bool -from libcpp.memory cimport shared_ptr, unique_ptr +from libcpp.memory cimport shared_ptr, unique_ptr, make_shared from libcpp.string cimport string as c_string from libcpp.vector cimport vector +from libcpp.unordered_map cimport unordered_map from cpython cimport PyObject cimport cpython diff --git a/python/pyarrow/includes/libarrow.pxd b/python/pyarrow/includes/libarrow.pxd index 473a0b9cd9b6..ef1a332bed52 100644 --- a/python/pyarrow/includes/libarrow.pxd +++ b/python/pyarrow/includes/libarrow.pxd @@ -1,4 +1,4 @@ -#t Licensed to the Apache Software Foundation (ASF) under one +# 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 @@ -19,6 +19,12 @@ from pyarrow.includes.common cimport * +cdef extern from "arrow/util/key_value_metadata.h" namespace "arrow" nogil: + cdef cppclass CKeyValueMetadata" arrow::KeyValueMetadata": + CKeyValueMetadata() + CKeyValueMetadata(const unordered_map[c_string, c_string]&) + void ToUnorderedMap(unordered_map[c_string, c_string]*) const + cdef extern from "arrow/api.h" namespace "arrow" nogil: enum Type" arrow::Type::type": @@ -170,10 +176,13 @@ cdef extern from "arrow/api.h" namespace "arrow" nogil: cdef cppclass CSchema" arrow::Schema": CSchema(const vector[shared_ptr[CField]]& fields) + CSchema(const vector[shared_ptr[CField]]& fields, + const CKeyValueMetadata& custom_metadata) c_bool Equals(const CSchema& other) shared_ptr[CField] field(int i) + const CKeyValueMetadata& custom_metadata() const shared_ptr[CField] GetFieldByName(c_string& name) int num_fields() c_string ToString()