Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/__init__.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/_compute_docstrings.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/_generated_version.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/acero.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/cffi.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/conftest.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/cuda.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/ipc.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/json.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/jvm.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/pandas_compat.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/substrait.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/__pycache__/util.cpython-310.pycAdded
- parrot/lib/python3.10/site-packages/pyarrow/include/arrow/builder.hAdded+33
- parrot/lib/python3.10/site-packages/pyarrow/include/arrow/chunked_array.hAdded+275
- parrot/lib/python3.10/site-packages/pyarrow/include/arrow/stl_iterator.hAdded+304
- parrot/lib/python3.10/site-packages/pyarrow/include/arrow/table_builder.hAdded+107
- parrot/lib/python3.10/site-packages/pyarrow/include/arrow/type.hAdded+2556
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/io.hAdded+20
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/reader.hAdded+35
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/schema.hAdded+21
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/writer.hAdded+25
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/reader.hAdded+379
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/schema.hAdded+184
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/test_util.hAdded+524
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/writer.hAdded+190
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/benchmark_util.hAdded+47
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter.hAdded+363
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter_reader.hAdded+68
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_page.hAdded+171
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_reader.hAdded+501
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_scanner.hAdded+264
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_writer.hAdded+307
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encoding.hAdded+476
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/crypto_factory.hAdded+152
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/encryption.hAdded+518
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_material_store.hAdded+57
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_unwrapper.hAdded+94
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_wrapper.hAdded+84
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_system_key_material_store.hAdded+89
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_encryption_key.hAdded+57
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_material.hAdded+129
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_metadata.hAdded+91
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_toolkit.hAdded+106
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client.hAdded+93
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client_factory.hAdded+38
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/local_wrap_kms_client.hAdded+94
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/test_encryption_util.hAdded+133
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/test_in_memory_kms.hAdded+94
- parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/two_level_cache_with_expiration.hAdded+157
123456789101112131415161718192021222324252627282930313233// 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.
#pragma once
#include <memory>
#include "arrow/array/builder_adaptive.h" // IWYU pragma: keep#include "arrow/array/builder_base.h" // IWYU pragma: keep#include "arrow/array/builder_binary.h" // IWYU pragma: keep#include "arrow/array/builder_decimal.h" // IWYU pragma: keep#include "arrow/array/builder_dict.h" // IWYU pragma: keep#include "arrow/array/builder_nested.h" // IWYU pragma: keep#include "arrow/array/builder_primitive.h" // IWYU pragma: keep#include "arrow/array/builder_run_end.h" // IWYU pragma: keep#include "arrow/array/builder_time.h" // IWYU pragma: keep#include "arrow/array/builder_union.h" // IWYU pragma: keep#include "arrow/status.h"#include "arrow/util/visibility.h"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275// 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.
#pragma once
#include <cstdint>#include <memory>#include <string>#include <utility>#include <vector>
#include "arrow/chunk_resolver.h"#include "arrow/compare.h"#include "arrow/result.h"#include "arrow/status.h"#include "arrow/type_fwd.h"#include "arrow/util/macros.h"#include "arrow/util/visibility.h"
namespace arrow {
class Array;class DataType;class MemoryPool;namespace stl {template <typename T, typename V>class ChunkedArrayIterator;} // namespace stl
/// \class ChunkedArray/// \brief A data structure managing a list of primitive Arrow arrays logically/// as one large array////// Data chunking is treated throughout this project largely as an/// implementation detail for performance and memory use optimization./// ChunkedArray allows Array objects to be collected and interpreted/// as a single logical array without requiring an expensive concatenation/// step.////// In some cases, data produced by a function may exceed the capacity of an/// Array (like BinaryArray or StringArray) and so returning multiple Arrays is/// the only possibility. In these cases, we recommend returning a ChunkedArray/// instead of vector of Arrays or some alternative.////// When data is processed in parallel, it may not be practical or possible to/// create large contiguous memory allocations and write output into them. With/// some data types, like binary and string types, it is not possible at all to/// produce non-chunked array outputs without requiring a concatenation step at/// the end of processing.////// Application developers may tune chunk sizes based on analysis of/// performance profiles but many developer-users will not need to be/// especially concerned with the chunking details.////// Preserving the chunk layout/sizes in processing steps is generally not/// considered to be a contract in APIs. A function may decide to alter the/// chunking of its result. Similarly, APIs accepting multiple ChunkedArray/// inputs should not expect the chunk layout to be the same in each input.class ARROW_EXPORT ChunkedArray { public: ChunkedArray(ChunkedArray&&) = default; ChunkedArray& operator=(ChunkedArray&&) = default;
/// \brief Construct a chunked array from a single Array explicit ChunkedArray(std::shared_ptr<Array> chunk) : ChunkedArray(ArrayVector{std::move(chunk)}) {}
/// \brief Construct a chunked array from a vector of arrays and an optional data type /// /// The vector elements must have the same data type. /// If the data type is passed explicitly, the vector may be empty. /// If the data type is omitted, the vector must be non-empty. explicit ChunkedArray(ArrayVector chunks, std::shared_ptr<DataType> type = NULLPTR);
// \brief Constructor with basic input validation. static Result<std::shared_ptr<ChunkedArray>> Make( ArrayVector chunks, std::shared_ptr<DataType> type = NULLPTR);
/// \brief Create an empty ChunkedArray of a given type /// /// The output ChunkedArray will have one chunk with an empty /// array of the given type. /// /// \param[in] type the data type of the empty ChunkedArray /// \param[in] pool the memory pool to allocate memory from /// \return the resulting ChunkedArray static Result<std::shared_ptr<ChunkedArray>> MakeEmpty( std::shared_ptr<DataType> type, MemoryPool* pool = default_memory_pool());
/// \return the total length of the chunked array; computed on construction int64_t length() const { return length_; }
/// \return the total number of nulls among all chunks int64_t null_count() const { return null_count_; }
/// \return the total number of chunks in the chunked array int num_chunks() const { return static_cast<int>(chunks_.size()); }
/// \return chunk a particular chunk from the chunked array const std::shared_ptr<Array>& chunk(int i) const { return chunks_[i]; }
/// \return an ArrayVector of chunks const ArrayVector& chunks() const { return chunks_; }
/// \brief Construct a zero-copy slice of the chunked array with the /// indicated offset and length /// /// \param[in] offset the position of the first element in the constructed /// slice /// \param[in] length the length of the slice. If there are not enough /// elements in the chunked array, the length will be adjusted accordingly /// /// \return a new object wrapped in std::shared_ptr<ChunkedArray> std::shared_ptr<ChunkedArray> Slice(int64_t offset, int64_t length) const;
/// \brief Slice from offset until end of the chunked array std::shared_ptr<ChunkedArray> Slice(int64_t offset) const;
/// \brief Flatten this chunked array as a vector of chunked arrays, one /// for each struct field /// /// \param[in] pool The pool for buffer allocations, if any Result<std::vector<std::shared_ptr<ChunkedArray>>> Flatten( MemoryPool* pool = default_memory_pool()) const;
/// Construct a zero-copy view of this chunked array with the given /// type. Calls Array::View on each constituent chunk. Always succeeds if /// there are zero chunks Result<std::shared_ptr<ChunkedArray>> View(const std::shared_ptr<DataType>& type) const;
/// \brief Return the type of the chunked array const std::shared_ptr<DataType>& type() const { return type_; }
/// \brief Return a Scalar containing the value of this array at index Result<std::shared_ptr<Scalar>> GetScalar(int64_t index) const;
/// \brief Determine if two chunked arrays are equal. /// /// Two chunked arrays can be equal only if they have equal datatypes. /// However, they may be equal even if they have different chunkings. bool Equals(const ChunkedArray& other, const EqualOptions& opts = EqualOptions::Defaults()) const; /// \brief Determine if two chunked arrays are equal. bool Equals(const std::shared_ptr<ChunkedArray>& other, const EqualOptions& opts = EqualOptions::Defaults()) const; /// \brief Determine if two chunked arrays approximately equal bool ApproxEquals(const ChunkedArray& other, const EqualOptions& = EqualOptions::Defaults()) const;
/// \return PrettyPrint representation suitable for debugging std::string ToString() const;
/// \brief Perform cheap validation checks to determine obvious inconsistencies /// within the chunk array's internal data. /// /// This is O(k*m) where k is the number of array descendents, /// and m is the number of chunks. /// /// \return Status Status Validate() const;
/// \brief Perform extensive validation checks to determine inconsistencies /// within the chunk array's internal data. /// /// This is O(k*n) where k is the number of array descendents, /// and n is the length in elements. /// /// \return Status Status ValidateFull() const;
protected: ArrayVector chunks_; std::shared_ptr<DataType> type_; int64_t length_; int64_t null_count_;
private: template <typename T, typename V> friend class ::arrow::stl::ChunkedArrayIterator; internal::ChunkResolver chunk_resolver_; ARROW_DISALLOW_COPY_AND_ASSIGN(ChunkedArray);};
namespace internal {
/// \brief EXPERIMENTAL: Utility for incremental iteration over contiguous/// pieces of potentially differently-chunked ChunkedArray objectsclass ARROW_EXPORT MultipleChunkIterator { public: MultipleChunkIterator(const ChunkedArray& left, const ChunkedArray& right) : left_(left), right_(right), pos_(0), length_(left.length()), chunk_idx_left_(0), chunk_idx_right_(0), chunk_pos_left_(0), chunk_pos_right_(0) {}
bool Next(std::shared_ptr<Array>* next_left, std::shared_ptr<Array>* next_right);
int64_t position() const { return pos_; }
private: const ChunkedArray& left_; const ChunkedArray& right_;
// The amount of the entire ChunkedArray consumed int64_t pos_;
// Length of the chunked array(s) int64_t length_;
// Current left chunk int chunk_idx_left_;
// Current right chunk int chunk_idx_right_;
// Offset into the current left chunk int64_t chunk_pos_left_;
// Offset into the current right chunk int64_t chunk_pos_right_;};
/// \brief Evaluate binary function on two ChunkedArray objects having possibly/// different chunk layouts. The passed binary function / functor should have/// the following signature.////// Status(const Array&, const Array&, int64_t)////// The third argument is the absolute position relative to the start of each/// ChunkedArray. The function is executed against each contiguous pair of/// array segments, slicing if necessary.////// For example, if two arrays have chunk sizes////// left: [10, 10, 20]/// right: [15, 10, 15]////// Then the following invocations take place (pseudocode)////// func(left.chunk[0][0:10], right.chunk[0][0:10], 0)/// func(left.chunk[1][0:5], right.chunk[0][10:15], 10)/// func(left.chunk[1][5:10], right.chunk[1][0:5], 15)/// func(left.chunk[2][0:5], right.chunk[1][5:10], 20)/// func(left.chunk[2][5:20], right.chunk[2][:], 25)template <typename Action>Status ApplyBinaryChunked(const ChunkedArray& left, const ChunkedArray& right, Action&& action) { MultipleChunkIterator iterator(left, right); std::shared_ptr<Array> left_piece, right_piece; while (iterator.Next(&left_piece, &right_piece)) { ARROW_RETURN_NOT_OK(action(*left_piece, *right_piece, iterator.position())); } return Status::OK();}
} // namespace internal} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304// 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.
#pragma once
#include <cassert>#include <cstddef>#include <iterator>#include <optional>#include <utility>
#include "arrow/chunked_array.h"#include "arrow/type.h"#include "arrow/type_fwd.h"#include "arrow/type_traits.h"#include "arrow/util/macros.h"
namespace arrow {namespace stl {
namespace detail {
template <typename ArrayType>struct DefaultValueAccessor { using ValueType = decltype(std::declval<ArrayType>().GetView(0));
ValueType operator()(const ArrayType& array, int64_t index) { return array.GetView(index); }};
} // namespace detail
template <typename ArrayType, typename ValueAccessor = detail::DefaultValueAccessor<ArrayType>>class ArrayIterator { public: using value_type = std::optional<typename ValueAccessor::ValueType>; using difference_type = int64_t; using pointer = value_type*; using reference = value_type&; using iterator_category = std::random_access_iterator_tag;
// Some algorithms need to default-construct an iterator ArrayIterator() : array_(NULLPTR), index_(0) {}
explicit ArrayIterator(const ArrayType& array, int64_t index = 0) : array_(&array), index_(index) {}
// Value access value_type operator*() const { assert(array_); return array_->IsNull(index_) ? value_type{} : array_->GetView(index_); }
value_type operator[](difference_type n) const { assert(array_); return array_->IsNull(index_ + n) ? value_type{} : array_->GetView(index_ + n); }
int64_t index() const { return index_; }
// Forward / backward ArrayIterator& operator++() { ++index_; return *this; } ArrayIterator& operator--() { --index_; return *this; } ArrayIterator operator++(int) { ArrayIterator tmp(*this); ++index_; return tmp; } ArrayIterator operator--(int) { ArrayIterator tmp(*this); --index_; return tmp; }
// Arithmetic difference_type operator-(const ArrayIterator& other) const { return index_ - other.index_; } ArrayIterator operator+(difference_type n) const { return ArrayIterator(*array_, index_ + n); } ArrayIterator operator-(difference_type n) const { return ArrayIterator(*array_, index_ - n); } friend inline ArrayIterator operator+(difference_type diff, const ArrayIterator& other) { return ArrayIterator(*other.array_, diff + other.index_); } friend inline ArrayIterator operator-(difference_type diff, const ArrayIterator& other) { return ArrayIterator(*other.array_, diff - other.index_); } ArrayIterator& operator+=(difference_type n) { index_ += n; return *this; } ArrayIterator& operator-=(difference_type n) { index_ -= n; return *this; }
// Comparisons bool operator==(const ArrayIterator& other) const { return index_ == other.index_; } bool operator!=(const ArrayIterator& other) const { return index_ != other.index_; } bool operator<(const ArrayIterator& other) const { return index_ < other.index_; } bool operator>(const ArrayIterator& other) const { return index_ > other.index_; } bool operator<=(const ArrayIterator& other) const { return index_ <= other.index_; } bool operator>=(const ArrayIterator& other) const { return index_ >= other.index_; }
private: const ArrayType* array_; int64_t index_;};
template <typename ArrayType, typename ValueAccessor = detail::DefaultValueAccessor<ArrayType>>class ChunkedArrayIterator { public: using value_type = std::optional<typename ValueAccessor::ValueType>; using difference_type = int64_t; using pointer = value_type*; using reference = value_type&; using iterator_category = std::random_access_iterator_tag;
// Some algorithms need to default-construct an iterator ChunkedArrayIterator() noexcept : chunked_array_(NULLPTR), index_(0) {}
explicit ChunkedArrayIterator(const ChunkedArray& chunked_array, int64_t index = 0) noexcept : chunked_array_(&chunked_array), index_(index) {}
// Value access value_type operator*() const { auto chunk_location = GetChunkLocation(index_); ArrayIterator<ArrayType> target_iterator{ arrow::internal::checked_cast<const ArrayType&>( *chunked_array_->chunk(static_cast<int>(chunk_location.chunk_index)))}; return target_iterator[chunk_location.index_in_chunk]; }
value_type operator[](difference_type n) const { return *(*this + n); }
int64_t index() const { return index_; }
// Forward / backward ChunkedArrayIterator& operator++() { (*this) += 1; return *this; } ChunkedArrayIterator& operator--() { (*this) -= 1; return *this; }
ChunkedArrayIterator operator++(int) { ChunkedArrayIterator tmp(*this); ++*this; return tmp; } ChunkedArrayIterator operator--(int) { ChunkedArrayIterator tmp(*this); --*this; return tmp; }
// Arithmetic difference_type operator-(const ChunkedArrayIterator& other) const { return index_ - other.index_; } ChunkedArrayIterator operator+(difference_type n) const { assert(chunked_array_); return ChunkedArrayIterator(*chunked_array_, index_ + n); } ChunkedArrayIterator operator-(difference_type n) const { assert(chunked_array_); return ChunkedArrayIterator(*chunked_array_, index_ - n); } friend inline ChunkedArrayIterator operator+(difference_type diff, const ChunkedArrayIterator& other) { assert(other.chunked_array_); return ChunkedArrayIterator(*other.chunked_array_, diff + other.index_); } friend inline ChunkedArrayIterator operator-(difference_type diff, const ChunkedArrayIterator& other) { assert(other.chunked_array_); return ChunkedArrayIterator(*other.chunked_array_, diff - other.index_); } ChunkedArrayIterator& operator+=(difference_type n) { index_ += n; return *this; } ChunkedArrayIterator& operator-=(difference_type n) { (*this) += -n; return *this; }
// Comparisons bool operator==(const ChunkedArrayIterator& other) const { return index_ == other.index_; } bool operator!=(const ChunkedArrayIterator& other) const { return index_ != other.index_; } bool operator<(const ChunkedArrayIterator& other) const { return index_ < other.index_; } bool operator>(const ChunkedArrayIterator& other) const { return index_ > other.index_; } bool operator<=(const ChunkedArrayIterator& other) const { return index_ <= other.index_; } bool operator>=(const ChunkedArrayIterator& other) const { return index_ >= other.index_; }
private: arrow::internal::ChunkLocation GetChunkLocation(int64_t index) const { assert(chunked_array_); return chunked_array_->chunk_resolver_.Resolve(index); }
const ChunkedArray* chunked_array_; int64_t index_;};
/// Return an iterator to the beginning of the chunked arraytemplate <typename Type, typename ArrayType = typename TypeTraits<Type>::ArrayType>ChunkedArrayIterator<ArrayType> Begin(const ChunkedArray& chunked_array) { return ChunkedArrayIterator<ArrayType>(chunked_array);}
/// Return an iterator to the end of the chunked arraytemplate <typename Type, typename ArrayType = typename TypeTraits<Type>::ArrayType>ChunkedArrayIterator<ArrayType> End(const ChunkedArray& chunked_array) { return ChunkedArrayIterator<ArrayType>(chunked_array, chunked_array.length());}
template <typename ArrayType>struct ChunkedArrayRange { const ChunkedArray* chunked_array;
ChunkedArrayIterator<ArrayType> begin() { return stl::ChunkedArrayIterator<ArrayType>(*chunked_array); } ChunkedArrayIterator<ArrayType> end() { return stl::ChunkedArrayIterator<ArrayType>(*chunked_array, chunked_array->length()); }};
/// Return an iterable range over the chunked arraytemplate <typename Type, typename ArrayType = typename TypeTraits<Type>::ArrayType>ChunkedArrayRange<ArrayType> Iterate(const ChunkedArray& chunked_array) { return stl::ChunkedArrayRange<ArrayType>{&chunked_array};}
} // namespace stl} // namespace arrow
namespace std {
template <typename ArrayType>struct iterator_traits<::arrow::stl::ArrayIterator<ArrayType>> { using IteratorType = ::arrow::stl::ArrayIterator<ArrayType>; using difference_type = typename IteratorType::difference_type; using value_type = typename IteratorType::value_type; using pointer = typename IteratorType::pointer; using reference = typename IteratorType::reference; using iterator_category = typename IteratorType::iterator_category;};
template <typename ArrayType>struct iterator_traits<::arrow::stl::ChunkedArrayIterator<ArrayType>> { using IteratorType = ::arrow::stl::ChunkedArrayIterator<ArrayType>; using difference_type = typename IteratorType::difference_type; using value_type = typename IteratorType::value_type; using pointer = typename IteratorType::pointer; using reference = typename IteratorType::reference; using iterator_category = typename IteratorType::iterator_category;};
} // namespace std123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107// 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.
#pragma once
#include <cstdint>#include <memory>#include <vector>
#include "arrow/array/builder_base.h"#include "arrow/status.h"#include "arrow/type.h"#include "arrow/util/checked_cast.h"#include "arrow/util/macros.h"#include "arrow/util/visibility.h"
namespace arrow {
class MemoryPool;class RecordBatch;
/// \class RecordBatchBuilder/// \brief Helper class for creating record batches iteratively given a known/// schemaclass ARROW_EXPORT RecordBatchBuilder { public: /// \brief Create and initialize a RecordBatchBuilder /// \param[in] schema The schema for the record batch /// \param[in] pool A MemoryPool to use for allocations /// \return the created builder instance static Result<std::unique_ptr<RecordBatchBuilder>> Make( const std::shared_ptr<Schema>& schema, MemoryPool* pool);
/// \brief Create and initialize a RecordBatchBuilder /// \param[in] schema The schema for the record batch /// \param[in] pool A MemoryPool to use for allocations /// \param[in] initial_capacity The initial capacity for the builders /// \return the created builder instance static Result<std::unique_ptr<RecordBatchBuilder>> Make( const std::shared_ptr<Schema>& schema, MemoryPool* pool, int64_t initial_capacity);
/// \brief Get base pointer to field builder /// \param i the field index /// \return pointer to ArrayBuilder ArrayBuilder* GetField(int i) { return raw_field_builders_[i]; }
/// \brief Return field builder casted to indicated specific builder type /// \param i the field index /// \return pointer to template type template <typename T> T* GetFieldAs(int i) { return internal::checked_cast<T*>(raw_field_builders_[i]); }
/// \brief Finish current batch and optionally reset /// \param[in] reset_builders the resulting RecordBatch /// \return the resulting RecordBatch Result<std::shared_ptr<RecordBatch>> Flush(bool reset_builders);
/// \brief Finish current batch and reset /// \return the resulting RecordBatch Result<std::shared_ptr<RecordBatch>> Flush();
/// \brief Set the initial capacity for new builders void SetInitialCapacity(int64_t capacity);
/// \brief The initial capacity for builders int64_t initial_capacity() const { return initial_capacity_; }
/// \brief The number of fields in the schema int num_fields() const { return schema_->num_fields(); }
/// \brief The number of fields in the schema std::shared_ptr<Schema> schema() const { return schema_; }
private: ARROW_DISALLOW_COPY_AND_ASSIGN(RecordBatchBuilder);
RecordBatchBuilder(const std::shared_ptr<Schema>& schema, MemoryPool* pool, int64_t initial_capacity);
Status CreateBuilders(); Status InitBuilders();
std::shared_ptr<Schema> schema_; int64_t initial_capacity_; MemoryPool* pool_;
std::vector<std::unique_ptr<ArrayBuilder>> field_builders_; std::vector<ArrayBuilder*> raw_field_builders_;};
} // namespace arrow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556// 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.
#pragma once
#include <atomic>#include <climits>#include <cstdint>#include <iosfwd>#include <limits>#include <memory>#include <optional>#include <string>#include <utility>#include <variant>#include <vector>
#include "arrow/result.h"#include "arrow/type_fwd.h" // IWYU pragma: export#include "arrow/util/checked_cast.h"#include "arrow/util/endian.h"#include "arrow/util/macros.h"#include "arrow/util/visibility.h"#include "arrow/visitor.h" // IWYU pragma: keep
namespace arrow {namespace detail {
/// \defgroup numeric-datatypes Datatypes for numeric data/// @{/// @}
/// \defgroup binary-datatypes Datatypes for binary/string data/// @{/// @}
/// \defgroup temporal-datatypes Datatypes for temporal data/// @{/// @}
/// \defgroup nested-datatypes Datatypes for nested data/// @{/// @}
class ARROW_EXPORT Fingerprintable { public: virtual ~Fingerprintable();
const std::string& fingerprint() const { auto p = fingerprint_.load(); if (ARROW_PREDICT_TRUE(p != NULLPTR)) { return *p; } return LoadFingerprintSlow(); }
const std::string& metadata_fingerprint() const { auto p = metadata_fingerprint_.load(); if (ARROW_PREDICT_TRUE(p != NULLPTR)) { return *p; } return LoadMetadataFingerprintSlow(); }
protected: const std::string& LoadFingerprintSlow() const; const std::string& LoadMetadataFingerprintSlow() const;
virtual std::string ComputeFingerprint() const = 0; virtual std::string ComputeMetadataFingerprint() const = 0;
mutable std::atomic<std::string*> fingerprint_{NULLPTR}; mutable std::atomic<std::string*> metadata_fingerprint_{NULLPTR};};
} // namespace detail
/// EXPERIMENTAL: Layout specification for a data typestruct ARROW_EXPORT DataTypeLayout { enum BufferKind { FIXED_WIDTH, VARIABLE_WIDTH, BITMAP, ALWAYS_NULL };
/// Layout specification for a single data type buffer struct BufferSpec { BufferKind kind; int64_t byte_width; // For FIXED_WIDTH
bool operator==(const BufferSpec& other) const { return kind == other.kind && (kind != FIXED_WIDTH || byte_width == other.byte_width); } bool operator!=(const BufferSpec& other) const { return !(*this == other); } };
static BufferSpec FixedWidth(int64_t w) { return BufferSpec{FIXED_WIDTH, w}; } static BufferSpec VariableWidth() { return BufferSpec{VARIABLE_WIDTH, -1}; } static BufferSpec Bitmap() { return BufferSpec{BITMAP, -1}; } static BufferSpec AlwaysNull() { return BufferSpec{ALWAYS_NULL, -1}; }
/// A vector of buffer layout specifications, one for each expected buffer std::vector<BufferSpec> buffers; /// Whether this type expects an associated dictionary array. bool has_dictionary = false; /// If this is provided, the number of buffers expected is only lower-bounded by /// buffers.size(). Buffers beyond this lower bound are expected to conform to /// variadic_spec. std::optional<BufferSpec> variadic_spec;
explicit DataTypeLayout(std::vector<BufferSpec> buffers, std::optional<BufferSpec> variadic_spec = {}) : buffers(std::move(buffers)), variadic_spec(variadic_spec) {}};
/// \brief Base class for all data types////// Data types in this library are all *logical*. They can be expressed as/// either a primitive physical type (bytes or bits of some fixed size), a/// nested type consisting of other data types, or another data type (e.g. a/// timestamp encoded as an int64).////// Simple datatypes may be entirely described by their Type::type id, but/// complex datatypes are usually parametric.class ARROW_EXPORT DataType : public std::enable_shared_from_this<DataType>, public detail::Fingerprintable, public util::EqualityComparable<DataType> { public: explicit DataType(Type::type id) : detail::Fingerprintable(), id_(id) {} ~DataType() override;
/// \brief Return whether the types are equal /// /// Types that are logically convertible from one to another (e.g. List<UInt8> /// and Binary) are NOT equal. bool Equals(const DataType& other, bool check_metadata = false) const;
/// \brief Return whether the types are equal bool Equals(const std::shared_ptr<DataType>& other, bool check_metadata = false) const;
/// \brief Return the child field at index i. const std::shared_ptr<Field>& field(int i) const { return children_[i]; }
/// \brief Return the children fields associated with this type. const FieldVector& fields() const { return children_; }
/// \brief Return the number of children fields associated with this type. int num_fields() const { return static_cast<int>(children_.size()); }
/// \brief Apply the TypeVisitor::Visit() method specialized to the data type Status Accept(TypeVisitor* visitor) const;
/// \brief A string representation of the type, including any children virtual std::string ToString(bool show_metadata = false) const = 0;
/// \brief Return hash value (excluding metadata in child fields) size_t Hash() const;
/// \brief A string name of the type, omitting any child fields /// /// \since 0.7.0 virtual std::string name() const = 0;
/// \brief Return the data type layout. Children are not included. /// /// \note Experimental API virtual DataTypeLayout layout() const = 0;
/// \brief Return the type category Type::type id() const { return id_; }
/// \brief Return the type category of the storage type virtual Type::type storage_id() const { return id_; }
/// \brief Returns the type's fixed byte width, if any. Returns -1 /// for non-fixed-width types, and should only be used for /// subclasses of FixedWidthType virtual int32_t byte_width() const { int32_t num_bits = this->bit_width(); return num_bits > 0 ? num_bits / 8 : -1; }
/// \brief Returns the type's fixed bit width, if any. Returns -1 /// for non-fixed-width types, and should only be used for /// subclasses of FixedWidthType virtual int bit_width() const { return -1; }
// \brief EXPERIMENTAL: Enable retrieving shared_ptr<DataType> from a const // context. std::shared_ptr<DataType> GetSharedPtr() const { return const_cast<DataType*>(this)->shared_from_this(); }
protected: // Dummy version that returns a null string (indicating not implemented). // Subclasses should override for fast equality checks. std::string ComputeFingerprint() const override;
// Generic versions that works for all regular types, nested or not. std::string ComputeMetadataFingerprint() const override;
Type::type id_; FieldVector children_;
private: ARROW_DISALLOW_COPY_AND_ASSIGN(DataType);};
/// \brief EXPERIMENTAL: Container for a type pointer which can hold a/// dynamically created shared_ptr<DataType> if it needs to.struct ARROW_EXPORT TypeHolder { const DataType* type = NULLPTR; std::shared_ptr<DataType> owned_type;
TypeHolder() = default; TypeHolder(const TypeHolder& other) = default; TypeHolder& operator=(const TypeHolder& other) = default; TypeHolder(TypeHolder&& other) = default; TypeHolder& operator=(TypeHolder&& other) = default;
TypeHolder(std::shared_ptr<DataType> owned_type) // NOLINT implicit construction : type(owned_type.get()), owned_type(std::move(owned_type)) {}
TypeHolder(const DataType* type) // NOLINT implicit construction : type(type) {}
Type::type id() const { return this->type->id(); }
std::shared_ptr<DataType> GetSharedPtr() const { return this->type != NULLPTR ? this->type->GetSharedPtr() : NULLPTR; }
const DataType& operator*() const { return *this->type; }
operator bool() const { return this->type != NULLPTR; }
bool operator==(const TypeHolder& other) const { if (type == other.type) return true; if (type == NULLPTR || other.type == NULLPTR) return false; return type->Equals(*other.type); }
bool operator==(decltype(NULLPTR)) const { return this->type == NULLPTR; }
bool operator==(const DataType& other) const { if (this->type == NULLPTR) return false; return other.Equals(*this->type); }
bool operator!=(const DataType& other) const { return !(*this == other); }
bool operator==(const std::shared_ptr<DataType>& other) const { return *this == *other; }
bool operator!=(const TypeHolder& other) const { return !(*this == other); }
std::string ToString(bool show_metadata = false) const { return this->type ? this->type->ToString(show_metadata) : "<NULLPTR>"; }
static std::string ToString(const std::vector<TypeHolder>&, bool show_metadata = false);
static std::vector<TypeHolder> FromTypes( const std::vector<std::shared_ptr<DataType>>& types);};
ARROW_EXPORTstd::ostream& operator<<(std::ostream& os, const DataType& type);
ARROW_EXPORTstd::ostream& operator<<(std::ostream& os, const TypeHolder& type);
/// \brief Return the compatible physical data type////// Some types may have distinct logical meanings but the exact same physical/// representation. For example, TimestampType has Int64Type as a physical/// type (defined as TimestampType::PhysicalType).////// The return value is as follows:/// - if a `PhysicalType` alias exists in the concrete type class, return/// an instance of `PhysicalType`./// - otherwise, return the input type itself.std::shared_ptr<DataType> GetPhysicalType(const std::shared_ptr<DataType>& type);
/// \brief Base class for all fixed-width data typesclass ARROW_EXPORT FixedWidthType : public DataType { public: using DataType::DataType; // This is only for preventing defining this class in each // translation unit to avoid one-definition-rule violation. ~FixedWidthType() override;};
/// \brief Base class for all data types representing primitive valuesclass ARROW_EXPORT PrimitiveCType : public FixedWidthType { public: using FixedWidthType::FixedWidthType; // This is only for preventing defining this class in each // translation unit to avoid one-definition-rule violation. ~PrimitiveCType() override;};
/// \brief Base class for all numeric data typesclass ARROW_EXPORT NumberType : public PrimitiveCType { public: using PrimitiveCType::PrimitiveCType; // This is only for preventing defining this class in each // translation unit to avoid one-definition-rule violation. ~NumberType() override;};
/// \brief Base class for all integral data typesclass ARROW_EXPORT IntegerType : public NumberType { public: using NumberType::NumberType; // This is only for preventing defining this class in each // translation unit to avoid one-definition-rule violation. ~IntegerType() override; virtual bool is_signed() const = 0;};
/// \brief Base class for all floating-point data typesclass ARROW_EXPORT FloatingPointType : public NumberType { public: using NumberType::NumberType; // This is only for preventing defining this class in each // translation unit to avoid one-definition-rule violation. ~FloatingPointType() override; enum Precision { HALF, SINGLE, DOUBLE }; virtual Precision precision() const = 0;};
/// \brief Base class for all parametric data typesclass ParametricType {};
class ARROW_EXPORT NestedType : public DataType, public ParametricType { public: using DataType::DataType; // This is only for preventing defining this class in each // translation unit to avoid one-definition-rule violation. ~NestedType() override;};
/// \brief The combination of a field name and data type, with optional metadata////// Fields are used to describe the individual constituents of a/// nested DataType or a Schema.////// A field's metadata is represented by a KeyValueMetadata instance,/// which holds arbitrary key-value pairs.class ARROW_EXPORT Field : public detail::Fingerprintable, public util::EqualityComparable<Field> { public: Field(std::string name, std::shared_ptr<DataType> type, bool nullable = true, std::shared_ptr<const KeyValueMetadata> metadata = NULLPTR) : detail::Fingerprintable(), name_(std::move(name)), type_(std::move(type)), nullable_(nullable), metadata_(std::move(metadata)) {}
~Field() override;
/// \brief Return the field's attached metadata std::shared_ptr<const KeyValueMetadata> metadata() const { return metadata_; }
/// \brief Return whether the field has non-empty metadata bool HasMetadata() const;
/// \brief Return a copy of this field with the given metadata attached to it std::shared_ptr<Field> WithMetadata( const std::shared_ptr<const KeyValueMetadata>& metadata) const;
/// \brief EXPERIMENTAL: Return a copy of this field with the given metadata /// merged with existing metadata (any colliding keys will be overridden by /// the passed metadata) std::shared_ptr<Field> WithMergedMetadata( const std::shared_ptr<const KeyValueMetadata>& metadata) const;
/// \brief Return a copy of this field without any metadata attached to it std::shared_ptr<Field> RemoveMetadata() const;
/// \brief Return a copy of this field with the replaced type. std::shared_ptr<Field> WithType(const std::shared_ptr<DataType>& type) const;
/// \brief Return a copy of this field with the replaced name. std::shared_ptr<Field> WithName(const std::string& name) const;
/// \brief Return a copy of this field with the replaced nullability. std::shared_ptr<Field> WithNullable(bool nullable) const;
/// \brief Options that control the behavior of `MergeWith`. /// Options are to be added to allow type conversions, including integer /// widening, promotion from integer to float, or conversion to or from boolean. struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> { /// If true, a Field of NullType can be unified with a Field of another type. /// The unified field will be of the other type and become nullable. /// Nullability will be promoted to the looser option (nullable if one is not /// nullable). bool promote_nullability = true;
/// Allow a decimal to be unified with another decimal of the same /// width, adjusting scale and precision as appropriate. May fail /// if the adjustment is not possible. bool promote_decimal = false;
/// Allow a decimal to be promoted to a float. The float type will /// not itself be promoted (e.g. Decimal128 + Float32 = Float32). bool promote_decimal_to_float = false;
/// Allow an integer to be promoted to a decimal. /// /// May fail if the decimal has insufficient precision to /// accommodate the integer (see promote_numeric_width). bool promote_integer_to_decimal = false;
/// Allow an integer of a given bit width to be promoted to a /// float; the result will be a float of an equal or greater bit /// width to both of the inputs. Examples: /// - int8 + float32 = float32 /// - int32 + float32 = float64 /// - int32 + float64 = float64 /// Because an int32 cannot always be represented exactly in the /// 24 bits of a float32 mantissa. bool promote_integer_to_float = false;
/// Allow an unsigned integer of a given bit width to be promoted /// to a signed integer that fits into the signed type: /// uint + int16 = int16 /// When widening is needed, set promote_numeric_width to true: /// uint16 + int16 = int32 bool promote_integer_sign = false;
/// Allow an integer, float, or decimal of a given bit width to be /// promoted to an equivalent type of a greater bit width. bool promote_numeric_width = false;
/// Allow strings to be promoted to binary types. Promotion of fixed size /// binary types to variable sized formats, and binary to large binary, /// and string to large string. bool promote_binary = false;
/// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc bool promote_temporal_unit = false;
/// Allow promotion from a list to a large-list and from a fixed-size list to a /// variable sized list bool promote_list = false;
/// Unify dictionary index types and dictionary value types. bool promote_dictionary = false;
/// Allow merging ordered and non-ordered dictionaries. /// The result will be ordered if and only if both inputs /// are ordered. bool promote_dictionary_ordered = false;
/// Get default options. Only NullType will be merged with other types. static MergeOptions Defaults() { return MergeOptions(); } /// Get permissive options. All options are enabled, except /// promote_dictionary_ordered. static MergeOptions Permissive(); /// Get a human-readable representation of the options. std::string ToString() const; };
/// \brief Merge the current field with a field of the same name. /// /// The two fields must be compatible, i.e: /// - have the same name /// - have the same type, or of compatible types according to `options`. /// /// The metadata of the current field is preserved; the metadata of the other /// field is discarded. Result<std::shared_ptr<Field>> MergeWith( const Field& other, MergeOptions options = MergeOptions::Defaults()) const; Result<std::shared_ptr<Field>> MergeWith( const std::shared_ptr<Field>& other, MergeOptions options = MergeOptions::Defaults()) const;
FieldVector Flatten() const;
/// \brief Indicate if fields are equals. /// /// \param[in] other field to check equality with. /// \param[in] check_metadata controls if it should check for metadata /// equality. /// /// \return true if fields are equal, false otherwise. bool Equals(const Field& other, bool check_metadata = false) const; bool Equals(const std::shared_ptr<Field>& other, bool check_metadata = false) const;
/// \brief Indicate if fields are compatibles. /// /// See the criteria of MergeWith. /// /// \return true if fields are compatible, false otherwise. bool IsCompatibleWith(const Field& other) const; bool IsCompatibleWith(const std::shared_ptr<Field>& other) const;
/// \brief Return a string representation ot the field /// \param[in] show_metadata when true, if KeyValueMetadata is non-empty, /// print keys and values in the output std::string ToString(bool show_metadata = false) const;
/// \brief Return the field name const std::string& name() const { return name_; } /// \brief Return the field data type const std::shared_ptr<DataType>& type() const { return type_; } /// \brief Return whether the field is nullable bool nullable() const { return nullable_; }
std::shared_ptr<Field> Copy() const;
private: std::string ComputeFingerprint() const override; std::string ComputeMetadataFingerprint() const override;
// Field name std::string name_;
// The field's data type std::shared_ptr<DataType> type_;
// Fields can be nullable bool nullable_;
// The field's metadata, if any std::shared_ptr<const KeyValueMetadata> metadata_;
ARROW_DISALLOW_COPY_AND_ASSIGN(Field);};
ARROW_EXPORT void PrintTo(const Field& field, std::ostream* os);
namespace detail {
template <typename DERIVED, typename BASE, Type::type TYPE_ID, typename C_TYPE>class ARROW_EXPORT CTypeImpl : public BASE { public: static constexpr Type::type type_id = TYPE_ID; using c_type = C_TYPE; using PhysicalType = DERIVED;
CTypeImpl() : BASE(TYPE_ID) {}
int bit_width() const override { return static_cast<int>(sizeof(C_TYPE) * CHAR_BIT); }
DataTypeLayout layout() const override { return DataTypeLayout( {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(C_TYPE))}); }
std::string name() const override { return DERIVED::type_name(); }
std::string ToString(bool show_metadata = false) const override { return this->name(); }};
template <typename DERIVED, typename BASE, Type::type TYPE_ID, typename C_TYPE>constexpr Type::type CTypeImpl<DERIVED, BASE, TYPE_ID, C_TYPE>::type_id;
template <typename DERIVED, Type::type TYPE_ID, typename C_TYPE>class IntegerTypeImpl : public detail::CTypeImpl<DERIVED, IntegerType, TYPE_ID, C_TYPE> { bool is_signed() const override { return std::is_signed<C_TYPE>::value; }};
} // namespace detail
/// Concrete type class for always-null dataclass ARROW_EXPORT NullType : public DataType { public: static constexpr Type::type type_id = Type::NA;
static constexpr const char* type_name() { return "null"; }
NullType() : DataType(Type::NA) {}
std::string ToString(bool show_metadata = false) const override;
DataTypeLayout layout() const override { return DataTypeLayout({DataTypeLayout::AlwaysNull()}); }
std::string name() const override { return "null"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for boolean dataclass ARROW_EXPORT BooleanType : public detail::CTypeImpl<BooleanType, PrimitiveCType, Type::BOOL, bool> { public: static constexpr const char* type_name() { return "bool"; }
// BooleanType within arrow use a single bit instead of the C 8-bits layout. int bit_width() const final { return 1; }
DataTypeLayout layout() const override { return DataTypeLayout({DataTypeLayout::Bitmap(), DataTypeLayout::Bitmap()}); }
protected: std::string ComputeFingerprint() const override;};
/// \addtogroup numeric-datatypes////// @{
/// Concrete type class for unsigned 8-bit integer dataclass ARROW_EXPORT UInt8Type : public detail::IntegerTypeImpl<UInt8Type, Type::UINT8, uint8_t> { public: static constexpr const char* type_name() { return "uint8"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for signed 8-bit integer dataclass ARROW_EXPORT Int8Type : public detail::IntegerTypeImpl<Int8Type, Type::INT8, int8_t> { public: static constexpr const char* type_name() { return "int8"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for unsigned 16-bit integer dataclass ARROW_EXPORT UInt16Type : public detail::IntegerTypeImpl<UInt16Type, Type::UINT16, uint16_t> { public: static constexpr const char* type_name() { return "uint16"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for signed 16-bit integer dataclass ARROW_EXPORT Int16Type : public detail::IntegerTypeImpl<Int16Type, Type::INT16, int16_t> { public: static constexpr const char* type_name() { return "int16"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for unsigned 32-bit integer dataclass ARROW_EXPORT UInt32Type : public detail::IntegerTypeImpl<UInt32Type, Type::UINT32, uint32_t> { public: static constexpr const char* type_name() { return "uint32"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for signed 32-bit integer dataclass ARROW_EXPORT Int32Type : public detail::IntegerTypeImpl<Int32Type, Type::INT32, int32_t> { public: static constexpr const char* type_name() { return "int32"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for unsigned 64-bit integer dataclass ARROW_EXPORT UInt64Type : public detail::IntegerTypeImpl<UInt64Type, Type::UINT64, uint64_t> { public: static constexpr const char* type_name() { return "uint64"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for signed 64-bit integer dataclass ARROW_EXPORT Int64Type : public detail::IntegerTypeImpl<Int64Type, Type::INT64, int64_t> { public: static constexpr const char* type_name() { return "int64"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for 16-bit floating-point dataclass ARROW_EXPORT HalfFloatType : public detail::CTypeImpl<HalfFloatType, FloatingPointType, Type::HALF_FLOAT, uint16_t> { public: Precision precision() const override; static constexpr const char* type_name() { return "halffloat"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for 32-bit floating-point data (C "float")class ARROW_EXPORT FloatType : public detail::CTypeImpl<FloatType, FloatingPointType, Type::FLOAT, float> { public: Precision precision() const override; static constexpr const char* type_name() { return "float"; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for 64-bit floating-point data (C "double")class ARROW_EXPORT DoubleType : public detail::CTypeImpl<DoubleType, FloatingPointType, Type::DOUBLE, double> { public: Precision precision() const override; static constexpr const char* type_name() { return "double"; }
protected: std::string ComputeFingerprint() const override;};
/// @}
/// \brief Base class for all variable-size binary data typesclass ARROW_EXPORT BaseBinaryType : public DataType { public: using DataType::DataType; // This is only for preventing defining this class in each // translation unit to avoid one-definition-rule violation. ~BaseBinaryType() override;};
constexpr int64_t kBinaryMemoryLimit = std::numeric_limits<int32_t>::max() - 1;
/// \addtogroup binary-datatypes////// @{
/// \brief Concrete type class for variable-size binary dataclass ARROW_EXPORT BinaryType : public BaseBinaryType { public: static constexpr Type::type type_id = Type::BINARY; static constexpr bool is_utf8 = false; using offset_type = int32_t; using PhysicalType = BinaryType;
static constexpr const char* type_name() { return "binary"; }
BinaryType() : BinaryType(Type::BINARY) {}
DataTypeLayout layout() const override { return DataTypeLayout({DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(offset_type)), DataTypeLayout::VariableWidth()}); }
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "binary"; }
protected: std::string ComputeFingerprint() const override;
// Allow subclasses like StringType to change the logical type. explicit BinaryType(Type::type logical_type) : BaseBinaryType(logical_type) {}};
/// \brief Concrete type class for variable-size binary view dataclass ARROW_EXPORT BinaryViewType : public DataType { public: static constexpr Type::type type_id = Type::BINARY_VIEW; static constexpr bool is_utf8 = false; using PhysicalType = BinaryViewType;
static constexpr int kSize = 16; static constexpr int kInlineSize = 12; static constexpr int kPrefixSize = 4;
/// Variable length string or binary with inline optimization for small values (12 bytes /// or fewer). This is similar to std::string_view except limited in size to INT32_MAX /// and at least the first four bytes of the string are copied inline (accessible /// without pointer dereference). This inline prefix allows failing comparisons early. /// Furthermore when dealing with short strings the CPU cache working set is reduced /// since many can be inline. /// /// This union supports two states: /// /// - Entirely inlined string data /// |----|--------------| /// ^ ^ /// | | /// size in-line string data, zero padded /// /// - Reference into a buffer /// |----|----|----|----| /// ^ ^ ^ ^ /// | | | | /// size | | `------. /// prefix | | /// buffer index | /// offset in buffer /// /// Adapted from TU Munich's UmbraDB [1], Velox, DuckDB. /// /// [1]: https://db.in.tum.de/~freitag/papers/p29-neumann-cidr20.pdf /// /// Alignment to 64 bits enables an aligned load of the size and prefix into /// a single 64 bit integer, which is useful to the comparison fast path. union alignas(int64_t) c_type { struct { int32_t size; std::array<uint8_t, kInlineSize> data; } inlined;
struct { int32_t size; std::array<uint8_t, kPrefixSize> prefix; int32_t buffer_index; int32_t offset; } ref;
/// The number of bytes viewed. int32_t size() const { // Size is in the common initial subsequence of each member of the union, // so accessing `inlined.size` is legal even if another member is active. return inlined.size; }
/// True if the view's data is entirely stored inline. bool is_inline() const { return size() <= kInlineSize; }
/// Return a pointer to the inline data of a view. /// /// For inline views, this points to the entire data of the view. /// For other views, this points to the 4 byte prefix. const uint8_t* inline_data() const& { // Since `ref.prefix` has the same address as `inlined.data`, // the branch will be trivially optimized out. return is_inline() ? inlined.data.data() : ref.prefix.data(); } const uint8_t* inline_data() && = delete; }; static_assert(sizeof(c_type) == kSize); static_assert(std::is_trivial_v<c_type>);
static constexpr const char* type_name() { return "binary_view"; }
BinaryViewType() : BinaryViewType(Type::BINARY_VIEW) {}
DataTypeLayout layout() const override { return DataTypeLayout({DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(kSize)}, DataTypeLayout::VariableWidth()); }
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "binary_view"; }
protected: std::string ComputeFingerprint() const override;
// Allow subclasses like StringType to change the logical type. explicit BinaryViewType(Type::type logical_type) : DataType(logical_type) {}};
/// \brief Concrete type class for large variable-size binary dataclass ARROW_EXPORT LargeBinaryType : public BaseBinaryType { public: static constexpr Type::type type_id = Type::LARGE_BINARY; static constexpr bool is_utf8 = false; using offset_type = int64_t; using PhysicalType = LargeBinaryType;
static constexpr const char* type_name() { return "large_binary"; }
LargeBinaryType() : LargeBinaryType(Type::LARGE_BINARY) {}
DataTypeLayout layout() const override { return DataTypeLayout({DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(offset_type)), DataTypeLayout::VariableWidth()}); }
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "large_binary"; }
protected: std::string ComputeFingerprint() const override;
// Allow subclasses like LargeStringType to change the logical type. explicit LargeBinaryType(Type::type logical_type) : BaseBinaryType(logical_type) {}};
/// \brief Concrete type class for variable-size string data, utf8-encodedclass ARROW_EXPORT StringType : public BinaryType { public: static constexpr Type::type type_id = Type::STRING; static constexpr bool is_utf8 = true; using PhysicalType = BinaryType;
static constexpr const char* type_name() { return "utf8"; }
StringType() : BinaryType(Type::STRING) {}
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "utf8"; }
protected: std::string ComputeFingerprint() const override;};
/// \brief Concrete type class for variable-size string data, utf8-encodedclass ARROW_EXPORT StringViewType : public BinaryViewType { public: static constexpr Type::type type_id = Type::STRING_VIEW; static constexpr bool is_utf8 = true; using PhysicalType = BinaryViewType;
static constexpr const char* type_name() { return "utf8_view"; }
StringViewType() : BinaryViewType(Type::STRING_VIEW) {}
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "utf8_view"; }
protected: std::string ComputeFingerprint() const override;};
/// \brief Concrete type class for large variable-size string data, utf8-encodedclass ARROW_EXPORT LargeStringType : public LargeBinaryType { public: static constexpr Type::type type_id = Type::LARGE_STRING; static constexpr bool is_utf8 = true; using PhysicalType = LargeBinaryType;
static constexpr const char* type_name() { return "large_utf8"; }
LargeStringType() : LargeBinaryType(Type::LARGE_STRING) {}
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "large_utf8"; }
protected: std::string ComputeFingerprint() const override;};
/// \brief Concrete type class for fixed-size binary dataclass ARROW_EXPORT FixedSizeBinaryType : public FixedWidthType, public ParametricType { public: static constexpr Type::type type_id = Type::FIXED_SIZE_BINARY; static constexpr bool is_utf8 = false;
static constexpr const char* type_name() { return "fixed_size_binary"; }
explicit FixedSizeBinaryType(int32_t byte_width) : FixedWidthType(Type::FIXED_SIZE_BINARY), byte_width_(byte_width) {} explicit FixedSizeBinaryType(int32_t byte_width, Type::type override_type_id) : FixedWidthType(override_type_id), byte_width_(byte_width) {}
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "fixed_size_binary"; }
DataTypeLayout layout() const override { return DataTypeLayout( {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(byte_width())}); }
int byte_width() const override { return byte_width_; }
int bit_width() const override;
// Validating constructor static Result<std::shared_ptr<DataType>> Make(int32_t byte_width);
protected: std::string ComputeFingerprint() const override;
int32_t byte_width_;};
/// @}
/// \addtogroup numeric-datatypes////// @{
/// \brief Base type class for (fixed-size) decimal dataclass ARROW_EXPORT DecimalType : public FixedSizeBinaryType { public: explicit DecimalType(Type::type type_id, int32_t byte_width, int32_t precision, int32_t scale) : FixedSizeBinaryType(byte_width, type_id), precision_(precision), scale_(scale) {}
/// Constructs concrete decimal types static Result<std::shared_ptr<DataType>> Make(Type::type type_id, int32_t precision, int32_t scale);
int32_t precision() const { return precision_; } int32_t scale() const { return scale_; }
/// \brief Returns the number of bytes needed for precision. /// /// precision must be >= 1 static int32_t DecimalSize(int32_t precision);
protected: std::string ComputeFingerprint() const override;
int32_t precision_; int32_t scale_;};
/// \brief Concrete type class for 128-bit decimal data////// Arrow decimals are fixed-point decimal numbers encoded as a scaled/// integer. The precision is the number of significant digits that the/// decimal type can represent; the scale is the number of digits after/// the decimal point (note the scale can be negative).////// As an example, `Decimal128Type(7, 3)` can exactly represent the numbers/// 1234.567 and -1234.567 (encoded internally as the 128-bit integers/// 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567.////// Decimal128Type has a maximum precision of 38 significant digits/// (also available as Decimal128Type::kMaxPrecision)./// If higher precision is needed, consider using Decimal256Type.class ARROW_EXPORT Decimal128Type : public DecimalType { public: static constexpr Type::type type_id = Type::DECIMAL128;
static constexpr const char* type_name() { return "decimal128"; }
/// Decimal128Type constructor that aborts on invalid input. explicit Decimal128Type(int32_t precision, int32_t scale);
/// Decimal128Type constructor that returns an error on invalid input. static Result<std::shared_ptr<DataType>> Make(int32_t precision, int32_t scale);
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "decimal128"; }
static constexpr int32_t kMinPrecision = 1; static constexpr int32_t kMaxPrecision = 38; static constexpr int32_t kByteWidth = 16;};
/// \brief Concrete type class for 256-bit decimal data////// Arrow decimals are fixed-point decimal numbers encoded as a scaled/// integer. The precision is the number of significant digits that the/// decimal type can represent; the scale is the number of digits after/// the decimal point (note the scale can be negative).////// Decimal256Type has a maximum precision of 76 significant digits./// (also available as Decimal256Type::kMaxPrecision).////// For most use cases, the maximum precision offered by Decimal128Type/// is sufficient, and it will result in a more compact and more efficient/// encoding.class ARROW_EXPORT Decimal256Type : public DecimalType { public: static constexpr Type::type type_id = Type::DECIMAL256;
static constexpr const char* type_name() { return "decimal256"; }
/// Decimal256Type constructor that aborts on invalid input. explicit Decimal256Type(int32_t precision, int32_t scale);
/// Decimal256Type constructor that returns an error on invalid input. static Result<std::shared_ptr<DataType>> Make(int32_t precision, int32_t scale);
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "decimal256"; }
static constexpr int32_t kMinPrecision = 1; static constexpr int32_t kMaxPrecision = 76; static constexpr int32_t kByteWidth = 32;};
/// @}
/// \addtogroup nested-datatypes////// @{
/// \brief Base class for all variable-size list data typesclass ARROW_EXPORT BaseListType : public NestedType { public: using NestedType::NestedType; // This is only for preventing defining this class in each // translation unit to avoid one-definition-rule violation. ~BaseListType() override; const std::shared_ptr<Field>& value_field() const { return children_[0]; }
const std::shared_ptr<DataType>& value_type() const { return children_[0]->type(); }};
/// \brief Concrete type class for list data////// List data is nested data where each value is a variable number of/// child items. Lists can be recursively nested, for example/// list(list(int32)).class ARROW_EXPORT ListType : public BaseListType { public: static constexpr Type::type type_id = Type::LIST; using offset_type = int32_t;
static constexpr const char* type_name() { return "list"; }
// List can contain any other logical value type explicit ListType(std::shared_ptr<DataType> value_type) : ListType(std::make_shared<Field>("item", std::move(value_type))) {}
explicit ListType(std::shared_ptr<Field> value_field) : BaseListType(type_id) { children_ = {std::move(value_field)}; }
DataTypeLayout layout() const override { return DataTypeLayout( {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(offset_type))}); }
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "list"; }
protected: std::string ComputeFingerprint() const override;};
/// \brief Concrete type class for large list data////// LargeListType is like ListType but with 64-bit rather than 32-bit offsets.class ARROW_EXPORT LargeListType : public BaseListType { public: static constexpr Type::type type_id = Type::LARGE_LIST; using offset_type = int64_t;
static constexpr const char* type_name() { return "large_list"; }
// List can contain any other logical value type explicit LargeListType(std::shared_ptr<DataType> value_type) : LargeListType(std::make_shared<Field>("item", std::move(value_type))) {}
explicit LargeListType(std::shared_ptr<Field> value_field) : BaseListType(type_id) { children_ = {std::move(value_field)}; }
DataTypeLayout layout() const override { return DataTypeLayout( {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(offset_type))}); }
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "large_list"; }
protected: std::string ComputeFingerprint() const override;};
/// \brief Type class for array of list viewsclass ARROW_EXPORT ListViewType : public BaseListType { public: static constexpr Type::type type_id = Type::LIST_VIEW; using offset_type = int32_t;
static constexpr const char* type_name() { return "list_view"; }
// ListView can contain any other logical value type explicit ListViewType(const std::shared_ptr<DataType>& value_type) : ListViewType(std::make_shared<Field>("item", value_type)) {}
explicit ListViewType(const std::shared_ptr<Field>& value_field) : BaseListType(type_id) { children_ = {value_field}; }
DataTypeLayout layout() const override { return DataTypeLayout({DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(offset_type)), DataTypeLayout::FixedWidth(sizeof(offset_type))}); }
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "list_view"; }
protected: std::string ComputeFingerprint() const override;};
/// \brief Concrete type class for large list-view data////// LargeListViewType is like ListViewType but with 64-bit rather than 32-bit offsets and/// sizes.class ARROW_EXPORT LargeListViewType : public BaseListType { public: static constexpr Type::type type_id = Type::LARGE_LIST_VIEW; using offset_type = int64_t;
static constexpr const char* type_name() { return "large_list_view"; }
// LargeListView can contain any other logical value type explicit LargeListViewType(const std::shared_ptr<DataType>& value_type) : LargeListViewType(std::make_shared<Field>("item", value_type)) {}
explicit LargeListViewType(const std::shared_ptr<Field>& value_field) : BaseListType(type_id) { children_ = {value_field}; }
DataTypeLayout layout() const override { return DataTypeLayout({DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(offset_type)), DataTypeLayout::FixedWidth(sizeof(offset_type))}); }
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "large_list_view"; }
protected: std::string ComputeFingerprint() const override;};
/// \brief Concrete type class for map data////// Map data is nested data where each value is a variable number of/// key-item pairs. Its physical representation is the same as/// a list of `{key, item}` structs.////// Maps can be recursively nested, for example map(utf8, map(utf8, int32)).class ARROW_EXPORT MapType : public ListType { public: static constexpr Type::type type_id = Type::MAP;
static constexpr const char* type_name() { return "map"; }
MapType(std::shared_ptr<DataType> key_type, std::shared_ptr<DataType> item_type, bool keys_sorted = false);
MapType(std::shared_ptr<DataType> key_type, std::shared_ptr<Field> item_field, bool keys_sorted = false);
MapType(std::shared_ptr<Field> key_field, std::shared_ptr<Field> item_field, bool keys_sorted = false);
explicit MapType(std::shared_ptr<Field> value_field, bool keys_sorted = false);
// Validating constructor static Result<std::shared_ptr<DataType>> Make(std::shared_ptr<Field> value_field, bool keys_sorted = false);
std::shared_ptr<Field> key_field() const { return value_type()->field(0); } std::shared_ptr<DataType> key_type() const { return key_field()->type(); }
std::shared_ptr<Field> item_field() const { return value_type()->field(1); } std::shared_ptr<DataType> item_type() const { return item_field()->type(); }
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "map"; }
bool keys_sorted() const { return keys_sorted_; }
private: std::string ComputeFingerprint() const override;
bool keys_sorted_;};
/// \brief Concrete type class for fixed size list dataclass ARROW_EXPORT FixedSizeListType : public BaseListType { public: static constexpr Type::type type_id = Type::FIXED_SIZE_LIST; // While the individual item size is 32-bit, the overall data size // (item size * list length) may not fit in a 32-bit int. using offset_type = int64_t;
static constexpr const char* type_name() { return "fixed_size_list"; }
// List can contain any other logical value type FixedSizeListType(std::shared_ptr<DataType> value_type, int32_t list_size) : FixedSizeListType(std::make_shared<Field>("item", std::move(value_type)), list_size) {}
FixedSizeListType(std::shared_ptr<Field> value_field, int32_t list_size) : BaseListType(type_id), list_size_(list_size) { children_ = {std::move(value_field)}; }
DataTypeLayout layout() const override { return DataTypeLayout({DataTypeLayout::Bitmap()}); }
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "fixed_size_list"; }
int32_t list_size() const { return list_size_; }
protected: std::string ComputeFingerprint() const override;
int32_t list_size_;};
/// \brief Concrete type class for struct dataclass ARROW_EXPORT StructType : public NestedType { public: static constexpr Type::type type_id = Type::STRUCT;
static constexpr const char* type_name() { return "struct"; }
explicit StructType(const FieldVector& fields);
~StructType() override;
DataTypeLayout layout() const override { return DataTypeLayout({DataTypeLayout::Bitmap()}); }
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "struct"; }
/// Returns null if name not found std::shared_ptr<Field> GetFieldByName(const std::string& name) const;
/// Return all fields having this name FieldVector GetAllFieldsByName(const std::string& name) const;
/// Returns -1 if name not found or if there are multiple fields having the /// same name int GetFieldIndex(const std::string& name) const;
/// \brief Return the indices of all fields having this name in sorted order std::vector<int> GetAllFieldIndices(const std::string& name) const;
/// \brief Create a new StructType with field added at given index Result<std::shared_ptr<StructType>> AddField(int i, const std::shared_ptr<Field>& field) const; /// \brief Create a new StructType by removing the field at given index Result<std::shared_ptr<StructType>> RemoveField(int i) const; /// \brief Create a new StructType by changing the field at given index Result<std::shared_ptr<StructType>> SetField(int i, const std::shared_ptr<Field>& field) const;
private: std::string ComputeFingerprint() const override;
class Impl; std::unique_ptr<Impl> impl_;};
/// \brief Base type class for union dataclass ARROW_EXPORT UnionType : public NestedType { public: static constexpr int8_t kMaxTypeCode = 127; static constexpr int kInvalidChildId = -1;
static Result<std::shared_ptr<DataType>> Make( const FieldVector& fields, const std::vector<int8_t>& type_codes, UnionMode::type mode = UnionMode::SPARSE) { if (mode == UnionMode::SPARSE) { return sparse_union(fields, type_codes); } else { return dense_union(fields, type_codes); } }
DataTypeLayout layout() const override;
std::string ToString(bool show_metadata = false) const override;
/// The array of logical type ids. /// /// For example, the first type in the union might be denoted by the id 5 /// (instead of 0). const std::vector<int8_t>& type_codes() const { return type_codes_; }
/// An array mapping logical type ids to physical child ids. const std::vector<int>& child_ids() const { return child_ids_; }
uint8_t max_type_code() const;
UnionMode::type mode() const;
protected: UnionType(FieldVector fields, std::vector<int8_t> type_codes, Type::type id);
static Status ValidateParameters(const FieldVector& fields, const std::vector<int8_t>& type_codes, UnionMode::type mode);
private: std::string ComputeFingerprint() const override;
std::vector<int8_t> type_codes_; std::vector<int> child_ids_;};
/// \brief Concrete type class for sparse union data////// A sparse union is a nested type where each logical value is taken from/// a single child. A buffer of 8-bit type ids indicates which child/// a given logical value is to be taken from.////// In a sparse union, each child array should have the same length as the/// union array, regardless of the actual number of union values that/// refer to it.////// Note that, unlike most other types, unions don't have a top-level validity bitmap.class ARROW_EXPORT SparseUnionType : public UnionType { public: static constexpr Type::type type_id = Type::SPARSE_UNION;
static constexpr const char* type_name() { return "sparse_union"; }
SparseUnionType(FieldVector fields, std::vector<int8_t> type_codes);
// A constructor variant that validates input parameters static Result<std::shared_ptr<DataType>> Make(FieldVector fields, std::vector<int8_t> type_codes);
std::string name() const override { return "sparse_union"; }};
/// \brief Concrete type class for dense union data////// A dense union is a nested type where each logical value is taken from/// a single child, at a specific offset. A buffer of 8-bit type ids/// indicates which child a given logical value is to be taken from,/// and a buffer of 32-bit offsets indicates at which physical position/// in the given child array the logical value is to be taken from.////// Unlike a sparse union, a dense union allows encoding only the child array/// values which are actually referred to by the union array. This is/// counterbalanced by the additional footprint of the offsets buffer, and/// the additional indirection cost when looking up values.////// Note that, unlike most other types, unions don't have a top-level validity bitmap.class ARROW_EXPORT DenseUnionType : public UnionType { public: static constexpr Type::type type_id = Type::DENSE_UNION;
static constexpr const char* type_name() { return "dense_union"; }
DenseUnionType(FieldVector fields, std::vector<int8_t> type_codes);
// A constructor variant that validates input parameters static Result<std::shared_ptr<DataType>> Make(FieldVector fields, std::vector<int8_t> type_codes);
std::string name() const override { return "dense_union"; }};
/// \brief Type class for run-end encoded dataclass ARROW_EXPORT RunEndEncodedType : public NestedType { public: static constexpr Type::type type_id = Type::RUN_END_ENCODED;
static constexpr const char* type_name() { return "run_end_encoded"; }
explicit RunEndEncodedType(std::shared_ptr<DataType> run_end_type, std::shared_ptr<DataType> value_type); ~RunEndEncodedType() override;
DataTypeLayout layout() const override { // A lot of existing code expects at least one buffer return DataTypeLayout({DataTypeLayout::AlwaysNull()}); }
const std::shared_ptr<DataType>& run_end_type() const { return fields()[0]->type(); } const std::shared_ptr<DataType>& value_type() const { return fields()[1]->type(); }
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "run_end_encoded"; }
static bool RunEndTypeValid(const DataType& run_end_type);
private: std::string ComputeFingerprint() const override;};
/// @}
// ----------------------------------------------------------------------// Date and time types
/// \addtogroup temporal-datatypes////// @{
/// \brief Base type for all date and time typesclass ARROW_EXPORT TemporalType : public FixedWidthType { public: using FixedWidthType::FixedWidthType; // This is only for preventing defining this class in each // translation unit to avoid one-definition-rule violation. ~TemporalType() override;
DataTypeLayout layout() const override { return DataTypeLayout( {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(bit_width() / 8)}); }};
/// \brief Base type class for date dataclass ARROW_EXPORT DateType : public TemporalType { public: virtual DateUnit unit() const = 0;
protected: explicit DateType(Type::type type_id);};
/// Concrete type class for 32-bit date data (as number of days since UNIX epoch)class ARROW_EXPORT Date32Type : public DateType { public: static constexpr Type::type type_id = Type::DATE32; static constexpr DateUnit UNIT = DateUnit::DAY; using c_type = int32_t; using PhysicalType = Int32Type;
static constexpr const char* type_name() { return "date32"; }
Date32Type();
int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "date32"; } DateUnit unit() const override { return UNIT; }
protected: std::string ComputeFingerprint() const override;};
/// Concrete type class for 64-bit date data (as number of milliseconds since UNIX epoch)class ARROW_EXPORT Date64Type : public DateType { public: static constexpr Type::type type_id = Type::DATE64; static constexpr DateUnit UNIT = DateUnit::MILLI; using c_type = int64_t; using PhysicalType = Int64Type;
static constexpr const char* type_name() { return "date64"; }
Date64Type();
int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "date64"; } DateUnit unit() const override { return UNIT; }
protected: std::string ComputeFingerprint() const override;};
ARROW_EXPORTstd::ostream& operator<<(std::ostream& os, TimeUnit::type unit);
/// Base type class for time dataclass ARROW_EXPORT TimeType : public TemporalType, public ParametricType { public: TimeUnit::type unit() const { return unit_; }
protected: TimeType(Type::type type_id, TimeUnit::type unit); std::string ComputeFingerprint() const override;
TimeUnit::type unit_;};
/// Concrete type class for 32-bit time data (as number of seconds or milliseconds/// since midnight)class ARROW_EXPORT Time32Type : public TimeType { public: static constexpr Type::type type_id = Type::TIME32; using c_type = int32_t; using PhysicalType = Int32Type;
static constexpr const char* type_name() { return "time32"; }
int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
explicit Time32Type(TimeUnit::type unit = TimeUnit::MILLI);
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "time32"; }};
/// Concrete type class for 64-bit time data (as number of microseconds or nanoseconds/// since midnight)class ARROW_EXPORT Time64Type : public TimeType { public: static constexpr Type::type type_id = Type::TIME64; using c_type = int64_t; using PhysicalType = Int64Type;
static constexpr const char* type_name() { return "time64"; }
int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
explicit Time64Type(TimeUnit::type unit = TimeUnit::NANO);
std::string ToString(bool show_metadata = false) const override;
std::string name() const override { return "time64"; }};
/// \brief Concrete type class for datetime data (as number of seconds, milliseconds,/// microseconds or nanoseconds since UNIX epoch)////// If supplied, the timezone string should take either the form (i) "Area/Location",/// with values drawn from the names in the IANA Time Zone Database (such as/// "Europe/Zurich"); or (ii) "(+|-)HH:MM" indicating an absolute offset from GMT/// (such as "-08:00"). To indicate a native UTC timestamp, one of the strings "UTC",/// "Etc/UTC" or "+00:00" should be used.////// If any non-empty string is supplied as the timezone for a TimestampType, then the/// Arrow field containing that timestamp type (and by extension the column associated/// with such a field) is considered "timezone-aware". The integer arrays that comprise/// a timezone-aware column must contain UTC normalized datetime values, regardless of/// the contents of their timezone string. More precisely, (i) the producer of a/// timezone-aware column must populate its constituent arrays with valid UTC values/// (performing offset conversions from non-UTC values if necessary); and (ii) the/// consumer of a timezone-aware column may assume that the column's values are directly/// comparable (that is, with no offset adjustment required) to the values of any other/// timezone-aware column or to any other valid UTC datetime value (provided all values/// are expressed in the same units).////// If a TimestampType is constructed without a timezone (or, equivalently, if the/// timezone supplied is an empty string) then the resulting Arrow field (column) is/// considered "timezone-naive". The producer of a timezone-naive column may populate/// its constituent integer arrays with datetime values from any timezone; the consumer/// of a timezone-naive column should make no assumptions about the interoperability or/// comparability of the values of such a column with those of any other timestamp/// column or datetime value.////// If a timezone-aware field contains a recognized timezone, its values may be/// localized to that locale upon display; the values of timezone-naive fields must/// always be displayed "as is", with no localization performed on them.class ARROW_EXPORT TimestampType : public TemporalType, public ParametricType { public: using Unit = TimeUnit;
static constexpr Type::type type_id = Type::TIMESTAMP; using c_type = int64_t; using PhysicalType = Int64Type;
static constexpr const char* type_name() { return "timestamp"; }
int bit_width() const override { return static_cast<int>(sizeof(int64_t) * CHAR_BIT); }
explicit TimestampType(TimeUnit::type unit = TimeUnit::MILLI) : TemporalType(Type::TIMESTAMP), unit_(unit) {}
explicit TimestampType(TimeUnit::type unit, const std::string& timezone) : TemporalType(Type::TIMESTAMP), unit_(unit), timezone_(timezone) {}
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "timestamp"; }
TimeUnit::type unit() const { return unit_; } const std::string& timezone() const { return timezone_; }
protected: std::string ComputeFingerprint() const override;
private: TimeUnit::type unit_; std::string timezone_;};
// Base class for the different kinds of calendar intervals.class ARROW_EXPORT IntervalType : public TemporalType, public ParametricType { public: enum type { MONTHS, DAY_TIME, MONTH_DAY_NANO };
virtual type interval_type() const = 0;
protected: explicit IntervalType(Type::type subtype) : TemporalType(subtype) {} std::string ComputeFingerprint() const override;};
/// \brief Represents a number of months.////// Type representing a number of months. Corresponds to YearMonth type/// in Schema.fbs (years are defined as 12 months).class ARROW_EXPORT MonthIntervalType : public IntervalType { public: static constexpr Type::type type_id = Type::INTERVAL_MONTHS; using c_type = int32_t; using PhysicalType = Int32Type;
static constexpr const char* type_name() { return "month_interval"; }
IntervalType::type interval_type() const override { return IntervalType::MONTHS; }
int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
MonthIntervalType() : IntervalType(type_id) {}
std::string ToString(bool ARROW_ARG_UNUSED(show_metadata) = false) const override { return name(); } std::string name() const override { return "month_interval"; }};
/// \brief Represents a number of days and milliseconds (fraction of day).class ARROW_EXPORT DayTimeIntervalType : public IntervalType { public: struct DayMilliseconds { int32_t days = 0; int32_t milliseconds = 0; constexpr DayMilliseconds() = default; constexpr DayMilliseconds(int32_t days, int32_t milliseconds) : days(days), milliseconds(milliseconds) {} bool operator==(DayMilliseconds other) const { return this->days == other.days && this->milliseconds == other.milliseconds; } bool operator!=(DayMilliseconds other) const { return !(*this == other); } bool operator<(DayMilliseconds other) const { return this->days < other.days || this->milliseconds < other.milliseconds; } }; using c_type = DayMilliseconds; using PhysicalType = DayTimeIntervalType;
static_assert(sizeof(DayMilliseconds) == 8, "DayMilliseconds struct assumed to be of size 8 bytes"); static constexpr Type::type type_id = Type::INTERVAL_DAY_TIME;
static constexpr const char* type_name() { return "day_time_interval"; }
IntervalType::type interval_type() const override { return IntervalType::DAY_TIME; }
DayTimeIntervalType() : IntervalType(type_id) {}
int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
std::string ToString(bool ARROW_ARG_UNUSED(show_metadata) = false) const override { return name(); } std::string name() const override { return "day_time_interval"; }};
ARROW_EXPORTstd::ostream& operator<<(std::ostream& os, DayTimeIntervalType::DayMilliseconds interval);
/// \brief Represents a number of months, days and nanoseconds between/// two dates.////// All fields are independent from one another.class ARROW_EXPORT MonthDayNanoIntervalType : public IntervalType { public: struct MonthDayNanos { int32_t months; int32_t days; int64_t nanoseconds; bool operator==(MonthDayNanos other) const { return this->months == other.months && this->days == other.days && this->nanoseconds == other.nanoseconds; } bool operator!=(MonthDayNanos other) const { return !(*this == other); } }; using c_type = MonthDayNanos; using PhysicalType = MonthDayNanoIntervalType;
static_assert(sizeof(MonthDayNanos) == 16, "MonthDayNanos struct assumed to be of size 16 bytes"); static constexpr Type::type type_id = Type::INTERVAL_MONTH_DAY_NANO;
static constexpr const char* type_name() { return "month_day_nano_interval"; }
IntervalType::type interval_type() const override { return IntervalType::MONTH_DAY_NANO; }
MonthDayNanoIntervalType() : IntervalType(type_id) {}
int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
std::string ToString(bool ARROW_ARG_UNUSED(show_metadata) = false) const override { return name(); } std::string name() const override { return "month_day_nano_interval"; }};
ARROW_EXPORTstd::ostream& operator<<(std::ostream& os, MonthDayNanoIntervalType::MonthDayNanos interval);
/// \brief Represents an elapsed time without any relation to a calendar artifact.class ARROW_EXPORT DurationType : public TemporalType, public ParametricType { public: using Unit = TimeUnit;
static constexpr Type::type type_id = Type::DURATION; using c_type = int64_t; using PhysicalType = Int64Type;
static constexpr const char* type_name() { return "duration"; }
int bit_width() const override { return static_cast<int>(sizeof(int64_t) * CHAR_BIT); }
explicit DurationType(TimeUnit::type unit = TimeUnit::MILLI) : TemporalType(Type::DURATION), unit_(unit) {}
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "duration"; }
TimeUnit::type unit() const { return unit_; }
protected: std::string ComputeFingerprint() const override;
private: TimeUnit::type unit_;};
/// @}
// ----------------------------------------------------------------------// Dictionary type (for representing categorical or dictionary-encoded// in memory)
/// \brief Dictionary-encoded value type with data-dependent/// dictionary. Indices are represented by any integer types.class ARROW_EXPORT DictionaryType : public FixedWidthType { public: static constexpr Type::type type_id = Type::DICTIONARY;
static constexpr const char* type_name() { return "dictionary"; }
DictionaryType(const std::shared_ptr<DataType>& index_type, const std::shared_ptr<DataType>& value_type, bool ordered = false);
// A constructor variant that validates its input parameters static Result<std::shared_ptr<DataType>> Make( const std::shared_ptr<DataType>& index_type, const std::shared_ptr<DataType>& value_type, bool ordered = false);
std::string ToString(bool show_metadata = false) const override; std::string name() const override { return "dictionary"; }
int bit_width() const override;
DataTypeLayout layout() const override;
const std::shared_ptr<DataType>& index_type() const { return index_type_; } const std::shared_ptr<DataType>& value_type() const { return value_type_; }
bool ordered() const { return ordered_; }
protected: static Status ValidateParameters(const DataType& index_type, const DataType& value_type);
std::string ComputeFingerprint() const override;
// Must be an integer type (not currently checked) std::shared_ptr<DataType> index_type_; std::shared_ptr<DataType> value_type_; bool ordered_;};
// ----------------------------------------------------------------------// FieldRef
/// \class FieldPath////// Represents a path to a nested field using indices of child fields./// For example, given indices {5, 9, 3} the field would be retrieved with/// schema->field(5)->type()->field(9)->type()->field(3)////// Attempting to retrieve a child field using a FieldPath which is not valid for/// a given schema will raise an error. Invalid FieldPaths include:/// - an index is out of range/// - the path is empty (note: a default constructed FieldPath will be empty)////// FieldPaths provide a number of accessors for drilling down to potentially nested/// children. They are overloaded for convenience to support Schema (returns a field),/// DataType (returns a child field), Field (returns a child field of this field's type)/// Array (returns a child array), RecordBatch (returns a column).class ARROW_EXPORT FieldPath { public: FieldPath() = default;
FieldPath(std::vector<int> indices) // NOLINT runtime/explicit : indices_(std::move(indices)) {}
FieldPath(std::initializer_list<int> indices) // NOLINT runtime/explicit : indices_(std::move(indices)) {}
std::string ToString() const;
size_t hash() const; struct Hash { size_t operator()(const FieldPath& path) const { return path.hash(); } };
bool empty() const { return indices_.empty(); } bool operator==(const FieldPath& other) const { return indices() == other.indices(); } bool operator!=(const FieldPath& other) const { return indices() != other.indices(); }
const std::vector<int>& indices() const { return indices_; } int operator[](size_t i) const { return indices_[i]; } std::vector<int>::const_iterator begin() const { return indices_.begin(); } std::vector<int>::const_iterator end() const { return indices_.end(); }
/// \brief Retrieve the referenced child Field from a Schema, Field, or DataType Result<std::shared_ptr<Field>> Get(const Schema& schema) const; Result<std::shared_ptr<Field>> Get(const Field& field) const; Result<std::shared_ptr<Field>> Get(const DataType& type) const; Result<std::shared_ptr<Field>> Get(const FieldVector& fields) const;
static Result<std::shared_ptr<Schema>> GetAll(const Schema& schema, const std::vector<FieldPath>& paths);
/// \brief Retrieve the referenced column from a RecordBatch or Table Result<std::shared_ptr<Array>> Get(const RecordBatch& batch) const; Result<std::shared_ptr<ChunkedArray>> Get(const Table& table) const;
/// \brief Retrieve the referenced child from an Array or ArrayData Result<std::shared_ptr<Array>> Get(const Array& array) const; Result<std::shared_ptr<ArrayData>> Get(const ArrayData& data) const;
/// \brief Retrieve the referenced child from a ChunkedArray Result<std::shared_ptr<ChunkedArray>> Get(const ChunkedArray& chunked_array) const;
/// \brief Retrieve the referenced child/column from an Array, ArrayData, ChunkedArray, /// RecordBatch, or Table /// /// Unlike `FieldPath::Get`, these variants are not zero-copy and the retrieved child's /// null bitmap is ANDed with its ancestors' Result<std::shared_ptr<Array>> GetFlattened(const Array& array, MemoryPool* pool = NULLPTR) const; Result<std::shared_ptr<ArrayData>> GetFlattened(const ArrayData& data, MemoryPool* pool = NULLPTR) const; Result<std::shared_ptr<ChunkedArray>> GetFlattened(const ChunkedArray& chunked_array, MemoryPool* pool = NULLPTR) const; Result<std::shared_ptr<Array>> GetFlattened(const RecordBatch& batch, MemoryPool* pool = NULLPTR) const; Result<std::shared_ptr<ChunkedArray>> GetFlattened(const Table& table, MemoryPool* pool = NULLPTR) const;
private: std::vector<int> indices_;};
/// \class FieldRef/// \brief Descriptor of a (potentially nested) field within a schema.////// Unlike FieldPath (which exclusively uses indices of child fields), FieldRef may/// reference a field by name. It is intended to replace parameters like `int field_index`/// and `const std::string& field_name`; it can be implicitly constructed from either a/// field index or a name.////// Nested fields can be referenced as well. Given/// schema({field("a", struct_({field("n", null())})), field("b", int32())})////// the following all indicate the nested field named "n":/// FieldRef ref1(0, 0);/// FieldRef ref2("a", 0);/// FieldRef ref3("a", "n");/// FieldRef ref4(0, "n");/// ARROW_ASSIGN_OR_RAISE(FieldRef ref5,/// FieldRef::FromDotPath(".a[0]"));////// FieldPaths matching a FieldRef are retrieved using the member function FindAll./// Multiple matches are possible because field names may be duplicated within a schema./// For example:/// Schema a_is_ambiguous({field("a", int32()), field("a", float32())});/// auto matches = FieldRef("a").FindAll(a_is_ambiguous);/// assert(matches.size() == 2);/// assert(matches[0].Get(a_is_ambiguous)->Equals(a_is_ambiguous.field(0)));/// assert(matches[1].Get(a_is_ambiguous)->Equals(a_is_ambiguous.field(1)));////// Convenience accessors are available which raise a helpful error if the field is not/// found or ambiguous, and for immediately calling FieldPath::Get to retrieve any/// matching children:/// auto maybe_match = FieldRef("struct", "field_i32").FindOneOrNone(schema);/// auto maybe_column = FieldRef("struct", "field_i32").GetOne(some_table);class ARROW_EXPORT FieldRef : public util::EqualityComparable<FieldRef> { public: FieldRef() = default;
/// Construct a FieldRef using a string of indices. The reference will be retrieved as: /// schema.fields[self.indices[0]].type.fields[self.indices[1]] ... /// /// Empty indices are not valid. FieldRef(FieldPath indices); // NOLINT runtime/explicit
/// Construct a by-name FieldRef. Multiple fields may match a by-name FieldRef: /// [f for f in schema.fields where f.name == self.name] FieldRef(std::string name) : impl_(std::move(name)) {} // NOLINT runtime/explicit FieldRef(const char* name) : impl_(std::string(name)) {} // NOLINT runtime/explicit
/// Equivalent to a single index string of indices. FieldRef(int index) : impl_(FieldPath({index})) {} // NOLINT runtime/explicit
/// Construct a nested FieldRef. explicit FieldRef(std::vector<FieldRef> refs) { Flatten(std::move(refs)); }
/// Convenience constructor for nested FieldRefs: each argument will be used to /// construct a FieldRef template <typename A0, typename A1, typename... A> FieldRef(A0&& a0, A1&& a1, A&&... a) { Flatten({// cpplint thinks the following are constructor decls FieldRef(std::forward<A0>(a0)), // NOLINT runtime/explicit FieldRef(std::forward<A1>(a1)), // NOLINT runtime/explicit FieldRef(std::forward<A>(a))...}); // NOLINT runtime/explicit }
/// Parse a dot path into a FieldRef. /// /// dot_path = '.' name /// | '[' digit+ ']' /// | dot_path+ /// /// Examples: /// ".alpha" => FieldRef("alpha") /// "[2]" => FieldRef(2) /// ".beta[3]" => FieldRef("beta", 3) /// "[5].gamma.delta[7]" => FieldRef(5, "gamma", "delta", 7) /// ".hello world" => FieldRef("hello world") /// R"(.\[y\]\\tho\.\)" => FieldRef(R"([y]\tho.\)") /// /// Note: When parsing a name, a '\' preceding any other character will be dropped from /// the resulting name. Therefore if a name must contain the characters '.', '\', or '[' /// those must be escaped with a preceding '\'. static Result<FieldRef> FromDotPath(const std::string& dot_path); std::string ToDotPath() const;
bool Equals(const FieldRef& other) const { return impl_ == other.impl_; }
std::string ToString() const;
size_t hash() const; struct Hash { size_t operator()(const FieldRef& ref) const { return ref.hash(); } };
explicit operator bool() const { return Equals(FieldPath{}); } bool operator!() const { return !Equals(FieldPath{}); }
bool IsFieldPath() const { return std::holds_alternative<FieldPath>(impl_); } bool IsName() const { return std::holds_alternative<std::string>(impl_); } bool IsNested() const { if (IsName()) return false; if (IsFieldPath()) return std::get<FieldPath>(impl_).indices().size() > 1; return true; }
/// \brief Return true if this ref is a name or a nested sequence of only names /// /// Useful for determining if iteration is possible without recursion or inner loops bool IsNameSequence() const { if (IsName()) return true; if (const auto* nested = nested_refs()) { for (const auto& ref : *nested) { if (!ref.IsName()) return false; } return !nested->empty(); } return false; }
const FieldPath* field_path() const { return IsFieldPath() ? &std::get<FieldPath>(impl_) : NULLPTR; } const std::string* name() const { return IsName() ? &std::get<std::string>(impl_) : NULLPTR; } const std::vector<FieldRef>* nested_refs() const { return std::holds_alternative<std::vector<FieldRef>>(impl_) ? &std::get<std::vector<FieldRef>>(impl_) : NULLPTR; }
/// \brief Retrieve FieldPath of every child field which matches this FieldRef. std::vector<FieldPath> FindAll(const Schema& schema) const; std::vector<FieldPath> FindAll(const Field& field) const; std::vector<FieldPath> FindAll(const DataType& type) const; std::vector<FieldPath> FindAll(const FieldVector& fields) const;
/// \brief Convenience function which applies FindAll to arg's type or schema. std::vector<FieldPath> FindAll(const ArrayData& array) const; std::vector<FieldPath> FindAll(const Array& array) const; std::vector<FieldPath> FindAll(const ChunkedArray& chunked_array) const; std::vector<FieldPath> FindAll(const RecordBatch& batch) const; std::vector<FieldPath> FindAll(const Table& table) const;
/// \brief Convenience function: raise an error if matches is empty. template <typename T> Status CheckNonEmpty(const std::vector<FieldPath>& matches, const T& root) const { if (matches.empty()) { return Status::Invalid("No match for ", ToString(), " in ", root.ToString()); } return Status::OK(); }
/// \brief Convenience function: raise an error if matches contains multiple FieldPaths. template <typename T> Status CheckNonMultiple(const std::vector<FieldPath>& matches, const T& root) const { if (matches.size() > 1) { return Status::Invalid("Multiple matches for ", ToString(), " in ", root.ToString()); } return Status::OK(); }
/// \brief Retrieve FieldPath of a single child field which matches this /// FieldRef. Emit an error if none or multiple match. template <typename T> Result<FieldPath> FindOne(const T& root) const { auto matches = FindAll(root); ARROW_RETURN_NOT_OK(CheckNonEmpty(matches, root)); ARROW_RETURN_NOT_OK(CheckNonMultiple(matches, root)); return std::move(matches[0]); }
/// \brief Retrieve FieldPath of a single child field which matches this /// FieldRef. Emit an error if multiple match. An empty (invalid) FieldPath /// will be returned if none match. template <typename T> Result<FieldPath> FindOneOrNone(const T& root) const { auto matches = FindAll(root); ARROW_RETURN_NOT_OK(CheckNonMultiple(matches, root)); if (matches.empty()) { return FieldPath(); } return std::move(matches[0]); }
template <typename T> using GetType = decltype(std::declval<FieldPath>().Get(std::declval<T>()).ValueOrDie());
/// \brief Get all children matching this FieldRef. template <typename T> std::vector<GetType<T>> GetAll(const T& root) const { std::vector<GetType<T>> out; for (const auto& match : FindAll(root)) { out.push_back(match.Get(root).ValueOrDie()); } return out; } /// \brief Get all children matching this FieldRef. /// /// Unlike `FieldRef::GetAll`, this variant is not zero-copy and the retrieved /// children's null bitmaps are ANDed with their ancestors' template <typename T> Result<std::vector<GetType<T>>> GetAllFlattened(const T& root, MemoryPool* pool = NULLPTR) const { std::vector<GetType<T>> out; for (const auto& match : FindAll(root)) { ARROW_ASSIGN_OR_RAISE(auto child, match.GetFlattened(root, pool)); out.push_back(std::move(child)); } return out; }
/// \brief Get the single child matching this FieldRef. /// Emit an error if none or multiple match. template <typename T> Result<GetType<T>> GetOne(const T& root) const { ARROW_ASSIGN_OR_RAISE(auto match, FindOne(root)); return match.Get(root).ValueOrDie(); } /// \brief Get the single child matching this FieldRef. /// /// Unlike `FieldRef::GetOne`, this variant is not zero-copy and the retrieved /// child's null bitmap is ANDed with its ancestors' template <typename T> Result<GetType<T>> GetOneFlattened(const T& root, MemoryPool* pool = NULLPTR) const { ARROW_ASSIGN_OR_RAISE(auto match, FindOne(root)); return match.GetFlattened(root, pool); }
/// \brief Get the single child matching this FieldRef. /// Return nullptr if none match, emit an error if multiple match. template <typename T> Result<GetType<T>> GetOneOrNone(const T& root) const { ARROW_ASSIGN_OR_RAISE(auto match, FindOneOrNone(root)); if (match.empty()) { return static_cast<GetType<T>>(NULLPTR); } return match.Get(root).ValueOrDie(); } /// \brief Get the single child matching this FieldRef. /// /// Return nullptr if none match, emit an error if multiple match. /// Unlike `FieldRef::GetOneOrNone`, this variant is not zero-copy and the /// retrieved child's null bitmap is ANDed with its ancestors' template <typename T> Result<GetType<T>> GetOneOrNoneFlattened(const T& root, MemoryPool* pool = NULLPTR) const { ARROW_ASSIGN_OR_RAISE(auto match, FindOneOrNone(root)); if (match.empty()) { return static_cast<GetType<T>>(NULLPTR); } return match.GetFlattened(root, pool); }
private: void Flatten(std::vector<FieldRef> children);
std::variant<FieldPath, std::string, std::vector<FieldRef>> impl_;};
ARROW_EXPORT void PrintTo(const FieldRef& ref, std::ostream* os);
ARROW_EXPORTstd::ostream& operator<<(std::ostream& os, const FieldRef&);
// ----------------------------------------------------------------------// Schema
enum class Endianness { Little = 0, Big = 1,#if ARROW_LITTLE_ENDIAN Native = Little#else Native = Big#endif};
/// \class Schema/// \brief Sequence of arrow::Field objects describing the columns of a record/// batch or table data structureclass ARROW_EXPORT Schema : public detail::Fingerprintable, public util::EqualityComparable<Schema>, public util::ToStringOstreamable<Schema> { public: explicit Schema(FieldVector fields, Endianness endianness, std::shared_ptr<const KeyValueMetadata> metadata = NULLPTR);
explicit Schema(FieldVector fields, std::shared_ptr<const KeyValueMetadata> metadata = NULLPTR);
Schema(const Schema&);
~Schema() override;
/// Returns true if all of the schema fields are equal bool Equals(const Schema& other, bool check_metadata = false) const; bool Equals(const std::shared_ptr<Schema>& other, bool check_metadata = false) const;
/// \brief Set endianness in the schema /// /// \return new Schema std::shared_ptr<Schema> WithEndianness(Endianness endianness) const;
/// \brief Return endianness in the schema Endianness endianness() const;
/// \brief Indicate if endianness is equal to platform-native endianness bool is_native_endian() const;
/// \brief Return the number of fields (columns) in the schema int num_fields() const;
/// Return the ith schema element. Does not boundscheck const std::shared_ptr<Field>& field(int i) const;
const FieldVector& fields() const;
std::vector<std::string> field_names() const;
/// Returns null if name not found std::shared_ptr<Field> GetFieldByName(const std::string& name) const;
/// \brief Return the indices of all fields having this name in sorted order FieldVector GetAllFieldsByName(const std::string& name) const;
/// Returns -1 if name not found int GetFieldIndex(const std::string& name) const;
/// Return the indices of all fields having this name std::vector<int> GetAllFieldIndices(const std::string& name) const;
/// Indicate if field named `name` can be found unambiguously in the schema. Status CanReferenceFieldByName(const std::string& name) const;
/// Indicate if fields named `names` can be found unambiguously in the schema. Status CanReferenceFieldsByNames(const std::vector<std::string>& names) const;
/// \brief The custom key-value metadata, if any /// /// \return metadata may be null const std::shared_ptr<const KeyValueMetadata>& metadata() const;
/// \brief Render a string representation of the schema suitable for debugging /// \param[in] show_metadata when true, if KeyValueMetadata is non-empty, /// print keys and values in the output std::string ToString(bool show_metadata = false) const;
Result<std::shared_ptr<Schema>> AddField(int i, const std::shared_ptr<Field>& field) const; Result<std::shared_ptr<Schema>> RemoveField(int i) const; Result<std::shared_ptr<Schema>> SetField(int i, const std::shared_ptr<Field>& field) const;
/// \brief Replace field names with new names /// /// \param[in] names new names /// \return new Schema Result<std::shared_ptr<Schema>> WithNames(const std::vector<std::string>& names) const;
/// \brief Replace key-value metadata with new metadata /// /// \param[in] metadata new KeyValueMetadata /// \return new Schema std::shared_ptr<Schema> WithMetadata( const std::shared_ptr<const KeyValueMetadata>& metadata) const;
/// \brief Return copy of Schema without the KeyValueMetadata std::shared_ptr<Schema> RemoveMetadata() const;
/// \brief Indicate that the Schema has non-empty KevValueMetadata bool HasMetadata() const;
/// \brief Indicate that the Schema has distinct field names. bool HasDistinctFieldNames() const;
protected: std::string ComputeFingerprint() const override; std::string ComputeMetadataFingerprint() const override;
private: class Impl; std::unique_ptr<Impl> impl_;};
ARROW_EXPORT void PrintTo(const Schema& s, std::ostream* os);
ARROW_EXPORTstd::string EndiannessToString(Endianness endianness);
// ----------------------------------------------------------------------
/// \brief Convenience class to incrementally construct/merge schemas.////// This class amortizes the cost of validating field name conflicts by/// maintaining the mapping. The caller also controls the conflict resolution/// scheme.class ARROW_EXPORT SchemaBuilder { public: // Indicate how field conflict(s) should be resolved when building a schema. A // conflict arise when a field is added to the builder and one or more field(s) // with the same name already exists. enum ConflictPolicy { // Ignore the conflict and append the field. This is the default behavior of the // Schema constructor and the `arrow::schema` factory function. CONFLICT_APPEND = 0, // Keep the existing field and ignore the newer one. CONFLICT_IGNORE, // Replace the existing field with the newer one. CONFLICT_REPLACE, // Merge the fields. The merging behavior can be controlled by `Field::MergeOptions` // specified at construction time. Also see documentation of `Field::MergeWith`. CONFLICT_MERGE, // Refuse the new field and error out. CONFLICT_ERROR };
/// \brief Construct an empty SchemaBuilder /// `field_merge_options` is only effective when `conflict_policy` == `CONFLICT_MERGE`. SchemaBuilder( ConflictPolicy conflict_policy = CONFLICT_APPEND, Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults()); /// \brief Construct a SchemaBuilder from a list of fields /// `field_merge_options` is only effective when `conflict_policy` == `CONFLICT_MERGE`. SchemaBuilder( FieldVector fields, ConflictPolicy conflict_policy = CONFLICT_APPEND, Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults()); /// \brief Construct a SchemaBuilder from a schema, preserving the metadata /// `field_merge_options` is only effective when `conflict_policy` == `CONFLICT_MERGE`. SchemaBuilder( const std::shared_ptr<Schema>& schema, ConflictPolicy conflict_policy = CONFLICT_APPEND, Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults());
/// \brief Return the conflict resolution method. ConflictPolicy policy() const;
/// \brief Set the conflict resolution method. void SetPolicy(ConflictPolicy resolution);
/// \brief Add a field to the constructed schema. /// /// \param[in] field to add to the constructed Schema. /// \return A failure if encountered. Status AddField(const std::shared_ptr<Field>& field);
/// \brief Add multiple fields to the constructed schema. /// /// \param[in] fields to add to the constructed Schema. /// \return The first failure encountered, if any. Status AddFields(const FieldVector& fields);
/// \brief Add fields of a Schema to the constructed Schema. /// /// \param[in] schema to take fields to add to the constructed Schema. /// \return The first failure encountered, if any. Status AddSchema(const std::shared_ptr<Schema>& schema);
/// \brief Add fields of multiple Schemas to the constructed Schema. /// /// \param[in] schemas to take fields to add to the constructed Schema. /// \return The first failure encountered, if any. Status AddSchemas(const std::vector<std::shared_ptr<Schema>>& schemas);
Status AddMetadata(const KeyValueMetadata& metadata);
/// \brief Return the constructed Schema. /// /// The builder internal state is not affected by invoking this method, i.e. /// a single builder can yield multiple incrementally constructed schemas. /// /// \return the constructed schema. Result<std::shared_ptr<Schema>> Finish() const;
/// \brief Merge schemas in a unified schema according to policy. static Result<std::shared_ptr<Schema>> Merge( const std::vector<std::shared_ptr<Schema>>& schemas, ConflictPolicy policy = CONFLICT_MERGE);
/// \brief Indicate if schemas are compatible to merge according to policy. static Status AreCompatible(const std::vector<std::shared_ptr<Schema>>& schemas, ConflictPolicy policy = CONFLICT_MERGE);
/// \brief Reset internal state with an empty schema (and metadata). void Reset();
~SchemaBuilder();
private: class Impl; std::unique_ptr<Impl> impl_;
Status AppendField(const std::shared_ptr<Field>& field);};
/// \brief Unifies schemas by merging fields by name.////// The behavior of field merging can be controlled via `Field::MergeOptions`.////// The resulting schema will contain the union of fields from all schemas./// Fields with the same name will be merged. See `Field::MergeOptions`./// - They are expected to be mergeable under provided `field_merge_options`./// - The unified field will inherit the metadata from the schema where/// that field is first defined./// - The first N fields in the schema will be ordered the same as the/// N fields in the first schema./// The resulting schema will inherit its metadata from the first input schema./// Returns an error if:/// - Any input schema contains fields with duplicate names./// - Fields of the same name are not mergeable.ARROW_EXPORTResult<std::shared_ptr<Schema>> UnifySchemas( const std::vector<std::shared_ptr<Schema>>& schemas, Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults());
namespace internal {
constexpr bool may_have_validity_bitmap(Type::type id) { switch (id) { case Type::NA: case Type::DENSE_UNION: case Type::SPARSE_UNION: case Type::RUN_END_ENCODED: return false; default: return true; }}
ARROW_DEPRECATED("Deprecated in 17.0.0. Use may_have_validity_bitmap() instead.")constexpr bool HasValidityBitmap(Type::type id) { return may_have_validity_bitmap(id); }
ARROW_EXPORTstd::string ToString(Type::type id);
ARROW_EXPORTstd::string ToTypeName(Type::type id);
ARROW_EXPORTstd::string ToString(TimeUnit::type unit);
} // namespace internal
// Helpers to get instances of data types based on general categories
/// \brief Signed integer typesARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& SignedIntTypes();/// \brief Unsigned integer typesARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& UnsignedIntTypes();/// \brief Signed and unsigned integer typesARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& IntTypes();/// \brief Floating point typesARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& FloatingPointTypes();/// \brief Number types without boolean - integer and floating point typesARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& NumericTypes();/// \brief Binary and string-like types (except fixed-size binary)ARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& BaseBinaryTypes();/// \brief Binary and large-binary typesARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& BinaryTypes();/// \brief String and large-string typesARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& StringTypes();/// \brief Temporal types including date, time and timestamps for each unitARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& TemporalTypes();/// \brief Interval typesARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& IntervalTypes();/// \brief Duration types for each unitARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& DurationTypes();/// \brief Numeric, base binary, date, boolean and null typesARROW_EXPORTconst std::vector<std::shared_ptr<DataType>>& PrimitiveTypes();
} // namespace arrow1234567891011121314151617181920// 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.
#pragma once
#include "parquet/exception.h"1234567891011121314151617181920212223242526272829303132333435// 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.
#pragma once
// Column reader API#include "parquet/column_reader.h"#include "parquet/column_scanner.h"#include "parquet/exception.h"#include "parquet/file_reader.h"#include "parquet/metadata.h"#include "parquet/platform.h"#include "parquet/printer.h"#include "parquet/properties.h"#include "parquet/statistics.h"
// Schemas#include "parquet/api/schema.h"
// IO#include "parquet/api/io.h"123456789101112131415161718192021// 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.
#pragma once
// Schemas#include "parquet/schema.h"12345678910111213141516171819202122232425// 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.
#pragma once
#include "parquet/api/io.h"#include "parquet/api/schema.h"#include "parquet/column_writer.h"#include "parquet/exception.h"#include "parquet/file_writer.h"#include "parquet/statistics.h"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379// 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.
#pragma once
#include <cstdint>// N.B. we don't include async_generator.h as it's relatively heavy#include <functional>#include <memory>#include <vector>
#include "parquet/file_reader.h"#include "parquet/platform.h"#include "parquet/properties.h"
namespace arrow {
class ChunkedArray;class KeyValueMetadata;class RecordBatchReader;struct Scalar;class Schema;class Table;class RecordBatch;
} // namespace arrow
namespace parquet {
class FileMetaData;class SchemaDescriptor;
namespace arrow {
class ColumnChunkReader;class ColumnReader;struct SchemaManifest;class RowGroupReader;
/// \brief Arrow read adapter class for deserializing Parquet files as Arrow row batches.////// This interfaces caters for different use cases and thus provides different/// interfaces. In its most simplistic form, we cater for a user that wants to/// read the whole Parquet at once with the `FileReader::ReadTable` method.////// More advanced users that also want to implement parallelism on top of each/// single Parquet files should do this on the RowGroup level. For this, they can/// call `FileReader::RowGroup(i)->ReadTable` to receive only the specified/// RowGroup as a table.////// In the most advanced situation, where a consumer wants to independently read/// RowGroups in parallel and consume each column individually, they can call/// `FileReader::RowGroup(i)->Column(j)->Read` and receive an `arrow::Column`/// instance.////// Finally, one can also get a stream of record batches using/// `FileReader::GetRecordBatchReader()`. This can internally decode columns/// in parallel if use_threads was enabled in the ArrowReaderProperties.////// The parquet format supports an optional integer field_id which can be assigned/// to a field. Arrow will convert these field IDs to a metadata key named/// PARQUET:field_id on the appropriate field.// TODO(wesm): nested data does not always make sense with this user// interface unless you are only reading a single leaf node from a branch of// a table. For example://// repeated group data {// optional group record {// optional int32 val1;// optional byte_array val2;// optional bool val3;// }// optional int32 val4;// }//// In the Parquet file, there are 4 leaf nodes://// * data.record.val1// * data.record.val2// * data.record.val3// * data.val4//// When materializing this data in an Arrow array, we would have://// data: list<struct<// record: struct<// val1: int32,// val2: string (= list<uint8>),// val3: bool,// >,// val4: int32// >>//// However, in the Parquet format, each leaf node has its own repetition and// definition levels describing the structure of the intermediate nodes in// this array structure. Thus, we will need to scan the leaf data for a group// of leaf nodes part of the same type tree to create a single result Arrow// nested array structure.//// This is additionally complicated "chunky" repeated fields or very large byte// arraysclass PARQUET_EXPORT FileReader { public: /// Factory function to create a FileReader from a ParquetFileReader and properties static ::arrow::Status Make(::arrow::MemoryPool* pool, std::unique_ptr<ParquetFileReader> reader, const ArrowReaderProperties& properties, std::unique_ptr<FileReader>* out);
/// Factory function to create a FileReader from a ParquetFileReader static ::arrow::Status Make(::arrow::MemoryPool* pool, std::unique_ptr<ParquetFileReader> reader, std::unique_ptr<FileReader>* out);
// Since the distribution of columns amongst a Parquet file's row groups may // be uneven (the number of values in each column chunk can be different), we // provide a column-oriented read interface. The ColumnReader hides the // details of paging through the file's row groups and yielding // fully-materialized arrow::Array instances // // Returns error status if the column of interest is not flat. // The indicated column index is relative to the schema virtual ::arrow::Status GetColumn(int i, std::unique_ptr<ColumnReader>* out) = 0;
/// \brief Return arrow schema for all the columns. virtual ::arrow::Status GetSchema(std::shared_ptr<::arrow::Schema>* out) = 0;
/// \brief Read column as a whole into a chunked array. /// /// The index i refers the index of the top level schema field, which may /// be nested or flat - e.g. /// /// 0 foo.bar /// foo.bar.baz /// foo.qux /// 1 foo2 /// 2 foo3 /// /// i=0 will read the entire foo struct, i=1 the foo2 primitive column etc virtual ::arrow::Status ReadColumn(int i, std::shared_ptr<::arrow::ChunkedArray>* out) = 0;
/// \brief Return a RecordBatchReader of all row groups and columns. virtual ::arrow::Status GetRecordBatchReader( std::unique_ptr<::arrow::RecordBatchReader>* out) = 0;
/// \brief Return a RecordBatchReader of row groups selected from row_group_indices. /// /// Note that the ordering in row_group_indices matters. FileReaders must outlive /// their RecordBatchReaders. /// /// \returns error Status if row_group_indices contains an invalid index virtual ::arrow::Status GetRecordBatchReader( const std::vector<int>& row_group_indices, std::unique_ptr<::arrow::RecordBatchReader>* out) = 0;
/// \brief Return a RecordBatchReader of row groups selected from /// row_group_indices, whose columns are selected by column_indices. /// /// Note that the ordering in row_group_indices and column_indices /// matter. FileReaders must outlive their RecordBatchReaders. /// /// \returns error Status if either row_group_indices or column_indices /// contains an invalid index virtual ::arrow::Status GetRecordBatchReader( const std::vector<int>& row_group_indices, const std::vector<int>& column_indices, std::unique_ptr<::arrow::RecordBatchReader>* out) = 0;
/// \brief Return a RecordBatchReader of row groups selected from /// row_group_indices, whose columns are selected by column_indices. /// /// Note that the ordering in row_group_indices and column_indices /// matter. FileReaders must outlive their RecordBatchReaders. /// /// \param row_group_indices which row groups to read (order determines read order). /// \param column_indices which columns to read (order determines output schema). /// \param[out] out record batch stream from parquet data. /// /// \returns error Status if either row_group_indices or column_indices /// contains an invalid index ::arrow::Status GetRecordBatchReader(const std::vector<int>& row_group_indices, const std::vector<int>& column_indices, std::shared_ptr<::arrow::RecordBatchReader>* out); ::arrow::Status GetRecordBatchReader(const std::vector<int>& row_group_indices, std::shared_ptr<::arrow::RecordBatchReader>* out); ::arrow::Status GetRecordBatchReader(std::shared_ptr<::arrow::RecordBatchReader>* out);
/// \brief Return a generator of record batches. /// /// The FileReader must outlive the generator, so this requires that you pass in a /// shared_ptr. /// /// \returns error Result if either row_group_indices or column_indices contains an /// invalid index virtual ::arrow::Result< std::function<::arrow::Future<std::shared_ptr<::arrow::RecordBatch>>()>> GetRecordBatchGenerator(std::shared_ptr<FileReader> reader, const std::vector<int> row_group_indices, const std::vector<int> column_indices, ::arrow::internal::Executor* cpu_executor = NULLPTR, int64_t rows_to_readahead = 0) = 0;
/// Read all columns into a Table virtual ::arrow::Status ReadTable(std::shared_ptr<::arrow::Table>* out) = 0;
/// \brief Read the given columns into a Table /// /// The indicated column indices are relative to the internal representation /// of the parquet table. For instance : /// 0 foo.bar /// foo.bar.baz 0 /// foo.bar.baz2 1 /// foo.qux 2 /// 1 foo2 3 /// 2 foo3 4 /// /// i=0 will read foo.bar.baz, i=1 will read only foo.bar.baz2 and so on. /// Only leaf fields have indices; foo itself doesn't have an index. /// To get the index for a particular leaf field, one can use /// manifest().schema_fields to get the top level fields, and then walk the /// tree to identify the relevant leaf fields and access its column_index. /// To get the total number of leaf fields, use FileMetadata.num_columns(). virtual ::arrow::Status ReadTable(const std::vector<int>& column_indices, std::shared_ptr<::arrow::Table>* out) = 0;
virtual ::arrow::Status ReadRowGroup(int i, const std::vector<int>& column_indices, std::shared_ptr<::arrow::Table>* out) = 0;
virtual ::arrow::Status ReadRowGroup(int i, std::shared_ptr<::arrow::Table>* out) = 0;
virtual ::arrow::Status ReadRowGroups(const std::vector<int>& row_groups, const std::vector<int>& column_indices, std::shared_ptr<::arrow::Table>* out) = 0;
virtual ::arrow::Status ReadRowGroups(const std::vector<int>& row_groups, std::shared_ptr<::arrow::Table>* out) = 0;
/// \brief Scan file contents with one thread, return number of rows virtual ::arrow::Status ScanContents(std::vector<int> columns, const int32_t column_batch_size, int64_t* num_rows) = 0;
/// \brief Return a reader for the RowGroup, this object must not outlive the /// FileReader. virtual std::shared_ptr<RowGroupReader> RowGroup(int row_group_index) = 0;
/// \brief The number of row groups in the file virtual int num_row_groups() const = 0;
virtual ParquetFileReader* parquet_reader() const = 0;
/// Set whether to use multiple threads during reads of multiple columns. /// By default only one thread is used. virtual void set_use_threads(bool use_threads) = 0;
/// Set number of records to read per batch for the RecordBatchReader. virtual void set_batch_size(int64_t batch_size) = 0;
virtual const ArrowReaderProperties& properties() const = 0;
virtual const SchemaManifest& manifest() const = 0;
virtual ~FileReader() = default;};
class RowGroupReader { public: virtual ~RowGroupReader() = default; virtual std::shared_ptr<ColumnChunkReader> Column(int column_index) = 0; virtual ::arrow::Status ReadTable(const std::vector<int>& column_indices, std::shared_ptr<::arrow::Table>* out) = 0; virtual ::arrow::Status ReadTable(std::shared_ptr<::arrow::Table>* out) = 0;
private: struct Iterator;};
class ColumnChunkReader { public: virtual ~ColumnChunkReader() = default; virtual ::arrow::Status Read(std::shared_ptr<::arrow::ChunkedArray>* out) = 0;};
// At this point, the column reader is a stream iterator. It only knows how to// read the next batch of values for a particular column from the file until it// runs out.//// We also do not expose any internal Parquet details, such as row groups. This// might change in the future.class PARQUET_EXPORT ColumnReader { public: virtual ~ColumnReader() = default;
// Scan the next array of the indicated size. The actual size of the // returned array may be less than the passed size depending how much data is // available in the file. // // When all the data in the file has been exhausted, the result is set to // nullptr. // // Returns Status::OK on a successful read, including if you have exhausted // the data available in the file. virtual ::arrow::Status NextBatch(int64_t batch_size, std::shared_ptr<::arrow::ChunkedArray>* out) = 0;};
/// \brief Experimental helper class for bindings (like Python) that struggle/// either with std::move or C++ exceptionsclass PARQUET_EXPORT FileReaderBuilder { public: FileReaderBuilder();
/// Create FileReaderBuilder from Arrow file and optional properties / metadata ::arrow::Status Open(std::shared_ptr<::arrow::io::RandomAccessFile> file, const ReaderProperties& properties = default_reader_properties(), std::shared_ptr<FileMetaData> metadata = NULLPTR);
/// Create FileReaderBuilder from file path and optional properties / metadata ::arrow::Status OpenFile(const std::string& path, bool memory_map = false, const ReaderProperties& props = default_reader_properties(), std::shared_ptr<FileMetaData> metadata = NULLPTR);
ParquetFileReader* raw_reader() { return raw_reader_.get(); }
/// Set Arrow MemoryPool for memory allocation FileReaderBuilder* memory_pool(::arrow::MemoryPool* pool); /// Set Arrow reader properties FileReaderBuilder* properties(const ArrowReaderProperties& arg_properties); /// Build FileReader instance ::arrow::Status Build(std::unique_ptr<FileReader>* out); ::arrow::Result<std::unique_ptr<FileReader>> Build();
private: ::arrow::MemoryPool* pool_; ArrowReaderProperties properties_; std::unique_ptr<ParquetFileReader> raw_reader_;};
/// \defgroup parquet-arrow-reader-factories Factory functions for Parquet Arrow readers////// @{
/// \brief Build FileReader from Arrow file and MemoryPool////// Advanced settings are supported through the FileReaderBuilder class.PARQUET_EXPORT::arrow::Status OpenFile(std::shared_ptr<::arrow::io::RandomAccessFile>, ::arrow::MemoryPool* allocator, std::unique_ptr<FileReader>* reader);
/// @}
PARQUET_EXPORT::arrow::Status StatisticsAsScalars(const Statistics& Statistics, std::shared_ptr<::arrow::Scalar>* min, std::shared_ptr<::arrow::Scalar>* max);
namespace internal {
PARQUET_EXPORT::arrow::Status FuzzReader(const uint8_t* data, int64_t size);
} // namespace internal} // namespace arrow} // namespace parquet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184// 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.
#pragma once
#include <cassert>#include <memory>#include <unordered_map>#include <unordered_set>#include <vector>
#include "arrow/result.h"#include "arrow/status.h"#include "arrow/type.h"#include "arrow/type_fwd.h"
#include "parquet/level_conversion.h"#include "parquet/platform.h"#include "parquet/schema.h"
namespace parquet {
class ArrowReaderProperties;class ArrowWriterProperties;class WriterProperties;
namespace arrow {
/// \defgroup arrow-to-parquet-schema-conversion Functions to convert an Arrow/// schema into a Parquet schema.////// @{
PARQUET_EXPORT::arrow::Status FieldToNode(const std::shared_ptr<::arrow::Field>& field, const WriterProperties& properties, const ArrowWriterProperties& arrow_properties, schema::NodePtr* out);
PARQUET_EXPORT::arrow::Status ToParquetSchema(const ::arrow::Schema* arrow_schema, const WriterProperties& properties, const ArrowWriterProperties& arrow_properties, std::shared_ptr<SchemaDescriptor>* out);
PARQUET_EXPORT::arrow::Status ToParquetSchema(const ::arrow::Schema* arrow_schema, const WriterProperties& properties, std::shared_ptr<SchemaDescriptor>* out);
/// @}
/// \defgroup parquet-to-arrow-schema-conversion Functions to convert a Parquet/// schema into an Arrow schema.////// @{
PARQUET_EXPORT::arrow::Status FromParquetSchema( const SchemaDescriptor* parquet_schema, const ArrowReaderProperties& properties, const std::shared_ptr<const ::arrow::KeyValueMetadata>& key_value_metadata, std::shared_ptr<::arrow::Schema>* out);
PARQUET_EXPORT::arrow::Status FromParquetSchema(const SchemaDescriptor* parquet_schema, const ArrowReaderProperties& properties, std::shared_ptr<::arrow::Schema>* out);
PARQUET_EXPORT::arrow::Status FromParquetSchema(const SchemaDescriptor* parquet_schema, std::shared_ptr<::arrow::Schema>* out);
/// @}
/// \brief Bridge between an arrow::Field and parquet column indices.struct PARQUET_EXPORT SchemaField { std::shared_ptr<::arrow::Field> field; std::vector<SchemaField> children;
// Only set for leaf nodes int column_index = -1;
parquet::internal::LevelInfo level_info;
bool is_leaf() const { return column_index != -1; }};
/// \brief Bridge between a parquet Schema and an arrow Schema.////// Expose parquet columns as a tree structure. Useful traverse and link/// between arrow's Schema and parquet's Schema.struct PARQUET_EXPORT SchemaManifest { static ::arrow::Status Make( const SchemaDescriptor* schema, const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata, const ArrowReaderProperties& properties, SchemaManifest* manifest);
const SchemaDescriptor* descr; std::shared_ptr<::arrow::Schema> origin_schema; std::shared_ptr<const ::arrow::KeyValueMetadata> schema_metadata; std::vector<SchemaField> schema_fields;
std::unordered_map<int, const SchemaField*> column_index_to_field; std::unordered_map<const SchemaField*, const SchemaField*> child_to_parent;
::arrow::Status GetColumnField(int column_index, const SchemaField** out) const { auto it = column_index_to_field.find(column_index); if (it == column_index_to_field.end()) { return ::arrow::Status::KeyError("Column index ", column_index, " not found in schema manifest, may be malformed"); } *out = it->second; return ::arrow::Status::OK(); }
const SchemaField* GetParent(const SchemaField* field) const { // Returns nullptr also if not found auto it = child_to_parent.find(field); if (it == child_to_parent.end()) { return NULLPTR; } return it->second; }
/// Coalesce a list of field indices (relative to the equivalent arrow::Schema) which /// correspond to the column root (first node below the parquet schema's root group) of /// each leaf referenced in column_indices. /// /// For example, for leaves `a.b.c`, `a.b.d.e`, and `i.j.k` (column_indices=[0,1,3]) /// the roots are `a` and `i` (return=[0,2]). /// /// root /// -- a <------ /// -- -- b | | /// -- -- -- c | /// -- -- -- d | /// -- -- -- -- e /// -- f /// -- -- g /// -- -- -- h /// -- i <--- /// -- -- j | /// -- -- -- k ::arrow::Result<std::vector<int>> GetFieldIndices( const std::vector<int>& column_indices) const { const schema::GroupNode* group = descr->group_node(); std::unordered_set<int> already_added;
std::vector<int> out; for (int column_idx : column_indices) { if (column_idx < 0 || column_idx >= descr->num_columns()) { return ::arrow::Status::IndexError("Column index ", column_idx, " is not valid"); }
auto field_node = descr->GetColumnRoot(column_idx); auto field_idx = group->FieldIndex(*field_node); if (field_idx == -1) { return ::arrow::Status::IndexError("Column index ", column_idx, " is not valid"); }
if (already_added.insert(field_idx).second) { out.push_back(field_idx); } } return out; }};
} // namespace arrow} // namespace parquet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524// 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.
#pragma once
#include <limits>#include <memory>#include <random>#include <string>#include <utility>#include <vector>
#include "arrow/array.h"#include "arrow/array/builder_binary.h"#include "arrow/array/builder_decimal.h"#include "arrow/array/builder_primitive.h"#include "arrow/testing/gtest_util.h"#include "arrow/testing/random.h"#include "arrow/type_fwd.h"#include "arrow/type_traits.h"#include "arrow/util/decimal.h"#include "arrow/util/float16.h"#include "parquet/column_reader.h"#include "parquet/test_util.h"
namespace parquet {
using internal::RecordReader;
namespace arrow {
using ::arrow::Array;using ::arrow::ChunkedArray;using ::arrow::Status;
template <int32_t PRECISION>struct DecimalWithPrecisionAndScale { static_assert(PRECISION >= 1 && PRECISION <= 38, "Invalid precision value");
using type = ::arrow::Decimal128Type; static constexpr ::arrow::Type::type type_id = ::arrow::Decimal128Type::type_id; static constexpr int32_t precision = PRECISION; static constexpr int32_t scale = PRECISION - 1;};
template <int32_t PRECISION>struct Decimal256WithPrecisionAndScale { static_assert(PRECISION >= 1 && PRECISION <= 76, "Invalid precision value");
using type = ::arrow::Decimal256Type; static constexpr ::arrow::Type::type type_id = ::arrow::Decimal256Type::type_id; static constexpr int32_t precision = PRECISION; static constexpr int32_t scale = PRECISION - 1;};
template <class ArrowType>::arrow::enable_if_floating_point<ArrowType, Status> NonNullArray( size_t size, std::shared_ptr<Array>* out) { using c_type = typename ArrowType::c_type; std::vector<c_type> values; if constexpr (::arrow::is_half_float_type<ArrowType>::value) { values.resize(size); test::random_float16_numbers(static_cast<int>(size), 0, ::arrow::util::Float16(0.0f), ::arrow::util::Float16(1.0f), values.data()); } else { ::arrow::random_real(size, 0, static_cast<c_type>(0), static_cast<c_type>(1), &values); } ::arrow::NumericBuilder<ArrowType> builder; RETURN_NOT_OK(builder.AppendValues(values.data(), values.size())); return builder.Finish(out);}
template <class ArrowType>::arrow::enable_if_integer<ArrowType, Status> NonNullArray(size_t size, std::shared_ptr<Array>* out) { std::vector<typename ArrowType::c_type> values; ::arrow::randint(size, 0, 64, &values);
// Passing data type so this will work with TimestampType too ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(), ::arrow::default_memory_pool()); RETURN_NOT_OK(builder.AppendValues(values.data(), values.size())); return builder.Finish(out);}
template <class ArrowType>::arrow::enable_if_date<ArrowType, Status> NonNullArray(size_t size, std::shared_ptr<Array>* out) { std::vector<typename ArrowType::c_type> values; ::arrow::randint(size, 0, 24, &values); for (size_t i = 0; i < size; i++) { values[i] *= 86400000; }
// Passing data type so this will work with TimestampType too ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(), ::arrow::default_memory_pool()); RETURN_NOT_OK(builder.AppendValues(values.data(), values.size())); return builder.Finish(out);}
template <class ArrowType>::arrow::enable_if_base_binary<ArrowType, Status> NonNullArray( size_t size, std::shared_ptr<Array>* out) { using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType; BuilderType builder; for (size_t i = 0; i < size; i++) { RETURN_NOT_OK(builder.Append("test-string")); } return builder.Finish(out);}
template <typename ArrowType>::arrow::enable_if_fixed_size_binary<ArrowType, Status> NonNullArray( size_t size, std::shared_ptr<Array>* out) { using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType; // set byte_width to the length of "fixed": 5 // todo: find a way to generate test data with more diversity. BuilderType builder(::arrow::fixed_size_binary(5)); for (size_t i = 0; i < size; i++) { RETURN_NOT_OK(builder.Append("fixed")); } return builder.Finish(out);}
template <int32_t byte_width>static void random_decimals(int64_t n, uint32_t seed, int32_t precision, uint8_t* out) { auto gen = ::arrow::random::RandomArrayGenerator(seed); std::shared_ptr<Array> decimals; if constexpr (byte_width == 16) { decimals = gen.Decimal128(::arrow::decimal128(precision, 0), n); } else { decimals = gen.Decimal256(::arrow::decimal256(precision, 0), n); } std::memcpy(out, decimals->data()->GetValues<uint8_t>(1, 0), byte_width * n);}
template <typename ArrowType, int32_t precision = ArrowType::precision>::arrow::enable_if_t< std::is_same<ArrowType, DecimalWithPrecisionAndScale<precision>>::value, Status>NonNullArray(size_t size, std::shared_ptr<Array>* out) { constexpr int32_t kDecimalPrecision = precision; constexpr int32_t kDecimalScale = DecimalWithPrecisionAndScale<precision>::scale;
const auto type = ::arrow::decimal(kDecimalPrecision, kDecimalScale); ::arrow::Decimal128Builder builder(type); const int32_t byte_width = static_cast<const ::arrow::Decimal128Type&>(*type).byte_width();
constexpr int32_t seed = 0;
ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width)); random_decimals<::arrow::Decimal128Type::kByteWidth>(size, seed, kDecimalPrecision, out_buf->mutable_data());
RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size)); return builder.Finish(out);}
template <typename ArrowType, int32_t precision = ArrowType::precision>::arrow::enable_if_t< std::is_same<ArrowType, Decimal256WithPrecisionAndScale<precision>>::value, Status>NonNullArray(size_t size, std::shared_ptr<Array>* out) { constexpr int32_t kDecimalPrecision = precision; constexpr int32_t kDecimalScale = Decimal256WithPrecisionAndScale<precision>::scale;
const auto type = ::arrow::decimal256(kDecimalPrecision, kDecimalScale); ::arrow::Decimal256Builder builder(type); const int32_t byte_width = static_cast<const ::arrow::Decimal256Type&>(*type).byte_width();
constexpr int32_t seed = 0;
ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width)); random_decimals<::arrow::Decimal256Type::kByteWidth>(size, seed, kDecimalPrecision, out_buf->mutable_data());
RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size)); return builder.Finish(out);}
template <class ArrowType>::arrow::enable_if_boolean<ArrowType, Status> NonNullArray(size_t size, std::shared_ptr<Array>* out) { std::vector<uint8_t> values; ::arrow::randint(size, 0, 1, &values); ::arrow::BooleanBuilder builder; RETURN_NOT_OK(builder.AppendValues(values.data(), values.size())); return builder.Finish(out);}
// This helper function only supports (size/2) nulls.template <typename ArrowType>::arrow::enable_if_floating_point<ArrowType, Status> NullableArray( size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<Array>* out) { using c_type = typename ArrowType::c_type; std::vector<c_type> values; if constexpr (::arrow::is_half_float_type<ArrowType>::value) { values.resize(size); test::random_float16_numbers(static_cast<int>(size), 0, ::arrow::util::Float16(-1e4f), ::arrow::util::Float16(1e4f), values.data()); } else { ::arrow::random_real(size, seed, static_cast<c_type>(-1e10), static_cast<c_type>(1e10), &values); } std::vector<uint8_t> valid_bytes(size, 1);
for (size_t i = 0; i < num_nulls; i++) { valid_bytes[i * 2] = 0; }
::arrow::NumericBuilder<ArrowType> builder; RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data())); return builder.Finish(out);}
// This helper function only supports (size/2) nulls.template <typename ArrowType>::arrow::enable_if_integer<ArrowType, Status> NullableArray(size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<Array>* out) { std::vector<typename ArrowType::c_type> values;
// Seed is random in Arrow right now (void)seed; ::arrow::randint(size, 0, 64, &values); std::vector<uint8_t> valid_bytes(size, 1);
for (size_t i = 0; i < num_nulls; i++) { valid_bytes[i * 2] = 0; }
// Passing data type so this will work with TimestampType too ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(), ::arrow::default_memory_pool()); RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data())); return builder.Finish(out);}
template <typename ArrowType>::arrow::enable_if_date<ArrowType, Status> NullableArray(size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<Array>* out) { std::vector<typename ArrowType::c_type> values;
// Seed is random in Arrow right now (void)seed; ::arrow::randint(size, 0, 24, &values); for (size_t i = 0; i < size; i++) { values[i] *= 86400000; } std::vector<uint8_t> valid_bytes(size, 1);
for (size_t i = 0; i < num_nulls; i++) { valid_bytes[i * 2] = 0; }
// Passing data type so this will work with TimestampType too ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(), ::arrow::default_memory_pool()); RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data())); return builder.Finish(out);}
// This helper function only supports (size/2) nulls yet.template <typename ArrowType>::arrow::enable_if_base_binary<ArrowType, Status> NullableArray( size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<::arrow::Array>* out) { std::vector<uint8_t> valid_bytes(size, 1);
for (size_t i = 0; i < num_nulls; i++) { valid_bytes[i * 2] = 0; }
using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType; BuilderType builder;
const int kBufferSize = 10; uint8_t buffer[kBufferSize]; for (size_t i = 0; i < size; i++) { if (!valid_bytes[i]) { RETURN_NOT_OK(builder.AppendNull()); } else { ::arrow::random_bytes(kBufferSize, seed + static_cast<uint32_t>(i), buffer); if (ArrowType::is_utf8) { // Trivially force data to be valid UTF8 by making it all ASCII for (auto& byte : buffer) { byte &= 0x7f; } } RETURN_NOT_OK(builder.Append(buffer, kBufferSize)); } } return builder.Finish(out);}
// This helper function only supports (size/2) nulls yet,// same as NullableArray<String|Binary>(..)template <typename ArrowType>::arrow::enable_if_fixed_size_binary<ArrowType, Status> NullableArray( size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<::arrow::Array>* out) { std::vector<uint8_t> valid_bytes(size, 1);
for (size_t i = 0; i < num_nulls; i++) { valid_bytes[i * 2] = 0; }
using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType; const int byte_width = 10; BuilderType builder(::arrow::fixed_size_binary(byte_width));
const int kBufferSize = byte_width; uint8_t buffer[kBufferSize]; for (size_t i = 0; i < size; i++) { if (!valid_bytes[i]) { RETURN_NOT_OK(builder.AppendNull()); } else { ::arrow::random_bytes(kBufferSize, seed + static_cast<uint32_t>(i), buffer); RETURN_NOT_OK(builder.Append(buffer)); } } return builder.Finish(out);}
template <typename ArrowType, int32_t precision = ArrowType::precision>::arrow::enable_if_t< std::is_same<ArrowType, DecimalWithPrecisionAndScale<precision>>::value, Status>NullableArray(size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<::arrow::Array>* out) { std::vector<uint8_t> valid_bytes(size, '\1');
for (size_t i = 0; i < num_nulls; ++i) { valid_bytes[i * 2] = '\0'; }
constexpr int32_t kDecimalPrecision = precision; constexpr int32_t kDecimalScale = DecimalWithPrecisionAndScale<precision>::scale; const auto type = ::arrow::decimal(kDecimalPrecision, kDecimalScale); const int32_t byte_width = static_cast<const ::arrow::Decimal128Type&>(*type).byte_width();
ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width));
random_decimals<::arrow::Decimal128Type::kByteWidth>(size, seed, precision, out_buf->mutable_data());
::arrow::Decimal128Builder builder(type); RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size, valid_bytes.data())); return builder.Finish(out);}
template <typename ArrowType, int32_t precision = ArrowType::precision>::arrow::enable_if_t< std::is_same<ArrowType, Decimal256WithPrecisionAndScale<precision>>::value, Status>NullableArray(size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<::arrow::Array>* out) { std::vector<uint8_t> valid_bytes(size, '\1');
for (size_t i = 0; i < num_nulls; ++i) { valid_bytes[i * 2] = '\0'; }
constexpr int32_t kDecimalPrecision = precision; constexpr int32_t kDecimalScale = Decimal256WithPrecisionAndScale<precision>::scale; const auto type = ::arrow::decimal256(kDecimalPrecision, kDecimalScale); const int32_t byte_width = static_cast<const ::arrow::Decimal256Type&>(*type).byte_width();
ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width));
random_decimals<::arrow::Decimal256Type::kByteWidth>(size, seed, precision, out_buf->mutable_data());
::arrow::Decimal256Builder builder(type); RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size, valid_bytes.data())); return builder.Finish(out);}
// This helper function only supports (size/2) nulls yet.template <class ArrowType>::arrow::enable_if_boolean<ArrowType, Status> NullableArray(size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<Array>* out) { std::vector<uint8_t> values;
// Seed is random in Arrow right now (void)seed;
::arrow::randint(size, 0, 1, &values); std::vector<uint8_t> valid_bytes(size, 1);
for (size_t i = 0; i < num_nulls; i++) { valid_bytes[i * 2] = 0; }
::arrow::BooleanBuilder builder; RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data())); return builder.Finish(out);}
/// Wrap an Array into a ListArray by splitting it up into size lists.////// This helper function only supports (size/2) nulls.Status MakeListArray(const std::shared_ptr<Array>& values, int64_t size, int64_t null_count, const std::string& item_name, bool nullable_values, std::shared_ptr<::arrow::ListArray>* out) { // We always include an empty list int64_t non_null_entries = size - null_count - 1; int64_t length_per_entry = values->length() / non_null_entries;
auto offsets = AllocateBuffer(); RETURN_NOT_OK(offsets->Resize((size + 1) * sizeof(int32_t))); int32_t* offsets_ptr = reinterpret_cast<int32_t*>(offsets->mutable_data());
auto null_bitmap = AllocateBuffer(); int64_t bitmap_size = ::arrow::bit_util::BytesForBits(size); RETURN_NOT_OK(null_bitmap->Resize(bitmap_size)); uint8_t* null_bitmap_ptr = null_bitmap->mutable_data(); memset(null_bitmap_ptr, 0, bitmap_size);
int32_t current_offset = 0; for (int64_t i = 0; i < size; i++) { offsets_ptr[i] = current_offset; if (!(((i % 2) == 0) && ((i / 2) < null_count))) { // Non-null list (list with index 1 is always empty). ::arrow::bit_util::SetBit(null_bitmap_ptr, i); if (i != 1) { current_offset += static_cast<int32_t>(length_per_entry); } } } offsets_ptr[size] = static_cast<int32_t>(values->length());
auto value_field = ::arrow::field(item_name, values->type(), nullable_values); *out = std::make_shared<::arrow::ListArray>(::arrow::list(value_field), size, offsets, values, null_bitmap, null_count);
return Status::OK();}
// Make an array containing only empty lists, with a null values arrayStatus MakeEmptyListsArray(int64_t size, std::shared_ptr<Array>* out_array) { // Allocate an offsets buffer containing only zeroes const int64_t offsets_nbytes = (size + 1) * sizeof(int32_t); ARROW_ASSIGN_OR_RAISE(auto offsets_buffer, ::arrow::AllocateBuffer(offsets_nbytes)); memset(offsets_buffer->mutable_data(), 0, offsets_nbytes);
auto value_field = ::arrow::field("item", ::arrow::float64(), false /* nullable_values */); auto list_type = ::arrow::list(value_field);
std::vector<std::shared_ptr<Buffer>> child_buffers = {nullptr /* null bitmap */, nullptr /* values */}; auto child_data = ::arrow::ArrayData::Make(value_field->type(), 0, std::move(child_buffers));
std::vector<std::shared_ptr<Buffer>> buffers = {nullptr /* bitmap */, std::move(offsets_buffer)}; auto array_data = ::arrow::ArrayData::Make(list_type, size, std::move(buffers)); array_data->child_data.push_back(child_data);
*out_array = ::arrow::MakeArray(array_data); return Status::OK();}
std::shared_ptr<::arrow::Table> MakeSimpleTable( const std::shared_ptr<ChunkedArray>& values, bool nullable) { auto schema = ::arrow::schema({::arrow::field("col", values->type(), nullable)}); return ::arrow::Table::Make(schema, {values});}
std::shared_ptr<::arrow::Table> MakeSimpleTable(const std::shared_ptr<Array>& values, bool nullable) { auto carr = std::make_shared<::arrow::ChunkedArray>(values); return MakeSimpleTable(carr, nullable);}
template <typename T>void ExpectArray(T* expected, Array* result) { auto p_array = static_cast<::arrow::PrimitiveArray*>(result); for (int i = 0; i < result->length(); i++) { EXPECT_EQ(expected[i], reinterpret_cast<const T*>(p_array->values()->data())[i]); }}
template <typename ArrowType>void ExpectArrayT(void* expected, Array* result) { ::arrow::PrimitiveArray* p_array = static_cast<::arrow::PrimitiveArray*>(result); for (int64_t i = 0; i < result->length(); i++) { EXPECT_EQ(reinterpret_cast<typename ArrowType::c_type*>(expected)[i], reinterpret_cast<const typename ArrowType::c_type*>( p_array->values()->data())[i]); }}
template <>void ExpectArrayT<::arrow::BooleanType>(void* expected, Array* result) { ::arrow::BooleanBuilder builder; ARROW_EXPECT_OK( builder.AppendValues(reinterpret_cast<uint8_t*>(expected), result->length()));
std::shared_ptr<Array> expected_array; ARROW_EXPECT_OK(builder.Finish(&expected_array)); EXPECT_TRUE(result->Equals(*expected_array));}
} // namespace arrow
} // namespace parquet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190// 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.
#pragma once
#include <cstdint>#include <memory>
#include "parquet/platform.h"#include "parquet/properties.h"
namespace arrow {
class Array;class ChunkedArray;class RecordBatch;class Schema;class Table;
} // namespace arrow
namespace parquet {
class FileMetaData;class ParquetFileWriter;
namespace arrow {
/// \brief Iterative FileWriter class////// For basic usage, can write a Table at a time, creating one or more row/// groups per write call.////// For advanced usage, can write column-by-column: Start a new RowGroup or/// Chunk with NewRowGroup, then write column-by-column the whole column chunk.////// If PARQUET:field_id is present as a metadata key on a field, and the corresponding/// value is a nonnegative integer, then it will be used as the field_id in the parquet/// file.class PARQUET_EXPORT FileWriter { public: static ::arrow::Status Make(MemoryPool* pool, std::unique_ptr<ParquetFileWriter> writer, std::shared_ptr<::arrow::Schema> schema, std::shared_ptr<ArrowWriterProperties> arrow_properties, std::unique_ptr<FileWriter>* out);
/// \brief Try to create an Arrow to Parquet file writer. /// /// \param schema schema of data that will be passed. /// \param pool memory pool to use. /// \param sink output stream to write Parquet data. /// \param properties general Parquet writer properties. /// \param arrow_properties Arrow-specific writer properties. /// /// \since 11.0.0 static ::arrow::Result<std::unique_ptr<FileWriter>> Open( const ::arrow::Schema& schema, MemoryPool* pool, std::shared_ptr<::arrow::io::OutputStream> sink, std::shared_ptr<WriterProperties> properties = default_writer_properties(), std::shared_ptr<ArrowWriterProperties> arrow_properties = default_arrow_writer_properties());
ARROW_DEPRECATED("Deprecated in 11.0.0. Use Result-returning variants instead.") static ::arrow::Status Open(const ::arrow::Schema& schema, MemoryPool* pool, std::shared_ptr<::arrow::io::OutputStream> sink, std::shared_ptr<WriterProperties> properties, std::unique_ptr<FileWriter>* writer); ARROW_DEPRECATED("Deprecated in 11.0.0. Use Result-returning variants instead.") static ::arrow::Status Open(const ::arrow::Schema& schema, MemoryPool* pool, std::shared_ptr<::arrow::io::OutputStream> sink, std::shared_ptr<WriterProperties> properties, std::shared_ptr<ArrowWriterProperties> arrow_properties, std::unique_ptr<FileWriter>* writer);
/// Return the Arrow schema to be written to. virtual std::shared_ptr<::arrow::Schema> schema() const = 0;
/// \brief Write a Table to Parquet. /// /// \param table Arrow table to write. /// \param chunk_size maximum number of rows to write per row group. virtual ::arrow::Status WriteTable( const ::arrow::Table& table, int64_t chunk_size = DEFAULT_MAX_ROW_GROUP_LENGTH) = 0;
/// \brief Start a new row group. /// /// Returns an error if not all columns have been written. /// /// \param chunk_size the number of rows in the next row group. virtual ::arrow::Status NewRowGroup(int64_t chunk_size) = 0;
/// \brief Write ColumnChunk in row group using an array. virtual ::arrow::Status WriteColumnChunk(const ::arrow::Array& data) = 0;
/// \brief Write ColumnChunk in row group using slice of a ChunkedArray virtual ::arrow::Status WriteColumnChunk( const std::shared_ptr<::arrow::ChunkedArray>& data, int64_t offset, int64_t size) = 0;
/// \brief Write ColumnChunk in a row group using a ChunkedArray virtual ::arrow::Status WriteColumnChunk( const std::shared_ptr<::arrow::ChunkedArray>& data) = 0;
/// \brief Start a new buffered row group. /// /// Returns an error if not all columns have been written. virtual ::arrow::Status NewBufferedRowGroup() = 0;
/// \brief Write a RecordBatch into the buffered row group. /// /// Multiple RecordBatches can be written into the same row group /// through this method. /// /// WriterProperties.max_row_group_length() is respected and a new /// row group will be created if the current row group exceeds the /// limit. /// /// Batches get flushed to the output stream once NewBufferedRowGroup() /// or Close() is called. /// /// WARNING: If you are writing multiple files in parallel in the same /// executor, deadlock may occur if ArrowWriterProperties::use_threads /// is set to true to write columns in parallel. Please disable use_threads /// option in this case. virtual ::arrow::Status WriteRecordBatch(const ::arrow::RecordBatch& batch) = 0;
/// \brief Write the footer and close the file. virtual ::arrow::Status Close() = 0; virtual ~FileWriter();
virtual MemoryPool* memory_pool() const = 0; /// \brief Add key-value metadata to the file. /// \param[in] key_value_metadata the metadata to add. /// \note This will overwrite any existing metadata with the same key. /// \return Error if Close() has been called. /// /// WARNING: If `store_schema` is enabled, `ARROW:schema` would be stored /// in the key-value metadata. Overwriting this key would result in /// `store_schema` being unusable during read. virtual ::arrow::Status AddKeyValueMetadata( const std::shared_ptr<const ::arrow::KeyValueMetadata>& key_value_metadata) = 0; /// \brief Return the file metadata, only available after calling Close(). virtual const std::shared_ptr<FileMetaData> metadata() const = 0;};
/// \brief Write Parquet file metadata only to indicated Arrow OutputStreamPARQUET_EXPORT::arrow::Status WriteFileMetaData(const FileMetaData& file_metadata, ::arrow::io::OutputStream* sink);
/// \brief Write metadata-only Parquet file to indicated Arrow OutputStreamPARQUET_EXPORT::arrow::Status WriteMetaDataFile(const FileMetaData& file_metadata, ::arrow::io::OutputStream* sink);
/// \brief Write a Table to Parquet.////// This writes one table in a single shot. To write a Parquet file with/// multiple tables iteratively, see parquet::arrow::FileWriter.////// \param table Table to write./// \param pool memory pool to use./// \param sink output stream to write Parquet data./// \param chunk_size maximum number of rows to write per row group./// \param properties general Parquet writer properties./// \param arrow_properties Arrow-specific writer properties.::arrow::Status PARQUET_EXPORTWriteTable(const ::arrow::Table& table, MemoryPool* pool, std::shared_ptr<::arrow::io::OutputStream> sink, int64_t chunk_size = DEFAULT_MAX_ROW_GROUP_LENGTH, std::shared_ptr<WriterProperties> properties = default_writer_properties(), std::shared_ptr<ArrowWriterProperties> arrow_properties = default_arrow_writer_properties());
} // namespace arrow} // namespace parquet1234567891011121314151617181920212223242526272829303132333435363738394041424344454647// 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.
#pragma once
#include <random>#include <string>#include <vector>
#include "parquet/types.h"
namespace parquet::benchmark {
template <typename T>void GenerateBenchmarkData(uint32_t size, uint32_t seed, T* data, std::vector<uint8_t>* heap, uint32_t data_string_length);
#define _GENERATE_BENCHMARK_DATA_DECL(KLASS) \ template <> \ void GenerateBenchmarkData(uint32_t size, uint32_t seed, KLASS* data, \ std::vector<uint8_t>* heap, uint32_t data_string_length);
_GENERATE_BENCHMARK_DATA_DECL(int32_t)_GENERATE_BENCHMARK_DATA_DECL(int64_t)_GENERATE_BENCHMARK_DATA_DECL(float)_GENERATE_BENCHMARK_DATA_DECL(double)_GENERATE_BENCHMARK_DATA_DECL(ByteArray)_GENERATE_BENCHMARK_DATA_DECL(FLBA)_GENERATE_BENCHMARK_DATA_DECL(Int96)
#undef _GENERATE_BENCHMARK_DATA_DECL
} // namespace parquet::benchmark123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363// 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.
#pragma once
#include <cmath>#include <cstdint>#include <memory>
#include "arrow/util/bit_util.h"#include "arrow/util/logging.h"#include "parquet/hasher.h"#include "parquet/platform.h"#include "parquet/types.h"
namespace parquet {
// A Bloom filter is a compact structure to indicate whether an item is not in a set or// probably in a set. The Bloom filter usually consists of a bit set that represents a// set of elements, a hash strategy and a Bloom filter algorithm.class PARQUET_EXPORT BloomFilter { public: // Maximum Bloom filter size, it sets to HDFS default block size 128MB // This value will be reconsidered when implementing Bloom filter producer. static constexpr uint32_t kMaximumBloomFilterBytes = 128 * 1024 * 1024;
/// Determine whether an element exist in set or not. /// /// @param hash the element to contain. /// @return false if value is definitely not in set, and true means PROBABLY /// in set. virtual bool FindHash(uint64_t hash) const = 0;
/// Insert element to set represented by Bloom filter bitset. /// @param hash the hash of value to insert into Bloom filter. virtual void InsertHash(uint64_t hash) = 0;
/// Insert elements to set represented by Bloom filter bitset. /// @param hashes the hash values to insert into Bloom filter. /// @param num_values the number of hash values to insert. virtual void InsertHashes(const uint64_t* hashes, int num_values) = 0;
/// Write this Bloom filter to an output stream. A Bloom filter structure should /// include bitset length, hash strategy, algorithm, and bitset. /// /// @param sink the output stream to write virtual void WriteTo(ArrowOutputStream* sink) const = 0;
/// Get the number of bytes of bitset virtual uint32_t GetBitsetSize() const = 0;
/// Compute hash for 32 bits value by using its plain encoding result. /// /// @param value the value to hash. /// @return hash result. virtual uint64_t Hash(int32_t value) const = 0;
/// Compute hash for 64 bits value by using its plain encoding result. /// /// @param value the value to hash. /// @return hash result. virtual uint64_t Hash(int64_t value) const = 0;
/// Compute hash for float value by using its plain encoding result. /// /// @param value the value to hash. /// @return hash result. virtual uint64_t Hash(float value) const = 0;
/// Compute hash for double value by using its plain encoding result. /// /// @param value the value to hash. /// @return hash result. virtual uint64_t Hash(double value) const = 0;
/// Compute hash for Int96 value by using its plain encoding result. /// /// @param value the value to hash. /// @return hash result. virtual uint64_t Hash(const Int96* value) const = 0;
/// Compute hash for ByteArray value by using its plain encoding result. /// /// @param value the value to hash. /// @return hash result. virtual uint64_t Hash(const ByteArray* value) const = 0;
/// Compute hash for fixed byte array value by using its plain encoding result. /// /// @param value the value address. /// @param len the value length. /// @return hash result. virtual uint64_t Hash(const FLBA* value, uint32_t len) const = 0;
/// Batch compute hashes for 32 bits values by using its plain encoding result. /// /// @param values values a pointer to the values to hash. /// @param num_values the number of values to hash. /// @param hashes a pointer to the output hash values, its length should be equal to /// num_values. virtual void Hashes(const int32_t* values, int num_values, uint64_t* hashes) const = 0;
/// Batch compute hashes for 64 bits values by using its plain encoding result. /// /// @param values values a pointer to the values to hash. /// @param num_values the number of values to hash. /// @param hashes a pointer to the output hash values, its length should be equal to /// num_values. virtual void Hashes(const int64_t* values, int num_values, uint64_t* hashes) const = 0;
/// Batch compute hashes for float values by using its plain encoding result. /// /// @param values values a pointer to the values to hash. /// @param num_values the number of values to hash. /// @param hashes a pointer to the output hash values, its length should be equal to /// num_values. virtual void Hashes(const float* values, int num_values, uint64_t* hashes) const = 0;
/// Batch compute hashes for double values by using its plain encoding result. /// /// @param values values a pointer to the values to hash. /// @param num_values the number of values to hash. /// @param hashes a pointer to the output hash values, its length should be equal to /// num_values. virtual void Hashes(const double* values, int num_values, uint64_t* hashes) const = 0;
/// Batch compute hashes for Int96 values by using its plain encoding result. /// /// @param values values a pointer to the values to hash. /// @param num_values the number of values to hash. /// @param hashes a pointer to the output hash values, its length should be equal to /// num_values. virtual void Hashes(const Int96* values, int num_values, uint64_t* hashes) const = 0;
/// Batch compute hashes for ByteArray values by using its plain encoding result. /// /// @param values values a pointer to the values to hash. /// @param num_values the number of values to hash. /// @param hashes a pointer to the output hash values, its length should be equal to /// num_values. virtual void Hashes(const ByteArray* values, int num_values, uint64_t* hashes) const = 0;
/// Batch compute hashes for fixed byte array values by using its plain encoding result. /// /// @param values values a pointer to the values to hash. /// @param type_len the value length. /// @param num_values the number of values to hash. /// @param hashes a pointer to the output hash values, its length should be equal to /// num_values. virtual void Hashes(const FLBA* values, uint32_t type_len, int num_values, uint64_t* hashes) const = 0;
virtual ~BloomFilter() = default;
protected: // Hash strategy available for Bloom filter. enum class HashStrategy : uint32_t { XXHASH = 0 };
// Bloom filter algorithm. enum class Algorithm : uint32_t { BLOCK = 0 };
enum class CompressionStrategy : uint32_t { UNCOMPRESSED = 0 };};
/// The BlockSplitBloomFilter is implemented using block-based Bloom filters from/// Putze et al.'s "Cache-,Hash- and Space-Efficient Bloom filters". The basic idea is to/// hash the item to a tiny Bloom filter which size fit a single cache line or smaller.////// This implementation sets 8 bits in each tiny Bloom filter. Each tiny Bloom/// filter is 32 bytes to take advantage of 32-byte SIMD instructions.class PARQUET_EXPORT BlockSplitBloomFilter : public BloomFilter { public: /// The constructor of BlockSplitBloomFilter. It uses XXH64 as hash function. /// /// \param pool memory pool to use. explicit BlockSplitBloomFilter( ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
/// Initialize the BlockSplitBloomFilter. The range of num_bytes should be within /// [kMinimumBloomFilterBytes, kMaximumBloomFilterBytes], it will be /// rounded up/down to lower/upper bound if num_bytes is out of range and also /// will be rounded up to a power of 2. /// /// @param num_bytes The number of bytes to store Bloom filter bitset. void Init(uint32_t num_bytes);
/// Initialize the BlockSplitBloomFilter. It copies the bitset as underlying /// bitset because the given bitset may not satisfy the 32-byte alignment requirement /// which may lead to segfault when performing SIMD instructions. It is the caller's /// responsibility to free the bitset passed in. This is used when reconstructing /// a Bloom filter from a parquet file. /// /// @param bitset The given bitset to initialize the Bloom filter. /// @param num_bytes The number of bytes of given bitset. void Init(const uint8_t* bitset, uint32_t num_bytes);
/// Minimum Bloom filter size, it sets to 32 bytes to fit a tiny Bloom filter. static constexpr uint32_t kMinimumBloomFilterBytes = 32;
/// Calculate optimal size according to the number of distinct values and false /// positive probability. /// /// @param ndv The number of distinct values. /// @param fpp The false positive probability. /// @return it always return a value between kMinimumBloomFilterBytes and /// kMaximumBloomFilterBytes, and the return value is always a power of 2 static uint32_t OptimalNumOfBytes(uint32_t ndv, double fpp) { uint32_t optimal_num_of_bits = OptimalNumOfBits(ndv, fpp); DCHECK(::arrow::bit_util::IsMultipleOf8(optimal_num_of_bits)); return optimal_num_of_bits >> 3; }
/// Calculate optimal size according to the number of distinct values and false /// positive probability. /// /// @param ndv The number of distinct values. /// @param fpp The false positive probability. /// @return it always return a value between kMinimumBloomFilterBytes * 8 and /// kMaximumBloomFilterBytes * 8, and the return value is always a power of 16 static uint32_t OptimalNumOfBits(uint32_t ndv, double fpp) { DCHECK(fpp > 0.0 && fpp < 1.0); const double m = -8.0 * ndv / log(1 - pow(fpp, 1.0 / 8)); uint32_t num_bits;
// Handle overflow. if (m < 0 || m > kMaximumBloomFilterBytes << 3) { num_bits = static_cast<uint32_t>(kMaximumBloomFilterBytes << 3); } else { num_bits = static_cast<uint32_t>(m); }
// Round up to lower bound if (num_bits < kMinimumBloomFilterBytes << 3) { num_bits = kMinimumBloomFilterBytes << 3; }
// Get next power of 2 if bits is not power of 2. if ((num_bits & (num_bits - 1)) != 0) { num_bits = static_cast<uint32_t>(::arrow::bit_util::NextPower2(num_bits)); }
// Round down to upper bound if (num_bits > kMaximumBloomFilterBytes << 3) { num_bits = kMaximumBloomFilterBytes << 3; }
return num_bits; }
bool FindHash(uint64_t hash) const override; void InsertHash(uint64_t hash) override; void InsertHashes(const uint64_t* hashes, int num_values) override; void WriteTo(ArrowOutputStream* sink) const override; uint32_t GetBitsetSize() const override { return num_bytes_; }
uint64_t Hash(int32_t value) const override { return hasher_->Hash(value); } uint64_t Hash(int64_t value) const override { return hasher_->Hash(value); } uint64_t Hash(float value) const override { return hasher_->Hash(value); } uint64_t Hash(double value) const override { return hasher_->Hash(value); } uint64_t Hash(const Int96* value) const override { return hasher_->Hash(value); } uint64_t Hash(const ByteArray* value) const override { return hasher_->Hash(value); } uint64_t Hash(const FLBA* value, uint32_t len) const override { return hasher_->Hash(value, len); }
void Hashes(const int32_t* values, int num_values, uint64_t* hashes) const override { hasher_->Hashes(values, num_values, hashes); } void Hashes(const int64_t* values, int num_values, uint64_t* hashes) const override { hasher_->Hashes(values, num_values, hashes); } void Hashes(const float* values, int num_values, uint64_t* hashes) const override { hasher_->Hashes(values, num_values, hashes); } void Hashes(const double* values, int num_values, uint64_t* hashes) const override { hasher_->Hashes(values, num_values, hashes); } void Hashes(const Int96* values, int num_values, uint64_t* hashes) const override { hasher_->Hashes(values, num_values, hashes); } void Hashes(const ByteArray* values, int num_values, uint64_t* hashes) const override { hasher_->Hashes(values, num_values, hashes); } void Hashes(const FLBA* values, uint32_t type_len, int num_values, uint64_t* hashes) const override { hasher_->Hashes(values, type_len, num_values, hashes); }
uint64_t Hash(const int32_t* value) const { return hasher_->Hash(*value); } uint64_t Hash(const int64_t* value) const { return hasher_->Hash(*value); } uint64_t Hash(const float* value) const { return hasher_->Hash(*value); } uint64_t Hash(const double* value) const { return hasher_->Hash(*value); }
/// Deserialize the Bloom filter from an input stream. It is used when reconstructing /// a Bloom filter from a parquet filter. /// /// @param properties The parquet reader properties. /// @param input_stream The input stream from which to construct the bloom filter. /// @param bloom_filter_length The length of the serialized bloom filter including /// header. /// @return The BlockSplitBloomFilter. static BlockSplitBloomFilter Deserialize( const ReaderProperties& properties, ArrowInputStream* input_stream, std::optional<int64_t> bloom_filter_length = std::nullopt);
private: inline void InsertHashImpl(uint64_t hash);
// Bytes in a tiny Bloom filter block. static constexpr int kBytesPerFilterBlock = 32;
// The number of bits to be set in each tiny Bloom filter static constexpr int kBitsSetPerBlock = 8;
// A mask structure used to set bits in each tiny Bloom filter. struct BlockMask { uint32_t item[kBitsSetPerBlock]; };
// The block-based algorithm needs eight odd SALT values to calculate eight indexes // of bit to set, one bit in each 32-bit word. static constexpr uint32_t SALT[kBitsSetPerBlock] = { 0x47b6137bU, 0x44974d91U, 0x8824ad5bU, 0xa2b7289dU, 0x705495c7U, 0x2df1424bU, 0x9efc4947U, 0x5c6bfb31U};
// Memory pool to allocate aligned buffer for bitset ::arrow::MemoryPool* pool_;
// The underlying buffer of bitset. std::shared_ptr<Buffer> data_;
// The number of bytes of Bloom filter bitset. uint32_t num_bytes_;
// Hash strategy used in this Bloom filter. HashStrategy hash_strategy_;
// Algorithm used in this Bloom filter. Algorithm algorithm_;
// Compression used in this Bloom filter. CompressionStrategy compression_strategy_;
// The hash pointer points to actual hash class used. std::unique_ptr<Hasher> hasher_;};
} // namespace parquet1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768// 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.
#pragma once
#include "arrow/io/interfaces.h"#include "parquet/properties.h"#include "parquet/type_fwd.h"
namespace parquet {
class InternalFileDecryptor;class BloomFilter;
class PARQUET_EXPORT RowGroupBloomFilterReader { public: virtual ~RowGroupBloomFilterReader() = default;
/// \brief Read bloom filter of a column chunk. /// /// \param[in] i column ordinal of the column chunk. /// \returns bloom filter of the column or nullptr if it does not exist. /// \throws ParquetException if the index is out of bound, or read bloom /// filter failed. virtual std::unique_ptr<BloomFilter> GetColumnBloomFilter(int i) = 0;};
/// \brief Interface for reading the bloom filter for a Parquet file.class PARQUET_EXPORT BloomFilterReader { public: virtual ~BloomFilterReader() = default;
/// \brief Create a BloomFilterReader instance. /// \returns a BloomFilterReader instance. /// WARNING: The returned BloomFilterReader references to all the input parameters, so /// it must not outlive all of the input parameters. Usually these input parameters /// come from the same ParquetFileReader object, so it must not outlive the reader /// that creates this BloomFilterReader. static std::unique_ptr<BloomFilterReader> Make( std::shared_ptr<::arrow::io::RandomAccessFile> input, std::shared_ptr<FileMetaData> file_metadata, const ReaderProperties& properties, std::shared_ptr<InternalFileDecryptor> file_decryptor = NULLPTR);
/// \brief Get the bloom filter reader of a specific row group. /// \param[in] i row group ordinal to get bloom filter reader. /// \returns RowGroupBloomFilterReader of the specified row group. A nullptr may or may /// not be returned if the bloom filter for the row group is unavailable. It /// is the caller's responsibility to check the return value of follow-up calls /// to the RowGroupBloomFilterReader. /// \throws ParquetException if the index is out of bound. virtual std::shared_ptr<RowGroupBloomFilterReader> RowGroup(int i) = 0;};
} // namespace parquet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171// 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.
// This module defines an abstract interface for iterating through pages in a// Parquet column chunk within a row group. It could be extended in the future// to iterate through all data pages in all chunks in a file.
#pragma once
#include <cstdint>#include <memory>#include <optional>#include <string>
#include "parquet/statistics.h"#include "parquet/types.h"
namespace parquet {
// TODO: Parallel processing is not yet safe because of memory-ownership// semantics (the PageReader may or may not own the memory referenced by a// page)//// TODO(wesm): In the future Parquet implementations may store the crc code// in format::PageHeader. parquet-mr currently does not, so we also skip it// here, both on the read and write pathclass Page { public: Page(const std::shared_ptr<Buffer>& buffer, PageType::type type) : buffer_(buffer), type_(type) {}
PageType::type type() const { return type_; }
std::shared_ptr<Buffer> buffer() const { return buffer_; }
// @returns: a pointer to the page's data const uint8_t* data() const { return buffer_->data(); }
// @returns: the total size in bytes of the page's data buffer int32_t size() const { return static_cast<int32_t>(buffer_->size()); }
private: std::shared_ptr<Buffer> buffer_; PageType::type type_;};
/// \brief Base type for DataPageV1 and DataPageV2 including common attributesclass DataPage : public Page { public: int32_t num_values() const { return num_values_; } Encoding::type encoding() const { return encoding_; } int64_t uncompressed_size() const { return uncompressed_size_; } const EncodedStatistics& statistics() const { return statistics_; } /// Return the row ordinal within the row group to the first row in the data page. /// Currently it is only present from data pages created by ColumnWriter in order /// to collect page index. std::optional<int64_t> first_row_index() const { return first_row_index_; }
virtual ~DataPage() = default;
protected: DataPage(PageType::type type, const std::shared_ptr<Buffer>& buffer, int32_t num_values, Encoding::type encoding, int64_t uncompressed_size, EncodedStatistics statistics = EncodedStatistics(), std::optional<int64_t> first_row_index = std::nullopt) : Page(buffer, type), num_values_(num_values), encoding_(encoding), uncompressed_size_(uncompressed_size), statistics_(std::move(statistics)), first_row_index_(std::move(first_row_index)) {}
int32_t num_values_; Encoding::type encoding_; int64_t uncompressed_size_; EncodedStatistics statistics_; /// Row ordinal within the row group to the first row in the data page. std::optional<int64_t> first_row_index_;};
class DataPageV1 : public DataPage { public: DataPageV1(const std::shared_ptr<Buffer>& buffer, int32_t num_values, Encoding::type encoding, Encoding::type definition_level_encoding, Encoding::type repetition_level_encoding, int64_t uncompressed_size, EncodedStatistics statistics = EncodedStatistics(), std::optional<int64_t> first_row_index = std::nullopt) : DataPage(PageType::DATA_PAGE, buffer, num_values, encoding, uncompressed_size, std::move(statistics), std::move(first_row_index)), definition_level_encoding_(definition_level_encoding), repetition_level_encoding_(repetition_level_encoding) {}
Encoding::type repetition_level_encoding() const { return repetition_level_encoding_; }
Encoding::type definition_level_encoding() const { return definition_level_encoding_; }
private: Encoding::type definition_level_encoding_; Encoding::type repetition_level_encoding_;};
class DataPageV2 : public DataPage { public: DataPageV2(const std::shared_ptr<Buffer>& buffer, int32_t num_values, int32_t num_nulls, int32_t num_rows, Encoding::type encoding, int32_t definition_levels_byte_length, int32_t repetition_levels_byte_length, int64_t uncompressed_size, bool is_compressed = false, EncodedStatistics statistics = EncodedStatistics(), std::optional<int64_t> first_row_index = std::nullopt) : DataPage(PageType::DATA_PAGE_V2, buffer, num_values, encoding, uncompressed_size, std::move(statistics), std::move(first_row_index)), num_nulls_(num_nulls), num_rows_(num_rows), definition_levels_byte_length_(definition_levels_byte_length), repetition_levels_byte_length_(repetition_levels_byte_length), is_compressed_(is_compressed) {}
int32_t num_nulls() const { return num_nulls_; }
int32_t num_rows() const { return num_rows_; }
int32_t definition_levels_byte_length() const { return definition_levels_byte_length_; }
int32_t repetition_levels_byte_length() const { return repetition_levels_byte_length_; }
bool is_compressed() const { return is_compressed_; }
private: int32_t num_nulls_; int32_t num_rows_; int32_t definition_levels_byte_length_; int32_t repetition_levels_byte_length_; bool is_compressed_;};
class DictionaryPage : public Page { public: DictionaryPage(const std::shared_ptr<Buffer>& buffer, int32_t num_values, Encoding::type encoding, bool is_sorted = false) : Page(buffer, PageType::DICTIONARY_PAGE), num_values_(num_values), encoding_(encoding), is_sorted_(is_sorted) {}
int32_t num_values() const { return num_values_; }
Encoding::type encoding() const { return encoding_; }
bool is_sorted() const { return is_sorted_; }
private: int32_t num_values_; Encoding::type encoding_; bool is_sorted_;};
} // namespace parquet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501// 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.
#pragma once
#include <cstdint>#include <memory>#include <utility>#include <vector>
#include "parquet/exception.h"#include "parquet/level_conversion.h"#include "parquet/metadata.h"#include "parquet/platform.h"#include "parquet/properties.h"#include "parquet/schema.h"#include "parquet/types.h"
namespace arrow {
class Array;class ChunkedArray;
namespace bit_util {class BitReader;} // namespace bit_util
namespace util {class RleDecoder;} // namespace util
} // namespace arrow
namespace parquet {
class Decryptor;class Page;
// 16 MB is the default maximum page header sizestatic constexpr uint32_t kDefaultMaxPageHeaderSize = 16 * 1024 * 1024;
// 16 KB is the default expected page header sizestatic constexpr uint32_t kDefaultPageHeaderSize = 16 * 1024;
// \brief DataPageStats stores encoded statistics and number of values/rows for// a page.struct PARQUET_EXPORT DataPageStats { DataPageStats(const EncodedStatistics* encoded_statistics, int32_t num_values, std::optional<int32_t> num_rows) : encoded_statistics(encoded_statistics), num_values(num_values), num_rows(num_rows) {}
// Encoded statistics extracted from the page header. // Nullptr if there are no statistics in the page header. const EncodedStatistics* encoded_statistics; // Number of values stored in the page. Filled for both V1 and V2 data pages. // For repeated fields, this can be greater than number of rows. For // non-repeated fields, this will be the same as the number of rows. int32_t num_values; // Number of rows stored in the page. std::nullopt if not available. std::optional<int32_t> num_rows;};
class PARQUET_EXPORT LevelDecoder { public: LevelDecoder(); ~LevelDecoder();
// Initialize the LevelDecoder state with new data // and return the number of bytes consumed int SetData(Encoding::type encoding, int16_t max_level, int num_buffered_values, const uint8_t* data, int32_t data_size);
void SetDataV2(int32_t num_bytes, int16_t max_level, int num_buffered_values, const uint8_t* data);
// Decodes a batch of levels into an array and returns the number of levels decoded int Decode(int batch_size, int16_t* levels);
private: int bit_width_; int num_values_remaining_; Encoding::type encoding_; std::unique_ptr<::arrow::util::RleDecoder> rle_decoder_; std::unique_ptr<::arrow::bit_util::BitReader> bit_packed_decoder_; int16_t max_level_;};
struct CryptoContext { CryptoContext(bool start_with_dictionary_page, int16_t rg_ordinal, int16_t col_ordinal, std::shared_ptr<Decryptor> meta, std::shared_ptr<Decryptor> data) : start_decrypt_with_dictionary_page(start_with_dictionary_page), row_group_ordinal(rg_ordinal), column_ordinal(col_ordinal), meta_decryptor(std::move(meta)), data_decryptor(std::move(data)) {} CryptoContext() {}
bool start_decrypt_with_dictionary_page = false; int16_t row_group_ordinal = -1; int16_t column_ordinal = -1; std::shared_ptr<Decryptor> meta_decryptor; std::shared_ptr<Decryptor> data_decryptor;};
// Abstract page iterator interface. This way, we can feed column pages to the// ColumnReader through whatever mechanism we chooseclass PARQUET_EXPORT PageReader { using DataPageFilter = std::function<bool(const DataPageStats&)>;
public: virtual ~PageReader() = default;
static std::unique_ptr<PageReader> Open( std::shared_ptr<ArrowInputStream> stream, int64_t total_num_values, Compression::type codec, bool always_compressed = false, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool(), const CryptoContext* ctx = NULLPTR); static std::unique_ptr<PageReader> Open(std::shared_ptr<ArrowInputStream> stream, int64_t total_num_values, Compression::type codec, const ReaderProperties& properties, bool always_compressed = false, const CryptoContext* ctx = NULLPTR);
// If data_page_filter is present (not null), NextPage() will call the // callback function exactly once per page in the order the pages appear in // the column. If the callback function returns true the page will be // skipped. The callback will be called only if the page type is DATA_PAGE or // DATA_PAGE_V2. Dictionary pages will not be skipped. // Caller is responsible for checking that statistics are correct using // ApplicationVersion::HasCorrectStatistics(). // \note API EXPERIMENTAL void set_data_page_filter(DataPageFilter data_page_filter) { data_page_filter_ = std::move(data_page_filter); }
// @returns: shared_ptr<Page>(nullptr) on EOS, std::shared_ptr<Page> // containing new Page otherwise // // The returned Page may contain references that aren't guaranteed to live // beyond the next call to NextPage(). virtual std::shared_ptr<Page> NextPage() = 0;
virtual void set_max_page_header_size(uint32_t size) = 0;
protected: // Callback that decides if we should skip a page or not. DataPageFilter data_page_filter_;};
class PARQUET_EXPORT ColumnReader { public: virtual ~ColumnReader() = default;
static std::shared_ptr<ColumnReader> Make( const ColumnDescriptor* descr, std::unique_ptr<PageReader> pager, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
// Returns true if there are still values in this column. virtual bool HasNext() = 0;
virtual Type::type type() const = 0;
virtual const ColumnDescriptor* descr() const = 0;
// Get the encoding that can be exposed by this reader. If it returns // dictionary encoding, then ReadBatchWithDictionary can be used to read data. // // \note API EXPERIMENTAL virtual ExposedEncoding GetExposedEncoding() = 0;
protected: friend class RowGroupReader; // Set the encoding that can be exposed by this reader. // // \note API EXPERIMENTAL virtual void SetExposedEncoding(ExposedEncoding encoding) = 0;};
// API to read values from a single column. This is a main client facing API.template <typename DType>class TypedColumnReader : public ColumnReader { public: using T = typename DType::c_type;
// Read a batch of repetition levels, definition levels, and values from the // column. // // Since null values are not stored in the values, the number of values read // may be less than the number of repetition and definition levels. With // nested data this is almost certainly true. // // Set def_levels or rep_levels to nullptr if you want to skip reading them. // This is only safe if you know through some other source that there are no // undefined values. // // To fully exhaust a row group, you must read batches until the number of // values read reaches the number of stored values according to the metadata. // // This API is the same for both V1 and V2 of the DataPage // // @returns: actual number of levels read (see values_read for number of values read) virtual int64_t ReadBatch(int64_t batch_size, int16_t* def_levels, int16_t* rep_levels, T* values, int64_t* values_read) = 0;
/// Read a batch of repetition levels, definition levels, and values from the /// column and leave spaces for null entries on the lowest level in the values /// buffer. /// /// In comparison to ReadBatch the length of repetition and definition levels /// is the same as of the number of values read for max_definition_level == 1. /// In the case of max_definition_level > 1, the repetition and definition /// levels are larger than the values but the values include the null entries /// with definition_level == (max_definition_level - 1). /// /// To fully exhaust a row group, you must read batches until the number of /// values read reaches the number of stored values according to the metadata. /// /// @param batch_size the number of levels to read /// @param[out] def_levels The Parquet definition levels, output has /// the length levels_read. /// @param[out] rep_levels The Parquet repetition levels, output has /// the length levels_read. /// @param[out] values The values in the lowest nested level including /// spacing for nulls on the lowest levels; output has the length /// values_read. /// @param[out] valid_bits Memory allocated for a bitmap that indicates if /// the row is null or on the maximum definition level. For performance /// reasons the underlying buffer should be able to store 1 bit more than /// required. If this requires an additional byte, this byte is only read /// but never written to. /// @param valid_bits_offset The offset in bits of the valid_bits where the /// first relevant bit resides. /// @param[out] levels_read The number of repetition/definition levels that were read. /// @param[out] values_read The number of values read, this includes all /// non-null entries as well as all null-entries on the lowest level /// (i.e. definition_level == max_definition_level - 1) /// @param[out] null_count The number of nulls on the lowest levels. /// (i.e. (values_read - null_count) is total number of non-null entries) /// /// \deprecated Since 4.0.0 ARROW_DEPRECATED("Doesn't handle nesting correctly and unused outside of unit tests.") virtual int64_t ReadBatchSpaced(int64_t batch_size, int16_t* def_levels, int16_t* rep_levels, T* values, uint8_t* valid_bits, int64_t valid_bits_offset, int64_t* levels_read, int64_t* values_read, int64_t* null_count) = 0;
// Skip reading values. This method will work for both repeated and // non-repeated fields. Note that this method is skipping values and not // records. This distinction is important for repeated fields, meaning that // we are not skipping over the values to the next record. For example, // consider the following two consecutive records containing one repeated field: // {[1, 2, 3]}, {[4, 5]}. If we Skip(2), our next read value will be 3, which // is inside the first record. // Returns the number of values skipped. virtual int64_t Skip(int64_t num_values_to_skip) = 0;
// Read a batch of repetition levels, definition levels, and indices from the // column. And read the dictionary if a dictionary page is encountered during // reading pages. This API is similar to ReadBatch(), with ability to read // dictionary and indices. It is only valid to call this method when the reader can // expose dictionary encoding. (i.e., the reader's GetExposedEncoding() returns // DICTIONARY). // // The dictionary is read along with the data page. When there's no data page, // the dictionary won't be returned. // // @param batch_size The batch size to read // @param[out] def_levels The Parquet definition levels. // @param[out] rep_levels The Parquet repetition levels. // @param[out] indices The dictionary indices. // @param[out] indices_read The number of indices read. // @param[out] dict The pointer to dictionary values. It will return nullptr if // there's no data page. Each column chunk only has one dictionary page. The dictionary // is owned by the reader, so the caller is responsible for copying the dictionary // values before the reader gets destroyed. // @param[out] dict_len The dictionary length. It will return 0 if there's no data // page. // @returns: actual number of levels read (see indices_read for number of // indices read // // \note API EXPERIMENTAL virtual int64_t ReadBatchWithDictionary(int64_t batch_size, int16_t* def_levels, int16_t* rep_levels, int32_t* indices, int64_t* indices_read, const T** dict, int32_t* dict_len) = 0;};
namespace internal {
/// \brief Stateful column reader that delimits semantic records for both flat/// and nested columns////// \note API EXPERIMENTAL/// \since 1.3.0class PARQUET_EXPORT RecordReader { public: /// \brief Creates a record reader. /// @param descr Column descriptor /// @param leaf_info Level info, used to determine if a column is nullable or not /// @param pool Memory pool to use for buffering values and rep/def levels /// @param read_dictionary True if reading directly as Arrow dictionary-encoded /// @param read_dense_for_nullable True if reading dense and not leaving space for null /// values static std::shared_ptr<RecordReader> Make( const ColumnDescriptor* descr, LevelInfo leaf_info, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool(), bool read_dictionary = false, bool read_dense_for_nullable = false);
virtual ~RecordReader() = default;
/// \brief Attempt to read indicated number of records from column chunk /// Note that for repeated fields, a record may have more than one value /// and all of them are read. If read_dense_for_nullable() it will /// not leave any space for null values. Otherwise, it will read spaced. /// \return number of records read virtual int64_t ReadRecords(int64_t num_records) = 0;
/// \brief Attempt to skip indicated number of records from column chunk. /// Note that for repeated fields, a record may have more than one value /// and all of them are skipped. /// \return number of records skipped virtual int64_t SkipRecords(int64_t num_records) = 0;
/// \brief Pre-allocate space for data. Results in better flat read performance virtual void Reserve(int64_t num_values) = 0;
/// \brief Clear consumed values and repetition/definition levels as the /// result of calling ReadRecords /// For FLBA and ByteArray types, call GetBuilderChunks() to reset them. virtual void Reset() = 0;
/// \brief Transfer filled values buffer to caller. A new one will be /// allocated in subsequent ReadRecords calls virtual std::shared_ptr<ResizableBuffer> ReleaseValues() = 0;
/// \brief Transfer filled validity bitmap buffer to caller. A new one will /// be allocated in subsequent ReadRecords calls virtual std::shared_ptr<ResizableBuffer> ReleaseIsValid() = 0;
/// \brief Return true if the record reader has more internal data yet to /// process virtual bool HasMoreData() const = 0;
/// \brief Advance record reader to the next row group. Must be set before /// any records could be read/skipped. /// \param[in] reader obtained from RowGroupReader::GetColumnPageReader virtual void SetPageReader(std::unique_ptr<PageReader> reader) = 0;
/// \brief Returns the underlying column reader's descriptor. virtual const ColumnDescriptor* descr() const = 0;
virtual void DebugPrintState() = 0;
/// \brief Returns the dictionary owned by the current decoder. Throws an /// exception if the current decoder is not for dictionary encoding. The caller is /// responsible for casting the returned pointer to proper type depending on the /// column's physical type. An example: /// const ByteArray* dict = reinterpret_cast<const ByteArray*>(ReadDictionary(&len)); /// or: /// const float* dict = reinterpret_cast<const float*>(ReadDictionary(&len)); /// \param[out] dictionary_length The number of dictionary entries. virtual const void* ReadDictionary(int32_t* dictionary_length) = 0;
/// \brief Decoded definition levels int16_t* def_levels() const { return reinterpret_cast<int16_t*>(def_levels_->mutable_data()); }
/// \brief Decoded repetition levels int16_t* rep_levels() const { return reinterpret_cast<int16_t*>(rep_levels_->mutable_data()); }
/// \brief Decoded values, including nulls, if any /// FLBA and ByteArray types do not use this array and read into their own /// builders. uint8_t* values() const { return values_->mutable_data(); }
/// \brief Number of values written, including space left for nulls if any. /// If this Reader was constructed with read_dense_for_nullable(), there is no space for /// nulls and null_count() will be 0. There is no read-ahead/buffering for values. For /// FLBA and ByteArray types this value reflects the values written with the last /// ReadRecords call since those readers will reset the values after each call. int64_t values_written() const { return values_written_; }
/// \brief Number of definition / repetition levels (from those that have /// been decoded) that have been consumed inside the reader. int64_t levels_position() const { return levels_position_; }
/// \brief Number of definition / repetition levels that have been written /// internally in the reader. This may be larger than values_written() because /// for repeated fields we need to look at the levels in advance to figure out /// the record boundaries. int64_t levels_written() const { return levels_written_; }
/// \brief Number of nulls in the leaf that we have read so far into the /// values vector. This is only valid when !read_dense_for_nullable(). When /// read_dense_for_nullable() it will always be 0. int64_t null_count() const { return null_count_; }
/// \brief True if the leaf values are nullable bool nullable_values() const { return nullable_values_; }
/// \brief True if reading directly as Arrow dictionary-encoded bool read_dictionary() const { return read_dictionary_; }
/// \brief True if reading dense for nullable columns. bool read_dense_for_nullable() const { return read_dense_for_nullable_; }
protected: /// \brief Indicates if we can have nullable values. Note that repeated fields /// may or may not be nullable. bool nullable_values_;
bool at_record_start_; int64_t records_read_;
/// \brief Stores values. These values are populated based on each ReadRecords /// call. No extra values are buffered for the next call. SkipRecords will not /// add any value to this buffer. std::shared_ptr<::arrow::ResizableBuffer> values_; /// \brief False for BYTE_ARRAY, in which case we don't allocate the values /// buffer and we directly read into builder classes. bool uses_values_;
/// \brief Values that we have read into 'values_' + 'null_count_'. int64_t values_written_; int64_t values_capacity_; int64_t null_count_;
/// \brief Each bit corresponds to one element in 'values_' and specifies if it /// is null or not null. Not set if read_dense_for_nullable_ is true. std::shared_ptr<::arrow::ResizableBuffer> valid_bits_;
/// \brief Buffer for definition levels. May contain more levels than /// is actually read. This is because we read levels ahead to /// figure out record boundaries for repeated fields. /// For flat required fields, 'def_levels_' and 'rep_levels_' are not /// populated. For non-repeated fields 'rep_levels_' is not populated. /// 'def_levels_' and 'rep_levels_' must be of the same size if present. std::shared_ptr<::arrow::ResizableBuffer> def_levels_; /// \brief Buffer for repetition levels. Only populated for repeated /// fields. std::shared_ptr<::arrow::ResizableBuffer> rep_levels_;
/// \brief Number of definition / repetition levels that have been written /// internally in the reader. This may be larger than values_written() since /// for repeated fields we need to look at the levels in advance to figure out /// the record boundaries. int64_t levels_written_; /// \brief Position of the next level that should be consumed. int64_t levels_position_; int64_t levels_capacity_;
bool read_dictionary_ = false; // If true, we will not leave any space for the null values in the values_ // vector. bool read_dense_for_nullable_ = false;};
class BinaryRecordReader : virtual public RecordReader { public: virtual std::vector<std::shared_ptr<::arrow::Array>> GetBuilderChunks() = 0;};
/// \brief Read records directly to dictionary-encoded Arrow form (int32/// indices). Only valid for BYTE_ARRAY columnsclass DictionaryRecordReader : virtual public RecordReader { public: virtual std::shared_ptr<::arrow::ChunkedArray> GetResult() = 0;};
} // namespace internal
using BoolReader = TypedColumnReader<BooleanType>;using Int32Reader = TypedColumnReader<Int32Type>;using Int64Reader = TypedColumnReader<Int64Type>;using Int96Reader = TypedColumnReader<Int96Type>;using FloatReader = TypedColumnReader<FloatType>;using DoubleReader = TypedColumnReader<DoubleType>;using ByteArrayReader = TypedColumnReader<ByteArrayType>;using FixedLenByteArrayReader = TypedColumnReader<FLBAType>;
} // namespace parquet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264// 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.
#pragma once
#include <stdio.h>
#include <cstdint>#include <memory>#include <ostream>#include <string>#include <utility>#include <vector>
#include "parquet/column_reader.h"#include "parquet/exception.h"#include "parquet/platform.h"#include "parquet/schema.h"#include "parquet/types.h"
namespace parquet {
static constexpr int64_t DEFAULT_SCANNER_BATCH_SIZE = 128;
class PARQUET_EXPORT Scanner { public: explicit Scanner(std::shared_ptr<ColumnReader> reader, int64_t batch_size = DEFAULT_SCANNER_BATCH_SIZE, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) : batch_size_(batch_size), level_offset_(0), levels_buffered_(0), value_buffer_(AllocateBuffer(pool)), value_offset_(0), values_buffered_(0), reader_(std::move(reader)) { def_levels_.resize( descr()->max_definition_level() > 0 ? static_cast<size_t>(batch_size_) : 0); rep_levels_.resize( descr()->max_repetition_level() > 0 ? static_cast<size_t>(batch_size_) : 0); }
virtual ~Scanner() {}
static std::shared_ptr<Scanner> Make( std::shared_ptr<ColumnReader> col_reader, int64_t batch_size = DEFAULT_SCANNER_BATCH_SIZE, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
virtual void PrintNext(std::ostream& out, int width, bool with_levels = false) = 0;
bool HasNext() { return level_offset_ < levels_buffered_ || reader_->HasNext(); }
const ColumnDescriptor* descr() const { return reader_->descr(); }
int64_t batch_size() const { return batch_size_; }
void SetBatchSize(int64_t batch_size) { batch_size_ = batch_size; }
protected: int64_t batch_size_;
std::vector<int16_t> def_levels_; std::vector<int16_t> rep_levels_; int level_offset_; int levels_buffered_;
std::shared_ptr<ResizableBuffer> value_buffer_; int value_offset_; int64_t values_buffered_; std::shared_ptr<ColumnReader> reader_;};
template <typename DType>class PARQUET_TEMPLATE_CLASS_EXPORT TypedScanner : public Scanner { public: typedef typename DType::c_type T;
explicit TypedScanner(std::shared_ptr<ColumnReader> reader, int64_t batch_size = DEFAULT_SCANNER_BATCH_SIZE, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) : Scanner(std::move(reader), batch_size, pool) { typed_reader_ = static_cast<TypedColumnReader<DType>*>(reader_.get()); int value_byte_size = type_traits<DType::type_num>::value_byte_size; PARQUET_THROW_NOT_OK(value_buffer_->Resize(batch_size_ * value_byte_size)); values_ = reinterpret_cast<T*>(value_buffer_->mutable_data()); }
virtual ~TypedScanner() {}
bool NextLevels(int16_t* def_level, int16_t* rep_level) { if (level_offset_ == levels_buffered_) { levels_buffered_ = static_cast<int>( typed_reader_->ReadBatch(static_cast<int>(batch_size_), def_levels_.data(), rep_levels_.data(), values_, &values_buffered_));
value_offset_ = 0; level_offset_ = 0; if (!levels_buffered_) { return false; } } *def_level = descr()->max_definition_level() > 0 ? def_levels_[level_offset_] : 0; *rep_level = descr()->max_repetition_level() > 0 ? rep_levels_[level_offset_] : 0; level_offset_++; return true; }
bool Next(T* val, int16_t* def_level, int16_t* rep_level, bool* is_null) { if (level_offset_ == levels_buffered_) { if (!HasNext()) { // Out of data pages return false; } }
NextLevels(def_level, rep_level); *is_null = *def_level < descr()->max_definition_level();
if (*is_null) { return true; }
if (value_offset_ == values_buffered_) { throw ParquetException("Value was non-null, but has not been buffered"); } *val = values_[value_offset_++]; return true; }
// Returns true if there is a next value bool NextValue(T* val, bool* is_null) { if (level_offset_ == levels_buffered_) { if (!HasNext()) { // Out of data pages return false; } }
// Out of values int16_t def_level = -1; int16_t rep_level = -1; NextLevels(&def_level, &rep_level); *is_null = def_level < descr()->max_definition_level();
if (*is_null) { return true; }
if (value_offset_ == values_buffered_) { throw ParquetException("Value was non-null, but has not been buffered"); } *val = values_[value_offset_++]; return true; }
virtual void PrintNext(std::ostream& out, int width, bool with_levels = false) { T val{}; int16_t def_level = -1; int16_t rep_level = -1; bool is_null = false; char buffer[80];
if (!Next(&val, &def_level, &rep_level, &is_null)) { throw ParquetException("No more values buffered"); }
if (with_levels) { out << " D:" << def_level << " R:" << rep_level << " "; if (!is_null) { out << "V:"; } }
if (is_null) { std::string null_fmt = format_fwf<ByteArrayType>(width); snprintf(buffer, sizeof(buffer), null_fmt.c_str(), "NULL"); } else { FormatValue(&val, buffer, sizeof(buffer), width); } out << buffer; }
private: // The ownership of this object is expressed through the reader_ variable in the base TypedColumnReader<DType>* typed_reader_;
inline void FormatValue(void* val, char* buffer, int bufsize, int width);
T* values_;};
template <typename DType>inline void TypedScanner<DType>::FormatValue(void* val, char* buffer, int bufsize, int width) { std::string fmt = format_fwf<DType>(width); snprintf(buffer, bufsize, fmt.c_str(), *reinterpret_cast<T*>(val));}
template <>inline void TypedScanner<Int96Type>::FormatValue(void* val, char* buffer, int bufsize, int width) { std::string fmt = format_fwf<Int96Type>(width); std::string result = Int96ToString(*reinterpret_cast<Int96*>(val)); snprintf(buffer, bufsize, fmt.c_str(), result.c_str());}
template <>inline void TypedScanner<ByteArrayType>::FormatValue(void* val, char* buffer, int bufsize, int width) { std::string fmt = format_fwf<ByteArrayType>(width); std::string result = ByteArrayToString(*reinterpret_cast<ByteArray*>(val)); snprintf(buffer, bufsize, fmt.c_str(), result.c_str());}
template <>inline void TypedScanner<FLBAType>::FormatValue(void* val, char* buffer, int bufsize, int width) { std::string fmt = format_fwf<FLBAType>(width); std::string result = FixedLenByteArrayToString( *reinterpret_cast<FixedLenByteArray*>(val), descr()->type_length()); snprintf(buffer, bufsize, fmt.c_str(), result.c_str());}
typedef TypedScanner<BooleanType> BoolScanner;typedef TypedScanner<Int32Type> Int32Scanner;typedef TypedScanner<Int64Type> Int64Scanner;typedef TypedScanner<Int96Type> Int96Scanner;typedef TypedScanner<FloatType> FloatScanner;typedef TypedScanner<DoubleType> DoubleScanner;typedef TypedScanner<ByteArrayType> ByteArrayScanner;typedef TypedScanner<FLBAType> FixedLenByteArrayScanner;
template <typename RType>int64_t ScanAll(int32_t batch_size, int16_t* def_levels, int16_t* rep_levels, uint8_t* values, int64_t* values_buffered, parquet::ColumnReader* reader) { typedef typename RType::T Type; auto typed_reader = static_cast<RType*>(reader); auto vals = reinterpret_cast<Type*>(&values[0]); return typed_reader->ReadBatch(batch_size, def_levels, rep_levels, vals, values_buffered);}
int64_t PARQUET_EXPORT ScanAllValues(int32_t batch_size, int16_t* def_levels, int16_t* rep_levels, uint8_t* values, int64_t* values_buffered, parquet::ColumnReader* reader);
} // namespace parquet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307// 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.
#pragma once
#include <cstdint>#include <cstring>#include <memory>
#include "arrow/util/compression.h"#include "parquet/exception.h"#include "parquet/platform.h"#include "parquet/types.h"
namespace arrow {
class Array;
namespace bit_util {class BitWriter;} // namespace bit_util
namespace util {class RleEncoder;class CodecOptions;} // namespace util
} // namespace arrow
namespace parquet {
struct ArrowWriteContext;class ColumnChunkMetaDataBuilder;class ColumnDescriptor;class ColumnIndexBuilder;class DataPage;class DictionaryPage;class Encryptor;class OffsetIndexBuilder;class WriterProperties;
class PARQUET_EXPORT LevelEncoder { public: LevelEncoder(); ~LevelEncoder();
static int MaxBufferSize(Encoding::type encoding, int16_t max_level, int num_buffered_values);
// Initialize the LevelEncoder. void Init(Encoding::type encoding, int16_t max_level, int num_buffered_values, uint8_t* data, int data_size);
// Encodes a batch of levels from an array and returns the number of levels encoded int Encode(int batch_size, const int16_t* levels);
int32_t len() { if (encoding_ != Encoding::RLE) { throw ParquetException("Only implemented for RLE encoding"); } return rle_length_; }
private: int bit_width_; int rle_length_; Encoding::type encoding_; std::unique_ptr<::arrow::util::RleEncoder> rle_encoder_; std::unique_ptr<::arrow::bit_util::BitWriter> bit_packed_encoder_;};
class PARQUET_EXPORT PageWriter { public: virtual ~PageWriter() {}
static std::unique_ptr<PageWriter> Open( std::shared_ptr<ArrowOutputStream> sink, Compression::type codec, ColumnChunkMetaDataBuilder* metadata, int16_t row_group_ordinal = -1, int16_t column_chunk_ordinal = -1, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool(), bool buffered_row_group = false, std::shared_ptr<Encryptor> header_encryptor = NULLPTR, std::shared_ptr<Encryptor> data_encryptor = NULLPTR, bool page_write_checksum_enabled = false, // column_index_builder MUST outlive the PageWriter ColumnIndexBuilder* column_index_builder = NULLPTR, // offset_index_builder MUST outlive the PageWriter OffsetIndexBuilder* offset_index_builder = NULLPTR, const CodecOptions& codec_options = CodecOptions{});
ARROW_DEPRECATED("Deprecated in 13.0.0. Use CodecOptions-taking overload instead.") static std::unique_ptr<PageWriter> Open( std::shared_ptr<ArrowOutputStream> sink, Compression::type codec, int compression_level, ColumnChunkMetaDataBuilder* metadata, int16_t row_group_ordinal = -1, int16_t column_chunk_ordinal = -1, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool(), bool buffered_row_group = false, std::shared_ptr<Encryptor> header_encryptor = NULLPTR, std::shared_ptr<Encryptor> data_encryptor = NULLPTR, bool page_write_checksum_enabled = false, // column_index_builder MUST outlive the PageWriter ColumnIndexBuilder* column_index_builder = NULLPTR, // offset_index_builder MUST outlive the PageWriter OffsetIndexBuilder* offset_index_builder = NULLPTR);
// The Column Writer decides if dictionary encoding is used if set and // if the dictionary encoding has fallen back to default encoding on reaching dictionary // page limit virtual void Close(bool has_dictionary, bool fallback) = 0;
// Return the number of uncompressed bytes written (including header size) virtual int64_t WriteDataPage(const DataPage& page) = 0;
// Return the number of uncompressed bytes written (including header size) virtual int64_t WriteDictionaryPage(const DictionaryPage& page) = 0;
/// \brief The total number of bytes written as serialized data and /// dictionary pages to the sink so far. virtual int64_t total_compressed_bytes_written() const = 0;
virtual bool has_compressor() = 0;
virtual void Compress(const Buffer& src_buffer, ResizableBuffer* dest_buffer) = 0;};
class PARQUET_EXPORT ColumnWriter { public: virtual ~ColumnWriter() = default;
static std::shared_ptr<ColumnWriter> Make(ColumnChunkMetaDataBuilder*, std::unique_ptr<PageWriter>, const WriterProperties* properties);
/// \brief Closes the ColumnWriter, commits any buffered values to pages. /// \return Total size of the column in bytes virtual int64_t Close() = 0;
/// \brief The physical Parquet type of the column virtual Type::type type() const = 0;
/// \brief The schema for the column virtual const ColumnDescriptor* descr() const = 0;
/// \brief The number of rows written so far virtual int64_t rows_written() const = 0;
/// \brief The total size of the compressed pages + page headers. Values /// are still buffered and not written to a pager yet /// /// So in un-buffered mode, it always returns 0 virtual int64_t total_compressed_bytes() const = 0;
/// \brief The total number of bytes written as serialized data and /// dictionary pages to the ColumnChunk so far /// These bytes are uncompressed bytes. virtual int64_t total_bytes_written() const = 0;
/// \brief The total number of bytes written as serialized data and /// dictionary pages to the ColumnChunk so far. /// If the column is uncompressed, the value would be equal to /// total_bytes_written(). virtual int64_t total_compressed_bytes_written() const = 0;
/// \brief Estimated size of the values that are not written to a page yet. virtual int64_t estimated_buffered_value_bytes() const = 0;
/// \brief The file-level writer properties virtual const WriterProperties* properties() = 0;
/// \brief Write Apache Arrow columnar data directly to ColumnWriter. Returns /// error status if the array data type is not compatible with the concrete /// writer type. /// /// leaf_array is always a primitive (possibly dictionary encoded type). /// Leaf_field_nullable indicates whether the leaf array is considered nullable /// according to its schema in a Table or its parent array. virtual ::arrow::Status WriteArrow(const int16_t* def_levels, const int16_t* rep_levels, int64_t num_levels, const ::arrow::Array& leaf_array, ArrowWriteContext* ctx, bool leaf_field_nullable) = 0;};
// API to write values to a single column. This is the main client facing API.template <typename DType>class TypedColumnWriter : public ColumnWriter { public: using T = typename DType::c_type;
// Write a batch of repetition levels, definition levels, and values to the // column. // `num_values` is the number of logical leaf values. // `def_levels` (resp. `rep_levels`) can be null if the column's max definition level // (resp. max repetition level) is 0. // If not null, each of `def_levels` and `rep_levels` must have at least // `num_values`. // // The number of physical values written (taken from `values`) is returned. // It can be smaller than `num_values` is there are some undefined values. virtual int64_t WriteBatch(int64_t num_values, const int16_t* def_levels, const int16_t* rep_levels, const T* values) = 0;
/// Write a batch of repetition levels, definition levels, and values to the /// column. /// /// In comparison to WriteBatch the length of repetition and definition levels /// is the same as of the number of values read for max_definition_level == 1. /// In the case of max_definition_level > 1, the repetition and definition /// levels are larger than the values but the values include the null entries /// with definition_level == (max_definition_level - 1). Thus we have to differentiate /// in the parameters of this function if the input has the length of num_values or the /// _number of rows in the lowest nesting level_. /// /// In the case that the most inner node in the Parquet is required, the _number of rows /// in the lowest nesting level_ is equal to the number of non-null values. If the /// inner-most schema node is optional, the _number of rows in the lowest nesting level_ /// also includes all values with definition_level == (max_definition_level - 1). /// /// @param num_values number of levels to write. /// @param def_levels The Parquet definition levels, length is num_values /// @param rep_levels The Parquet repetition levels, length is num_values /// @param valid_bits Bitmap that indicates if the row is null on the lowest nesting /// level. The length is number of rows in the lowest nesting level. /// @param valid_bits_offset The offset in bits of the valid_bits where the /// first relevant bit resides. /// @param values The values in the lowest nested level including /// spacing for nulls on the lowest levels; input has the length /// of the number of rows on the lowest nesting level. virtual void WriteBatchSpaced(int64_t num_values, const int16_t* def_levels, const int16_t* rep_levels, const uint8_t* valid_bits, int64_t valid_bits_offset, const T* values) = 0;};
using BoolWriter = TypedColumnWriter<BooleanType>;using Int32Writer = TypedColumnWriter<Int32Type>;using Int64Writer = TypedColumnWriter<Int64Type>;using Int96Writer = TypedColumnWriter<Int96Type>;using FloatWriter = TypedColumnWriter<FloatType>;using DoubleWriter = TypedColumnWriter<DoubleType>;using ByteArrayWriter = TypedColumnWriter<ByteArrayType>;using FixedLenByteArrayWriter = TypedColumnWriter<FLBAType>;
namespace internal {
/** * Timestamp conversion constants */constexpr int64_t kJulianEpochOffsetDays = INT64_C(2440588);
template <int64_t UnitPerDay, int64_t NanosecondsPerUnit>inline void ArrowTimestampToImpalaTimestamp(const int64_t time, Int96* impala_timestamp) { int64_t julian_days = (time / UnitPerDay) + kJulianEpochOffsetDays; (*impala_timestamp).value[2] = (uint32_t)julian_days;
int64_t last_day_units = time % UnitPerDay; auto last_day_nanos = last_day_units * NanosecondsPerUnit; // impala_timestamp will be unaligned every other entry so do memcpy instead // of assign and reinterpret cast to avoid undefined behavior. std::memcpy(impala_timestamp, &last_day_nanos, sizeof(int64_t));}
constexpr int64_t kSecondsInNanos = INT64_C(1000000000);
inline void SecondsToImpalaTimestamp(const int64_t seconds, Int96* impala_timestamp) { ArrowTimestampToImpalaTimestamp<kSecondsPerDay, kSecondsInNanos>(seconds, impala_timestamp);}
constexpr int64_t kMillisecondsInNanos = kSecondsInNanos / INT64_C(1000);
inline void MillisecondsToImpalaTimestamp(const int64_t milliseconds, Int96* impala_timestamp) { ArrowTimestampToImpalaTimestamp<kMillisecondsPerDay, kMillisecondsInNanos>( milliseconds, impala_timestamp);}
constexpr int64_t kMicrosecondsInNanos = kMillisecondsInNanos / INT64_C(1000);
inline void MicrosecondsToImpalaTimestamp(const int64_t microseconds, Int96* impala_timestamp) { ArrowTimestampToImpalaTimestamp<kMicrosecondsPerDay, kMicrosecondsInNanos>( microseconds, impala_timestamp);}
constexpr int64_t kNanosecondsInNanos = INT64_C(1);
inline void NanosecondsToImpalaTimestamp(const int64_t nanoseconds, Int96* impala_timestamp) { ArrowTimestampToImpalaTimestamp<kNanosecondsPerDay, kNanosecondsInNanos>( nanoseconds, impala_timestamp);}
} // namespace internal} // namespace parquet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476// 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.
#pragma once
#include <cstdint>#include <cstring>#include <memory>#include <vector>
#include "arrow/util/spaced.h"
#include "parquet/exception.h"#include "parquet/platform.h"#include "parquet/types.h"
namespace arrow {
class Array;class ArrayBuilder;class BinaryArray;class BinaryBuilder;class BooleanBuilder;class Int32Type;class Int64Type;class FloatType;class DoubleType;class FixedSizeBinaryType;template <typename T>class NumericBuilder;class FixedSizeBinaryBuilder;template <typename T>class Dictionary32Builder;
} // namespace arrow
namespace parquet {
template <typename DType>class TypedEncoder;
using BooleanEncoder = TypedEncoder<BooleanType>;using Int32Encoder = TypedEncoder<Int32Type>;using Int64Encoder = TypedEncoder<Int64Type>;using Int96Encoder = TypedEncoder<Int96Type>;using FloatEncoder = TypedEncoder<FloatType>;using DoubleEncoder = TypedEncoder<DoubleType>;using ByteArrayEncoder = TypedEncoder<ByteArrayType>;using FLBAEncoder = TypedEncoder<FLBAType>;
template <typename DType>class TypedDecoder;
class BooleanDecoder;using Int32Decoder = TypedDecoder<Int32Type>;using Int64Decoder = TypedDecoder<Int64Type>;using Int96Decoder = TypedDecoder<Int96Type>;using FloatDecoder = TypedDecoder<FloatType>;using DoubleDecoder = TypedDecoder<DoubleType>;using ByteArrayDecoder = TypedDecoder<ByteArrayType>;class FLBADecoder;
template <typename T>struct EncodingTraits;
template <>struct EncodingTraits<BooleanType> { using Encoder = BooleanEncoder; using Decoder = BooleanDecoder;
using ArrowType = ::arrow::BooleanType; using Accumulator = ::arrow::BooleanBuilder; struct DictAccumulator {};};
template <>struct EncodingTraits<Int32Type> { using Encoder = Int32Encoder; using Decoder = Int32Decoder;
using ArrowType = ::arrow::Int32Type; using Accumulator = ::arrow::NumericBuilder<::arrow::Int32Type>; using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::Int32Type>;};
template <>struct EncodingTraits<Int64Type> { using Encoder = Int64Encoder; using Decoder = Int64Decoder;
using ArrowType = ::arrow::Int64Type; using Accumulator = ::arrow::NumericBuilder<::arrow::Int64Type>; using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::Int64Type>;};
template <>struct EncodingTraits<Int96Type> { using Encoder = Int96Encoder; using Decoder = Int96Decoder;
struct Accumulator {}; struct DictAccumulator {};};
template <>struct EncodingTraits<FloatType> { using Encoder = FloatEncoder; using Decoder = FloatDecoder;
using ArrowType = ::arrow::FloatType; using Accumulator = ::arrow::NumericBuilder<::arrow::FloatType>; using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::FloatType>;};
template <>struct EncodingTraits<DoubleType> { using Encoder = DoubleEncoder; using Decoder = DoubleDecoder;
using ArrowType = ::arrow::DoubleType; using Accumulator = ::arrow::NumericBuilder<::arrow::DoubleType>; using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::DoubleType>;};
template <>struct EncodingTraits<ByteArrayType> { using Encoder = ByteArrayEncoder; using Decoder = ByteArrayDecoder;
using ArrowType = ::arrow::BinaryType; /// \brief Internal helper class for decoding BYTE_ARRAY data where we can /// overflow the capacity of a single arrow::BinaryArray struct Accumulator { std::unique_ptr<::arrow::BinaryBuilder> builder; std::vector<std::shared_ptr<::arrow::Array>> chunks; }; using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::BinaryType>;};
template <>struct EncodingTraits<FLBAType> { using Encoder = FLBAEncoder; using Decoder = FLBADecoder;
using ArrowType = ::arrow::FixedSizeBinaryType; using Accumulator = ::arrow::FixedSizeBinaryBuilder; using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::FixedSizeBinaryType>;};
class ColumnDescriptor;
// Untyped base for all encodersclass Encoder { public: virtual ~Encoder() = default;
virtual int64_t EstimatedDataEncodedSize() = 0; virtual std::shared_ptr<Buffer> FlushValues() = 0; virtual Encoding::type encoding() const = 0;
virtual void Put(const ::arrow::Array& values) = 0;
virtual MemoryPool* memory_pool() const = 0;};
// Base class for value encoders. Since encoders may or not have state (e.g.,// dictionary encoding) we use a class instance to maintain any state.//// Encode interfaces are internal, subject to change without deprecation.template <typename DType>class TypedEncoder : virtual public Encoder { public: typedef typename DType::c_type T;
using Encoder::Put;
virtual void Put(const T* src, int num_values) = 0;
virtual void Put(const std::vector<T>& src, int num_values = -1);
virtual void PutSpaced(const T* src, int num_values, const uint8_t* valid_bits, int64_t valid_bits_offset) = 0;};
template <typename DType>void TypedEncoder<DType>::Put(const std::vector<T>& src, int num_values) { if (num_values == -1) { num_values = static_cast<int>(src.size()); } Put(src.data(), num_values);}
template <>inline void TypedEncoder<BooleanType>::Put(const std::vector<bool>& src, int num_values) { // NOTE(wesm): This stub is here only to satisfy the compiler; it is // overridden later with the actual implementation}
// Base class for dictionary encoderstemplate <typename DType>class DictEncoder : virtual public TypedEncoder<DType> { public: /// Writes out any buffered indices to buffer preceded by the bit width of this data. /// Returns the number of bytes written. /// If the supplied buffer is not big enough, returns -1. /// buffer must be preallocated with buffer_len bytes. Use EstimatedDataEncodedSize() /// to size buffer. virtual int WriteIndices(uint8_t* buffer, int buffer_len) = 0;
virtual int dict_encoded_size() const = 0;
virtual int bit_width() const = 0;
/// Writes out the encoded dictionary to buffer. buffer must be preallocated to /// dict_encoded_size() bytes. virtual void WriteDict(uint8_t* buffer) const = 0;
virtual int num_entries() const = 0;
/// \brief EXPERIMENTAL: Append dictionary indices into the encoder. It is /// assumed (without any boundschecking) that the indices reference /// preexisting dictionary values /// \param[in] indices the dictionary index values. Only Int32Array currently /// supported virtual void PutIndices(const ::arrow::Array& indices) = 0;
/// \brief EXPERIMENTAL: Append dictionary into encoder, inserting indices /// separately. Currently throws exception if the current dictionary memo is /// non-empty /// \param[in] values the dictionary values. Only valid for certain /// Parquet/Arrow type combinations, like BYTE_ARRAY/BinaryArray virtual void PutDictionary(const ::arrow::Array& values) = 0;};
// ----------------------------------------------------------------------// Value decoding
class Decoder { public: virtual ~Decoder() = default;
// Sets the data for a new page. This will be called multiple times on the same // decoder and should reset all internal state. // // `num_values` comes from the data page header, and may be greater than the number of // physical values in the data buffer if there are some omitted (null) values. // `len`, on the other hand, is the size in bytes of the data buffer and // directly relates to the number of physical values. virtual void SetData(int num_values, const uint8_t* data, int len) = 0;
// Returns the number of values left (for the last call to SetData()). This is // the number of values left in this page. virtual int values_left() const = 0; virtual Encoding::type encoding() const = 0;};
template <typename DType>class TypedDecoder : virtual public Decoder { public: using T = typename DType::c_type;
/// \brief Decode values into a buffer /// /// Subclasses may override the more specialized Decode methods below. /// /// \param[in] buffer destination for decoded values /// \param[in] max_values maximum number of values to decode /// \return The number of values decoded. Should be identical to max_values except /// at the end of the current data page. virtual int Decode(T* buffer, int max_values) = 0;
/// \brief Decode the values in this data page but leave spaces for null entries. /// /// \param[in] buffer destination for decoded values /// \param[in] num_values size of the def_levels and buffer arrays including the number /// of null slots /// \param[in] null_count number of null slots /// \param[in] valid_bits bitmap data indicating position of valid slots /// \param[in] valid_bits_offset offset into valid_bits /// \return The number of values decoded, including nulls. virtual int DecodeSpaced(T* buffer, int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset) { if (null_count > 0) { int values_to_read = num_values - null_count; int values_read = Decode(buffer, values_to_read); if (values_read != values_to_read) { throw ParquetException("Number of values / definition_levels read did not match"); }
return ::arrow::util::internal::SpacedExpand<T>(buffer, num_values, null_count, valid_bits, valid_bits_offset); } else { return Decode(buffer, num_values); } }
/// \brief Decode into an ArrayBuilder or other accumulator /// /// This function assumes the definition levels were already decoded /// as a validity bitmap in the given `valid_bits`. `null_count` /// is the number of 0s in `valid_bits`. /// As a space optimization, it is allowed for `valid_bits` to be null /// if `null_count` is zero. /// /// \return number of values decoded virtual int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset, typename EncodingTraits<DType>::Accumulator* out) = 0;
/// \brief Decode into an ArrayBuilder or other accumulator ignoring nulls /// /// \return number of values decoded int DecodeArrowNonNull(int num_values, typename EncodingTraits<DType>::Accumulator* out) { return DecodeArrow(num_values, 0, /*valid_bits=*/NULLPTR, 0, out); }
/// \brief Decode into a DictionaryBuilder /// /// This function assumes the definition levels were already decoded /// as a validity bitmap in the given `valid_bits`. `null_count` /// is the number of 0s in `valid_bits`. /// As a space optimization, it is allowed for `valid_bits` to be null /// if `null_count` is zero. /// /// \return number of values decoded virtual int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset, typename EncodingTraits<DType>::DictAccumulator* builder) = 0;
/// \brief Decode into a DictionaryBuilder ignoring nulls /// /// \return number of values decoded int DecodeArrowNonNull(int num_values, typename EncodingTraits<DType>::DictAccumulator* builder) { return DecodeArrow(num_values, 0, /*valid_bits=*/NULLPTR, 0, builder); }};
template <typename DType>class DictDecoder : virtual public TypedDecoder<DType> { public: using T = typename DType::c_type;
virtual void SetDict(TypedDecoder<DType>* dictionary) = 0;
/// \brief Insert dictionary values into the Arrow dictionary builder's memo, /// but do not append any indices virtual void InsertDictionary(::arrow::ArrayBuilder* builder) = 0;
/// \brief Decode only dictionary indices and append to dictionary /// builder. The builder must have had the dictionary from this decoder /// inserted already. /// /// \warning Remember to reset the builder each time the dict decoder is initialized /// with a new dictionary page virtual int DecodeIndicesSpaced(int num_values, int null_count, const uint8_t* valid_bits, int64_t valid_bits_offset, ::arrow::ArrayBuilder* builder) = 0;
/// \brief Decode only dictionary indices (no nulls) /// /// \warning Remember to reset the builder each time the dict decoder is initialized /// with a new dictionary page virtual int DecodeIndices(int num_values, ::arrow::ArrayBuilder* builder) = 0;
/// \brief Decode only dictionary indices (no nulls). Same as above /// DecodeIndices but target is an array instead of a builder. /// /// \note API EXPERIMENTAL virtual int DecodeIndices(int num_values, int32_t* indices) = 0;
/// \brief Get dictionary. The reader will call this API when it encounters a /// new dictionary. /// /// @param[out] dictionary The pointer to dictionary values. Dictionary is owned by /// the decoder and is destroyed when the decoder is destroyed. /// @param[out] dictionary_length The dictionary length. /// /// \note API EXPERIMENTAL virtual void GetDictionary(const T** dictionary, int32_t* dictionary_length) = 0;};
// ----------------------------------------------------------------------// TypedEncoder specializations, traits, and factory functions
class BooleanDecoder : virtual public TypedDecoder<BooleanType> { public: using TypedDecoder<BooleanType>::Decode;
/// \brief Decode and bit-pack values into a buffer /// /// \param[in] buffer destination for decoded values /// This buffer will contain bit-packed values. If /// max_values is not a multiple of 8, the trailing bits /// of the last byte will be undefined. /// \param[in] max_values max values to decode. /// \return The number of values decoded. Should be identical to max_values except /// at the end of the current data page. virtual int Decode(uint8_t* buffer, int max_values) = 0;};
class FLBADecoder : virtual public TypedDecoder<FLBAType> { public: using TypedDecoder<FLBAType>::DecodeSpaced;
// TODO(wesm): As possible follow-up to PARQUET-1508, we should examine if // there is value in adding specialized read methods for // FIXED_LEN_BYTE_ARRAY. If only Decimal data can occur with this data type // then perhaps not};
PARQUET_EXPORTstd::unique_ptr<Encoder> MakeEncoder( Type::type type_num, Encoding::type encoding, bool use_dictionary = false, const ColumnDescriptor* descr = NULLPTR, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
template <typename DType>std::unique_ptr<typename EncodingTraits<DType>::Encoder> MakeTypedEncoder( Encoding::type encoding, bool use_dictionary = false, const ColumnDescriptor* descr = NULLPTR, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) { using OutType = typename EncodingTraits<DType>::Encoder; std::unique_ptr<Encoder> base = MakeEncoder(DType::type_num, encoding, use_dictionary, descr, pool); return std::unique_ptr<OutType>(dynamic_cast<OutType*>(base.release()));}
PARQUET_EXPORTstd::unique_ptr<Decoder> MakeDecoder( Type::type type_num, Encoding::type encoding, const ColumnDescriptor* descr = NULLPTR, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
namespace detail {
PARQUET_EXPORTstd::unique_ptr<Decoder> MakeDictDecoder(Type::type type_num, const ColumnDescriptor* descr, ::arrow::MemoryPool* pool);
} // namespace detail
template <typename DType>std::unique_ptr<DictDecoder<DType>> MakeDictDecoder( const ColumnDescriptor* descr = NULLPTR, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) { using OutType = DictDecoder<DType>; auto decoder = detail::MakeDictDecoder(DType::type_num, descr, pool); return std::unique_ptr<OutType>(dynamic_cast<OutType*>(decoder.release()));}
template <typename DType>std::unique_ptr<typename EncodingTraits<DType>::Decoder> MakeTypedDecoder( Encoding::type encoding, const ColumnDescriptor* descr = NULLPTR, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) { using OutType = typename EncodingTraits<DType>::Decoder; std::unique_ptr<Decoder> base = MakeDecoder(DType::type_num, encoding, descr, pool); return std::unique_ptr<OutType>(dynamic_cast<OutType*>(base.release()));}
} // namespace parquet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152// 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.
#pragma once
#include <memory>
#include "parquet/encryption/encryption.h"#include "parquet/encryption/file_key_wrapper.h"#include "parquet/encryption/key_toolkit.h"#include "parquet/encryption/kms_client_factory.h"#include "parquet/platform.h"
namespace parquet::encryption {
static constexpr ParquetCipher::type kDefaultEncryptionAlgorithm = ParquetCipher::AES_GCM_V1;static constexpr bool kDefaultPlaintextFooter = false;static constexpr bool kDefaultDoubleWrapping = true;static constexpr double kDefaultCacheLifetimeSeconds = 600; // 10 minutesstatic constexpr bool kDefaultInternalKeyMaterial = true;static constexpr bool kDefaultUniformEncryption = false;static constexpr int32_t kDefaultDataKeyLengthBits = 128;
struct PARQUET_EXPORT EncryptionConfiguration { explicit EncryptionConfiguration(const std::string& footer_key) : footer_key(footer_key) {}
/// ID of the master key for footer encryption/signing std::string footer_key;
/// List of columns to encrypt, with master key IDs (see HIVE-21848). /// Format: "masterKeyID:colName,colName;masterKeyID:colName..." /// Either /// (1) column_keys must be set /// or /// (2) uniform_encryption must be set to true /// If none of (1) and (2) are true, or if both are true, an exception will be /// thrown. std::string column_keys;
/// Encrypt footer and all columns with the same encryption key. bool uniform_encryption = kDefaultUniformEncryption;
/// Parquet encryption algorithm. Can be "AES_GCM_V1" (default), or "AES_GCM_CTR_V1". ParquetCipher::type encryption_algorithm = kDefaultEncryptionAlgorithm;
/// Write files with plaintext footer. /// The default is false - files are written with encrypted footer. bool plaintext_footer = kDefaultPlaintextFooter;
/// Use double wrapping - where data encryption keys (DEKs) are encrypted with key /// encryption keys (KEKs), which in turn are encrypted with master keys. /// The default is true. If set to false, use single wrapping - where DEKs are /// encrypted directly with master keys. bool double_wrapping = kDefaultDoubleWrapping;
/// Lifetime of cached entities (key encryption keys, local wrapping keys, KMS client /// objects). /// The default is 600 (10 minutes). double cache_lifetime_seconds = kDefaultCacheLifetimeSeconds;
/// Store key material inside Parquet file footers; this mode doesn’t produce /// additional files. By default, true. If set to false, key material is stored in /// separate files in the same folder, which enables key rotation for immutable /// Parquet files. bool internal_key_material = kDefaultInternalKeyMaterial;
/// Length of data encryption keys (DEKs), randomly generated by parquet key /// management tools. Can be 128, 192 or 256 bits. /// The default is 128 bits. int32_t data_key_length_bits = kDefaultDataKeyLengthBits;};
struct PARQUET_EXPORT DecryptionConfiguration { /// Lifetime of cached entities (key encryption keys, local wrapping keys, KMS client /// objects). /// The default is 600 (10 minutes). double cache_lifetime_seconds = kDefaultCacheLifetimeSeconds;};
/// This is a core class, that translates the parameters of high level encryption (like/// the names of encrypted columns, names of master keys, etc), into parameters of low/// level encryption (like the key metadata, DEK, etc). A factory that produces the low/// level FileEncryptionProperties and FileDecryptionProperties objects, from the high/// level parameters.class PARQUET_EXPORT CryptoFactory { public: /// a KmsClientFactory object must be registered via this method before calling any of /// GetFileEncryptionProperties()/GetFileDecryptionProperties() methods. void RegisterKmsClientFactory(std::shared_ptr<KmsClientFactory> kms_client_factory);
/// Get the encryption properties for a Parquet file. /// If external key material is used then a file system and path to the /// parquet file must be provided. std::shared_ptr<FileEncryptionProperties> GetFileEncryptionProperties( const KmsConnectionConfig& kms_connection_config, const EncryptionConfiguration& encryption_config, const std::string& file_path = "", const std::shared_ptr<::arrow::fs::FileSystem>& file_system = NULLPTR);
/// Get decryption properties for a Parquet file. /// If external key material is used then a file system and path to the /// parquet file must be provided. std::shared_ptr<FileDecryptionProperties> GetFileDecryptionProperties( const KmsConnectionConfig& kms_connection_config, const DecryptionConfiguration& decryption_config, const std::string& file_path = "", const std::shared_ptr<::arrow::fs::FileSystem>& file_system = NULLPTR);
void RemoveCacheEntriesForToken(const std::string& access_token) { key_toolkit_->RemoveCacheEntriesForToken(access_token); }
void RemoveCacheEntriesForAllTokens() { key_toolkit_->RemoveCacheEntriesForAllTokens(); }
/// Rotates master encryption keys for a Parquet file that uses external key material. /// In single wrapping mode, data encryption keys are decrypted with the old master keys /// and then re-encrypted with new master keys. /// In double wrapping mode, key encryption keys are decrypted with the old master keys /// and then re-encrypted with new master keys. /// This relies on the KMS supporting versioning, such that the old master key is /// used when unwrapping a key, and the latest version is used when wrapping a key. void RotateMasterKeys(const KmsConnectionConfig& kms_connection_config, const std::string& parquet_file_path, const std::shared_ptr<::arrow::fs::FileSystem>& file_system, bool double_wrapping = kDefaultDoubleWrapping, double cache_lifetime_seconds = kDefaultCacheLifetimeSeconds);
private: ColumnPathToEncryptionPropertiesMap GetColumnEncryptionProperties( int dek_length, const std::string& column_keys, FileKeyWrapper* key_wrapper);
/// Key utilities object for kms client initialization and cache control std::shared_ptr<KeyToolkit> key_toolkit_ = std::make_shared<KeyToolkit>();};
} // namespace parquet::encryption123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518// 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.
#pragma once
#include <map>#include <memory>#include <string>#include <utility>
#include "parquet/exception.h"#include "parquet/schema.h"#include "parquet/types.h"
namespace parquet {
static constexpr ParquetCipher::type kDefaultEncryptionAlgorithm = ParquetCipher::AES_GCM_V1;static constexpr int32_t kMaximalAadMetadataLength = 256;static constexpr bool kDefaultEncryptedFooter = true;static constexpr bool kDefaultCheckSignature = true;static constexpr bool kDefaultAllowPlaintextFiles = false;static constexpr int32_t kAadFileUniqueLength = 8;
class ColumnDecryptionProperties;using ColumnPathToDecryptionPropertiesMap = std::map<std::string, std::shared_ptr<ColumnDecryptionProperties>>;
class ColumnEncryptionProperties;using ColumnPathToEncryptionPropertiesMap = std::map<std::string, std::shared_ptr<ColumnEncryptionProperties>>;
class PARQUET_EXPORT DecryptionKeyRetriever { public: virtual std::string GetKey(const std::string& key_metadata) = 0; virtual ~DecryptionKeyRetriever() {}};
/// Simple integer key retrieverclass PARQUET_EXPORT IntegerKeyIdRetriever : public DecryptionKeyRetriever { public: void PutKey(uint32_t key_id, const std::string& key); std::string GetKey(const std::string& key_metadata) override;
private: std::map<uint32_t, std::string> key_map_;};
// Simple string key retrieverclass PARQUET_EXPORT StringKeyIdRetriever : public DecryptionKeyRetriever { public: void PutKey(const std::string& key_id, const std::string& key); std::string GetKey(const std::string& key_metadata) override;
private: std::map<std::string, std::string> key_map_;};
class PARQUET_EXPORT HiddenColumnException : public ParquetException { public: explicit HiddenColumnException(const std::string& columnPath) : ParquetException(columnPath.c_str()) {}};
class PARQUET_EXPORT KeyAccessDeniedException : public ParquetException { public: explicit KeyAccessDeniedException(const std::string& columnPath) : ParquetException(columnPath.c_str()) {}};
inline const uint8_t* str2bytes(const std::string& str) { if (str.empty()) return NULLPTR;
char* cbytes = const_cast<char*>(str.c_str()); return reinterpret_cast<const uint8_t*>(cbytes);}
inline ::arrow::util::span<const uint8_t> str2span(const std::string& str) { if (str.empty()) { return {}; }
return {reinterpret_cast<const uint8_t*>(str.data()), str.size()};}
class PARQUET_EXPORT ColumnEncryptionProperties { public: class PARQUET_EXPORT Builder { public: /// Convenience builder for encrypted columns. explicit Builder(const std::string& name) : Builder(name, true) {}
/// Convenience builder for encrypted columns. explicit Builder(const std::shared_ptr<schema::ColumnPath>& path) : Builder(path->ToDotString(), true) {}
/// Set a column-specific key. /// If key is not set on an encrypted column, the column will /// be encrypted with the footer key. /// keyBytes Key length must be either 16, 24 or 32 bytes. /// The key is cloned, and will be wiped out (array values set to 0) upon completion /// of file writing. /// Caller is responsible for wiping out the input key array. Builder* key(std::string column_key);
/// Set a key retrieval metadata. /// use either key_metadata() or key_id(), not both Builder* key_metadata(const std::string& key_metadata);
/// A convenience function to set key metadata using a string id. /// Set a key retrieval metadata (converted from String). /// use either key_metadata() or key_id(), not both /// key_id will be converted to metadata (UTF-8 array). Builder* key_id(const std::string& key_id);
std::shared_ptr<ColumnEncryptionProperties> build() { return std::shared_ptr<ColumnEncryptionProperties>( new ColumnEncryptionProperties(encrypted_, column_path_, key_, key_metadata_)); }
private: const std::string column_path_; bool encrypted_; std::string key_; std::string key_metadata_;
Builder(const std::string path, bool encrypted) : column_path_(path), encrypted_(encrypted) {} };
std::string column_path() const { return column_path_; } bool is_encrypted() const { return encrypted_; } bool is_encrypted_with_footer_key() const { return encrypted_with_footer_key_; } std::string key() const { return key_; } std::string key_metadata() const { return key_metadata_; }
/// Upon completion of file writing, the encryption key /// will be wiped out. void WipeOutEncryptionKey() { key_.clear(); }
bool is_utilized() { if (key_.empty()) return false; // can re-use column properties without encryption keys return utilized_; }
/// ColumnEncryptionProperties object can be used for writing one file only. /// Mark ColumnEncryptionProperties as utilized once it is used in /// FileEncryptionProperties as the encryption key will be wiped out upon /// completion of file writing. void set_utilized() { utilized_ = true; }
std::shared_ptr<ColumnEncryptionProperties> DeepClone() { std::string key_copy = key_; return std::shared_ptr<ColumnEncryptionProperties>(new ColumnEncryptionProperties( encrypted_, column_path_, key_copy, key_metadata_)); }
ColumnEncryptionProperties() = default; ColumnEncryptionProperties(const ColumnEncryptionProperties& other) = default; ColumnEncryptionProperties(ColumnEncryptionProperties&& other) = default;
private: const std::string column_path_; bool encrypted_; bool encrypted_with_footer_key_; std::string key_; std::string key_metadata_; bool utilized_; explicit ColumnEncryptionProperties(bool encrypted, const std::string& column_path, const std::string& key, const std::string& key_metadata);};
class PARQUET_EXPORT ColumnDecryptionProperties { public: class PARQUET_EXPORT Builder { public: explicit Builder(const std::string& name) : column_path_(name) {}
explicit Builder(const std::shared_ptr<schema::ColumnPath>& path) : Builder(path->ToDotString()) {}
/// Set an explicit column key. If applied on a file that contains /// key metadata for this column the metadata will be ignored, /// the column will be decrypted with this key. /// key length must be either 16, 24 or 32 bytes. Builder* key(const std::string& key);
std::shared_ptr<ColumnDecryptionProperties> build();
private: const std::string column_path_; std::string key_; };
ColumnDecryptionProperties() = default; ColumnDecryptionProperties(const ColumnDecryptionProperties& other) = default; ColumnDecryptionProperties(ColumnDecryptionProperties&& other) = default;
std::string column_path() const { return column_path_; } std::string key() const { return key_; } bool is_utilized() { return utilized_; }
/// ColumnDecryptionProperties object can be used for reading one file only. /// Mark ColumnDecryptionProperties as utilized once it is used in /// FileDecryptionProperties as the encryption key will be wiped out upon /// completion of file reading. void set_utilized() { utilized_ = true; }
/// Upon completion of file reading, the encryption key /// will be wiped out. void WipeOutDecryptionKey();
std::shared_ptr<ColumnDecryptionProperties> DeepClone();
private: const std::string column_path_; std::string key_; bool utilized_;
/// This class is only required for setting explicit column decryption keys - /// to override key retriever (or to provide keys when key metadata and/or /// key retriever are not available) explicit ColumnDecryptionProperties(const std::string& column_path, const std::string& key);};
class PARQUET_EXPORT AADPrefixVerifier { public: /// Verifies identity (AAD Prefix) of individual file, /// or of file collection in a data set. /// Throws exception if an AAD prefix is wrong. /// In a data set, AAD Prefixes should be collected, /// and then checked for missing files. virtual void Verify(const std::string& aad_prefix) = 0; virtual ~AADPrefixVerifier() {}};
class PARQUET_EXPORT FileDecryptionProperties { public: class PARQUET_EXPORT Builder { public: Builder() { check_plaintext_footer_integrity_ = kDefaultCheckSignature; plaintext_files_allowed_ = kDefaultAllowPlaintextFiles; }
/// Set an explicit footer key. If applied on a file that contains /// footer key metadata the metadata will be ignored, the footer /// will be decrypted/verified with this key. /// If explicit key is not set, footer key will be fetched from /// key retriever. /// With explicit keys or AAD prefix, new encryption properties object must be /// created for each encrypted file. /// Explicit encryption keys (footer and column) are cloned. /// Upon completion of file reading, the cloned encryption keys in the properties /// will be wiped out (array values set to 0). /// Caller is responsible for wiping out the input key array. /// param footerKey Key length must be either 16, 24 or 32 bytes. Builder* footer_key(const std::string footer_key);
/// Set explicit column keys (decryption properties). /// Its also possible to set a key retriever on this property object. /// Upon file decryption, availability of explicit keys is checked before /// invocation of the retriever callback. /// If an explicit key is available for a footer or a column, /// its key metadata will be ignored. Builder* column_keys( const ColumnPathToDecryptionPropertiesMap& column_decryption_properties);
/// Set a key retriever callback. Its also possible to /// set explicit footer or column keys on this file property object. /// Upon file decryption, availability of explicit keys is checked before /// invocation of the retriever callback. /// If an explicit key is available for a footer or a column, /// its key metadata will be ignored. Builder* key_retriever(const std::shared_ptr<DecryptionKeyRetriever>& key_retriever);
/// Skip integrity verification of plaintext footers. /// If not called, integrity of plaintext footers will be checked in runtime, /// and an exception will be thrown in the following situations: /// - footer signing key is not available /// (not passed, or not found by key retriever) /// - footer content and signature don't match Builder* disable_footer_signature_verification() { check_plaintext_footer_integrity_ = false; return this; }
/// Explicitly supply the file AAD prefix. /// A must when a prefix is used for file encryption, but not stored in file. /// If AAD prefix is stored in file, it will be compared to the explicitly /// supplied value and an exception will be thrown if they differ. Builder* aad_prefix(const std::string& aad_prefix);
/// Set callback for verification of AAD Prefixes stored in file. Builder* aad_prefix_verifier(std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier);
/// By default, reading plaintext (unencrypted) files is not /// allowed when using a decryptor /// - in order to detect files that were not encrypted by mistake. /// However, the default behavior can be overridden by calling this method. /// The caller should use then a different method to ensure encryption /// of files with sensitive data. Builder* plaintext_files_allowed() { plaintext_files_allowed_ = true; return this; }
std::shared_ptr<FileDecryptionProperties> build() { return std::shared_ptr<FileDecryptionProperties>(new FileDecryptionProperties( footer_key_, key_retriever_, check_plaintext_footer_integrity_, aad_prefix_, aad_prefix_verifier_, column_decryption_properties_, plaintext_files_allowed_)); }
private: std::string footer_key_; std::string aad_prefix_; std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier_; ColumnPathToDecryptionPropertiesMap column_decryption_properties_;
std::shared_ptr<DecryptionKeyRetriever> key_retriever_; bool check_plaintext_footer_integrity_; bool plaintext_files_allowed_; };
std::string column_key(const std::string& column_path) const;
std::string footer_key() const { return footer_key_; }
std::string aad_prefix() const { return aad_prefix_; }
const std::shared_ptr<DecryptionKeyRetriever>& key_retriever() const { return key_retriever_; }
bool check_plaintext_footer_integrity() const { return check_plaintext_footer_integrity_; }
bool plaintext_files_allowed() const { return plaintext_files_allowed_; }
const std::shared_ptr<AADPrefixVerifier>& aad_prefix_verifier() const { return aad_prefix_verifier_; }
/// Upon completion of file reading, the encryption keys in the properties /// will be wiped out (array values set to 0). void WipeOutDecryptionKeys();
bool is_utilized();
/// FileDecryptionProperties object can be used for reading one file only. /// Mark FileDecryptionProperties as utilized once it is used to read a file as the /// encryption keys will be wiped out upon completion of file reading. void set_utilized() { utilized_ = true; }
/// FileDecryptionProperties object can be used for reading one file only. /// (unless this object keeps the keyRetrieval callback only, and no explicit /// keys or aadPrefix). /// At the end, keys are wiped out in the memory. /// This method allows to clone identical properties for another file, /// with an option to update the aadPrefix (if newAadPrefix is null, /// aadPrefix will be cloned too) std::shared_ptr<FileDecryptionProperties> DeepClone(std::string new_aad_prefix = "");
private: std::string footer_key_; std::string aad_prefix_; std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier_;
const std::string empty_string_ = ""; ColumnPathToDecryptionPropertiesMap column_decryption_properties_;
std::shared_ptr<DecryptionKeyRetriever> key_retriever_; bool check_plaintext_footer_integrity_; bool plaintext_files_allowed_; bool utilized_;
FileDecryptionProperties( const std::string& footer_key, std::shared_ptr<DecryptionKeyRetriever> key_retriever, bool check_plaintext_footer_integrity, const std::string& aad_prefix, std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier, const ColumnPathToDecryptionPropertiesMap& column_decryption_properties, bool plaintext_files_allowed);};
class PARQUET_EXPORT FileEncryptionProperties { public: class PARQUET_EXPORT Builder { public: explicit Builder(const std::string& footer_key) : parquet_cipher_(kDefaultEncryptionAlgorithm), encrypted_footer_(kDefaultEncryptedFooter) { footer_key_ = footer_key; store_aad_prefix_in_file_ = false; }
/// Create files with plaintext footer. /// If not called, the files will be created with encrypted footer (default). Builder* set_plaintext_footer() { encrypted_footer_ = false; return this; }
/// Set encryption algorithm. /// If not called, files will be encrypted with AES_GCM_V1 (default). Builder* algorithm(ParquetCipher::type parquet_cipher) { parquet_cipher_ = parquet_cipher; return this; }
/// Set a key retrieval metadata (converted from String). /// use either footer_key_metadata or footer_key_id, not both. Builder* footer_key_id(const std::string& key_id);
/// Set a key retrieval metadata. /// use either footer_key_metadata or footer_key_id, not both. Builder* footer_key_metadata(const std::string& footer_key_metadata);
/// Set the file AAD Prefix. Builder* aad_prefix(const std::string& aad_prefix);
/// Skip storing AAD Prefix in file. /// If not called, and if AAD Prefix is set, it will be stored. Builder* disable_aad_prefix_storage();
/// Set the list of encrypted columns and their properties (keys etc). /// If not called, all columns will be encrypted with the footer key. /// If called, the file columns not in the list will be left unencrypted. Builder* encrypted_columns( const ColumnPathToEncryptionPropertiesMap& encrypted_columns);
std::shared_ptr<FileEncryptionProperties> build() { return std::shared_ptr<FileEncryptionProperties>(new FileEncryptionProperties( parquet_cipher_, footer_key_, footer_key_metadata_, encrypted_footer_, aad_prefix_, store_aad_prefix_in_file_, encrypted_columns_)); }
private: ParquetCipher::type parquet_cipher_; bool encrypted_footer_; std::string footer_key_; std::string footer_key_metadata_;
std::string aad_prefix_; bool store_aad_prefix_in_file_; ColumnPathToEncryptionPropertiesMap encrypted_columns_; }; bool encrypted_footer() const { return encrypted_footer_; }
EncryptionAlgorithm algorithm() const { return algorithm_; }
std::string footer_key() const { return footer_key_; }
std::string footer_key_metadata() const { return footer_key_metadata_; }
std::string file_aad() const { return file_aad_; }
std::shared_ptr<ColumnEncryptionProperties> column_encryption_properties( const std::string& column_path);
bool is_utilized() const { return utilized_; }
/// FileEncryptionProperties object can be used for writing one file only. /// Mark FileEncryptionProperties as utilized once it is used to write a file as the /// encryption keys will be wiped out upon completion of file writing. void set_utilized() { utilized_ = true; }
/// Upon completion of file writing, the encryption keys /// will be wiped out (array values set to 0). void WipeOutEncryptionKeys();
/// FileEncryptionProperties object can be used for writing one file only. /// (at the end, keys are wiped out in the memory). /// This method allows to clone identical properties for another file, /// with an option to update the aadPrefix (if newAadPrefix is null, /// aadPrefix will be cloned too) std::shared_ptr<FileEncryptionProperties> DeepClone(std::string new_aad_prefix = "");
ColumnPathToEncryptionPropertiesMap encrypted_columns() const { return encrypted_columns_; }
private: EncryptionAlgorithm algorithm_; std::string footer_key_; std::string footer_key_metadata_; bool encrypted_footer_; std::string file_aad_; std::string aad_prefix_; bool utilized_; bool store_aad_prefix_in_file_; ColumnPathToEncryptionPropertiesMap encrypted_columns_;
FileEncryptionProperties(ParquetCipher::type cipher, const std::string& footer_key, const std::string& footer_key_metadata, bool encrypted_footer, const std::string& aad_prefix, bool store_aad_prefix_in_file, const ColumnPathToEncryptionPropertiesMap& encrypted_columns);};
} // namespace parquet123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657// 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.
#pragma once
#include <set>#include <string>#include <unordered_map>
#include "arrow/filesystem/filesystem.h"#include "parquet/platform.h"
namespace parquet::encryption {
/// Stores encryption key material outside the Parquet file, for example in a separate/// small file in the same folder. This is important for “key rotation”, when MEKs have to/// be changed (if compromised; or periodically, just in case) - without modifying the/// Parquet files (often immutable).class PARQUET_EXPORT FileKeyMaterialStore { public: /// Add key material for one encryption key. virtual void AddKeyMaterial(std::string key_id_in_file, std::string key_material) = 0;
/// Get key material virtual std::string GetKeyMaterial(std::string key_id_in_file) = 0;
/// After key material was added for all keys in the given Parquet file, /// save material in persistent store. virtual void SaveMaterial() = 0;
/// Remove key material from persistent store. Used in key rotation. virtual void RemoveMaterial() = 0;
/// Move key material to another store. Used in key rotation. virtual void MoveMaterialTo(std::shared_ptr<FileKeyMaterialStore> target_key_store) = 0;
/// Returns the Set of all key IDs in this store (for the given Parquet file) virtual std::vector<std::string> GetKeyIDSet() = 0;
virtual ~FileKeyMaterialStore() {}};
} // namespace parquet::encryption12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394// 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.
#pragma once
#include "arrow/util/concurrent_map.h"
#include "parquet/encryption/encryption.h"#include "parquet/encryption/file_system_key_material_store.h"#include "parquet/encryption/key_material.h"#include "parquet/encryption/key_toolkit.h"#include "parquet/encryption/key_toolkit_internal.h"#include "parquet/encryption/kms_client.h"#include "parquet/platform.h"
namespace parquet::encryption {
// This class will retrieve the key from "key metadata", following these steps:// 1. Parse "key metadata" (see structure in KeyMetadata class).// 2. Retrieve "key material" which can be stored inside or outside "key metadata".// 3. Unwrap the "data encryption key" from "key material". There are 2 modes:// 3.1. single wrapping: decrypt the wrapped "data encryption key" directly with "master// encryption key" 3.2. double wrapping: 2 steps: 3.2.1. "key encryption key" is decrypted// with "master encryption key" 3.2.2. "data encryption key" is decrypted with the above// "key encryption key"class PARQUET_EXPORT FileKeyUnwrapper : public DecryptionKeyRetriever { public: /// key_toolkit and kms_connection_config is to get KmsClient from cache or create /// KmsClient if it's not in the cache yet. cache_entry_lifetime_seconds is life time of /// KmsClient in the cache. /// If the file uses external key material then the Parquet file path and file /// system must be specified. FileKeyUnwrapper(std::shared_ptr<KeyToolkit> key_toolkit, const KmsConnectionConfig& kms_connection_config, double cache_lifetime_seconds, const std::string& file_path = "", const std::shared_ptr<::arrow::fs::FileSystem>& file_system = NULLPTR);
/// Constructor overload that takes a raw pointer to the KeyToolkit FileKeyUnwrapper(KeyToolkit* key_toolkit, const KmsConnectionConfig& kms_connection_config, double cache_lifetime_seconds, const std::string& file_path = "", const std::shared_ptr<::arrow::fs::FileSystem>& file_system = NULLPTR);
/// Constructor overload that takes a raw pointer to the KeyToolkit and /// accepts an existing key_material_store rather than using /// the file path and file system to create one when needed. FileKeyUnwrapper(KeyToolkit* key_toolkit, const KmsConnectionConfig& kms_connection_config, double cache_lifetime_seconds, std::shared_ptr<FileKeyMaterialStore> key_material_store);
/// Get the data key from key metadata std::string GetKey(const std::string& key_metadata) override;
/// Get the data key along with the master key id from key material KeyWithMasterId GetDataEncryptionKey(const KeyMaterial& key_material);
private: FileKeyUnwrapper(std::shared_ptr<KeyToolkit> key_toolkit_owner, KeyToolkit* key_toolkit, const KmsConnectionConfig& kms_connection_config, double cache_lifetime_seconds, std::shared_ptr<FileKeyMaterialStore> key_material_store, const std::string& file_path, const std::shared_ptr<::arrow::fs::FileSystem>& file_system);
std::shared_ptr<KmsClient> GetKmsClientFromConfigOrKeyMaterial( const KeyMaterial& key_material);
/// A map of Key Encryption Key (KEK) ID -> KEK bytes, for the current token std::shared_ptr<::arrow::util::ConcurrentMap<std::string, std::string>> kek_per_kek_id_; std::shared_ptr<KeyToolkit> key_toolkit_owner_; KeyToolkit* key_toolkit_; KmsConnectionConfig kms_connection_config_; const double cache_entry_lifetime_seconds_; std::shared_ptr<FileKeyMaterialStore> key_material_store_; const std::string file_path_; std::shared_ptr<::arrow::fs::FileSystem> file_system_;};
} // namespace parquet::encryption123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384// 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.
#pragma once
#include <memory>#include <string>#include <unordered_map>
#include "arrow/util/concurrent_map.h"
#include "parquet/encryption/file_key_material_store.h"#include "parquet/encryption/key_encryption_key.h"#include "parquet/encryption/key_toolkit.h"#include "parquet/encryption/kms_client.h"#include "parquet/platform.h"
namespace parquet::encryption {
// This class will generate "key metadata" from "data encryption key" and "master key",// following these steps:// 1. Wrap "data encryption key". There are 2 modes:// 1.1. single wrapping: encrypt "data encryption key" directly with "master encryption// key"// 1.2. double wrapping: 2 steps:// 1.2.1. "key encryption key" is randomized (see KeyEncryptionKey class)// 1.2.2. "data encryption key" is encrypted with the above "key encryption key"// 2. Create "key material" (see structure in KeyMaterial class)// 3. Create "key metadata" with "key material" inside or a reference to outside "key// material" (see structure in KeyMetadata class).class PARQUET_EXPORT FileKeyWrapper { public: static constexpr int kKeyEncryptionKeyLength = 16; static constexpr int kKeyEncryptionKeyIdLength = 16;
/// key_toolkit and kms_connection_config is to get KmsClient from the cache or create /// KmsClient if it's not in the cache yet. cache_entry_lifetime_seconds is life time of /// KmsClient in the cache. key_material_store is to store "key material" outside /// parquet file, NULL if "key material" is stored inside parquet file. FileKeyWrapper(KeyToolkit* key_toolkit, const KmsConnectionConfig& kms_connection_config, std::shared_ptr<FileKeyMaterialStore> key_material_store, double cache_entry_lifetime_seconds, bool double_wrapping);
/// Creates key_metadata field for a given data key, via wrapping the key with the /// master key. /// When external key material is used, an identifier is usually generated automatically /// but may be specified explicitly to support key rotation, /// which requires keeping the same identifiers. std::string GetEncryptionKeyMetadata(const std::string& data_key, const std::string& master_key_id, bool is_footer_key, std::string key_id_in_file = "");
private: KeyEncryptionKey CreateKeyEncryptionKey(const std::string& master_key_id);
/// A map of Master Encryption Key ID -> KeyEncryptionKey, for the current token std::shared_ptr<::arrow::util::ConcurrentMap<std::string, KeyEncryptionKey>> kek_per_master_key_id_;
std::shared_ptr<KmsClient> kms_client_; KmsConnectionConfig kms_connection_config_; std::shared_ptr<FileKeyMaterialStore> key_material_store_; const double cache_entry_lifetime_seconds_; const bool double_wrapping_; uint16_t key_counter_;};
} // namespace parquet::encryption1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889// 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.
#pragma once
#include <set>#include <string>#include <unordered_map>
#include "arrow/filesystem/filesystem.h"
#include "parquet/encryption/file_key_material_store.h"
namespace parquet::encryption {
/// A FileKeyMaterialStore that stores key material in a file system file in the same/// folder as the Parquet file.class PARQUET_EXPORT FileSystemKeyMaterialStore : public FileKeyMaterialStore { public: static constexpr const char kKeyMaterialFilePrefix[] = "_KEY_MATERIAL_FOR_"; static constexpr const char kTempFilePrefix[] = "_TMP"; static constexpr const char kKeyMaterialFileSuffix[] = ".json";
FileSystemKeyMaterialStore() {} FileSystemKeyMaterialStore(const std::string& key_material_file_path, const std::shared_ptr<::arrow::fs::FileSystem>& file_system);
/// Creates a new file system key material store for a parquet file. /// When use_tmp_prefix is true, files are saved with an extra _TMP prefix so they don't /// conflict with existing external material files. This is useful during key rotation /// so that temporary key material files can be created while using the existing key /// material, before moving the key material to the non-temporary location. static std::shared_ptr<FileSystemKeyMaterialStore> Make( const std::string& parquet_file_path, const std::shared_ptr<::arrow::fs::FileSystem>& file_system, bool use_tmp_prefix);
/// Add key material for one encryption key. void AddKeyMaterial(std::string key_id_in_file, std::string key_material) { key_material_map_.insert({key_id_in_file, key_material}); }
/// Get key material std::string GetKeyMaterial(std::string key_id_in_file) { if (key_material_map_.empty()) { LoadKeyMaterialMap(); } auto found = key_material_map_.find(key_id_in_file); return found->second; }
/// After key material was added for all keys in the given Parquet file, /// save material in persistent store. void SaveMaterial();
/// Remove key material from persistent store. Used in key rotation. void RemoveMaterial();
/// Move key material to another store. Used in key rotation. void MoveMaterialTo(std::shared_ptr<FileKeyMaterialStore> target_key_store);
/// Returns the Set of all key IDs in this store (for the given Parquet file) std::vector<std::string> GetKeyIDSet();
private: std::string GetStorageFilePath() { return key_material_file_path_; }
std::string BuildKeyMaterialMapJson(); void LoadKeyMaterialMap(); std::string key_material_file_path_; std::shared_ptr<::arrow::fs::FileSystem> file_system_; /// Maps ID of a key in Parquet file and key material std::unordered_map<std::string, std::string> key_material_map_;};
} // namespace parquet::encryption123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657// 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.
#pragma once
#include <cstdint>#include <vector>
#include "arrow/util/base64.h"
namespace parquet::encryption {
// In the double wrapping mode, each "data encryption key" (DEK) is encrypted with a “key// encryption key” (KEK), that in turn is encrypted with a "master encryption key" (MEK).// In a writer process, a random KEK is generated for each MEK ID, and cached in a <MEK-ID// : KEK> map. This allows to perform an interaction with a KMS server only once for each// MEK, in order to wrap its KEK. "Data encryption key" (DEK) wrapping is performed// locally, and does not involve an interaction with a KMS server.class KeyEncryptionKey { public: KeyEncryptionKey(std::string kek_bytes, std::string kek_id, std::string encoded_wrapped_kek) : kek_bytes_(std::move(kek_bytes)), kek_id_(std::move(kek_id)), encoded_kek_id_(::arrow::util::base64_encode(kek_id_)), encoded_wrapped_kek_(std::move(encoded_wrapped_kek)) {}
const std::string& kek_bytes() const { return kek_bytes_; }
const std::string& kek_id() const { return kek_id_; }
const std::string& encoded_kek_id() const { return encoded_kek_id_; }
const std::string& encoded_wrapped_kek() const { return encoded_wrapped_kek_; }
private: std::string kek_bytes_; std::string kek_id_; std::string encoded_kek_id_; std::string encoded_wrapped_kek_;};
} // namespace parquet::encryption123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129// 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.
#pragma once
#include <string>
#include "parquet/platform.h"
namespace arrow {namespace json {namespace internal {class ObjectParser;} // namespace internal} // namespace json} // namespace arrow
namespace parquet::encryption {
// KeyMaterial class represents the "key material", keeping the information that allows// readers to recover an encryption key (see description of the KeyMetadata class). The// keytools package (PARQUET-1373) implements the "envelope encryption" pattern, in a// "single wrapping" or "double wrapping" mode. In the single wrapping mode, the key// material is generated by encrypting the "data encryption key" (DEK) by a "master key".// In the double wrapping mode, the key material is generated by encrypting the DEK by a// "key encryption key" (KEK), that in turn is encrypted by a "master key".//// Key material is kept in a flat json object, with the following fields:// 1. "keyMaterialType" - a String, with the type of key material. In the current// version, only one value is allowed - "PKMT1" (stands// for "parquet key management tools, version 1"). For external key material storage,// this field is written in both "key metadata" and "key material" jsons. For internal// key material storage, this field is written only once in the common json.// 2. "isFooterKey" - a boolean. If true, means that the material belongs to a file footer// key, and keeps additional information (such as// KMS instance ID and URL). If false, means that the material belongs to a column// key.// 3. "kmsInstanceID" - a String, with the KMS Instance ID. Written only in footer key// material.// 4. "kmsInstanceURL" - a String, with the KMS Instance URL. Written only in footer key// material.// 5. "masterKeyID" - a String, with the ID of the master key used to generate the// material.// 6. "wrappedDEK" - a String, with the wrapped DEK (base64 encoding).// 7. "doubleWrapping" - a boolean. If true, means that the material was generated in// double wrapping mode.// If false - in single wrapping mode.// 8. "keyEncryptionKeyID" - a String, with the ID of the KEK used to generate the// material. Written only in double wrapping mode.// 9. "wrappedKEK" - a String, with the wrapped KEK (base64 encoding). Written only in// double wrapping mode.class PARQUET_EXPORT KeyMaterial { public: // these fields are defined in a specification and should never be changed static constexpr const char kKeyMaterialTypeField[] = "keyMaterialType"; static constexpr const char kKeyMaterialType1[] = "PKMT1";
static constexpr const char kFooterKeyIdInFile[] = "footerKey"; static constexpr const char kColumnKeyIdInFilePrefix[] = "columnKey";
static constexpr const char kIsFooterKeyField[] = "isFooterKey"; static constexpr const char kDoubleWrappingField[] = "doubleWrapping"; static constexpr const char kKmsInstanceIdField[] = "kmsInstanceID"; static constexpr const char kKmsInstanceUrlField[] = "kmsInstanceURL"; static constexpr const char kMasterKeyIdField[] = "masterKeyID"; static constexpr const char kWrappedDataEncryptionKeyField[] = "wrappedDEK"; static constexpr const char kKeyEncryptionKeyIdField[] = "keyEncryptionKeyID"; static constexpr const char kWrappedKeyEncryptionKeyField[] = "wrappedKEK";
public: KeyMaterial() = default;
static KeyMaterial Parse(const std::string& key_material_string);
static KeyMaterial Parse( const ::arrow::json::internal::ObjectParser* key_material_json);
/// This method returns a json string that will be stored either inside a parquet file /// or in a key material store outside the parquet file. static std::string SerializeToJson(bool is_footer_key, const std::string& kms_instance_id, const std::string& kms_instance_url, const std::string& master_key_id, bool is_double_wrapped, const std::string& kek_id, const std::string& encoded_wrapped_kek, const std::string& encoded_wrapped_dek, bool is_internal_storage);
bool is_footer_key() const { return is_footer_key_; } bool is_double_wrapped() const { return is_double_wrapped_; } const std::string& master_key_id() const { return master_key_id_; } const std::string& wrapped_dek() const { return encoded_wrapped_dek_; } const std::string& kek_id() const { return kek_id_; } const std::string& wrapped_kek() const { return encoded_wrapped_kek_; } const std::string& kms_instance_id() const { return kms_instance_id_; } const std::string& kms_instance_url() const { return kms_instance_url_; }
private: KeyMaterial(bool is_footer_key, const std::string& kms_instance_id, const std::string& kms_instance_url, const std::string& master_key_id, bool is_double_wrapped, const std::string& kek_id, const std::string& encoded_wrapped_kek, const std::string& encoded_wrapped_dek);
bool is_footer_key_; std::string kms_instance_id_; std::string kms_instance_url_; std::string master_key_id_; bool is_double_wrapped_; std::string kek_id_; std::string encoded_wrapped_kek_; std::string encoded_wrapped_dek_;};
} // namespace parquet::encryption12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091// 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.
#pragma once
#include <string>#include <variant>
#include "parquet/encryption/key_material.h"#include "parquet/exception.h"#include "parquet/platform.h"
namespace parquet::encryption {
// Parquet encryption specification defines "key metadata" as an arbitrary byte array,// generated by file writers for each encryption key, and passed to the low level API for// storage in the file footer. The "key metadata" field is made available to file readers// to enable recovery of the key. This interface can be utilized for implementation// of any key management scheme.//// The keytools package (PARQUET-1373) implements one approach, of many possible, to key// management and to generation of the "key metadata" fields. This approach, based on the// "envelope encryption" pattern, allows integration with KMS servers. It keeps the actual// material, required to recover a key, in a "key material" object (see the KeyMaterial// class for details). This class is implemented to support version 1 of the parquet key// management tools specification.//// KeyMetadata writes (and reads) the "key metadata" field as a flat json object,// with the following fields:// 1. "keyMaterialType" - a String, with the type of key material.// 2. "internalStorage" - a boolean. If true, means that "key material" is kept inside the// "key metadata" field. If false, "key material" is kept externally (outside Parquet// files) - in this case, "key metadata" keeps a reference to the external "key material".// 3. "keyReference" - a String, with the reference to the external "key material".// Written only if internalStorage is false.//// If internalStorage is true, "key material" is a part of "key metadata", and the json// keeps additional fields, described in the KeyMaterial class.class PARQUET_EXPORT KeyMetadata { public: static constexpr const char kKeyMaterialInternalStorageField[] = "internalStorage"; static constexpr const char kKeyReferenceField[] = "keyReference";
/// key_metadata_bytes is the key metadata field stored in the parquet file, /// in the serialized json object format. static KeyMetadata Parse(const std::string& key_metadata_bytes);
static std::string CreateSerializedForExternalMaterial( const std::string& key_reference);
bool key_material_stored_internally() const { return is_internal_storage_; }
const KeyMaterial& key_material() const { if (!is_internal_storage_) { throw ParquetException("key material is stored externally."); } return ::std::get<KeyMaterial>(key_material_or_reference_); }
const std::string& key_reference() const { if (is_internal_storage_) { throw ParquetException("key material is stored internally."); } return ::std::get<std::string>(key_material_or_reference_); }
private: explicit KeyMetadata(const KeyMaterial& key_material); explicit KeyMetadata(const std::string& key_reference);
bool is_internal_storage_; /// If is_internal_storage_ is true, KeyMaterial is set, /// else a string referencing to an outside "key material" is set. ::std::variant<KeyMaterial, std::string> key_material_or_reference_;};
} // namespace parquet::encryption123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106// 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.
#pragma once
#include <memory>#include <string>
#include "parquet/encryption/key_encryption_key.h"#include "parquet/encryption/kms_client.h"#include "parquet/encryption/kms_client_factory.h"#include "parquet/encryption/two_level_cache_with_expiration.h"#include "parquet/platform.h"
namespace parquet::encryption {
static constexpr uint64_t kCacheCleanPeriodForKeyRotation = 60 * 60; // 1 hour
// KeyToolkit is a utility that keeps various tools for key management (such as key// rotation, kms client instantiation, cache control, etc), plus a number of auxiliary// classes for internal use.class PARQUET_EXPORT KeyToolkit { public: KeyToolkit() { last_cache_clean_for_key_rotation_time_ = {}; }
/// KMS client two level cache: token -> KMSInstanceId -> KmsClient TwoLevelCacheWithExpiration<std::shared_ptr<KmsClient>>& kms_client_cache_per_token() { return kms_client_cache_; } /// Key encryption key two level cache for wrapping: token -> MasterEncryptionKeyId -> /// KeyEncryptionKey TwoLevelCacheWithExpiration<KeyEncryptionKey>& kek_write_cache_per_token() { return key_encryption_key_write_cache_; }
/// Key encryption key two level cache for unwrapping: token -> KeyEncryptionKeyId -> /// KeyEncryptionKeyBytes TwoLevelCacheWithExpiration<std::string>& kek_read_cache_per_token() { return key_encryption_key_read_cache_; }
std::shared_ptr<KmsClient> GetKmsClient( const KmsConnectionConfig& kms_connection_config, double cache_entry_lifetime_ms);
/// Flush any caches that are tied to the (compromised) access_token void RemoveCacheEntriesForToken(const std::string& access_token);
void RemoveCacheEntriesForAllTokens();
void RegisterKmsClientFactory(std::shared_ptr<KmsClientFactory> kms_client_factory) { if (kms_client_factory_ != NULLPTR) { throw ParquetException("KMS client factory has already been registered."); } kms_client_factory_ = std::move(kms_client_factory); }
/// Key rotation. In the single wrapping mode, decrypts data keys with old master keys, /// then encrypts them with new master keys. In the double wrapping mode, decrypts KEKs /// (key encryption keys) with old master keys, generates new KEKs and encrypts them /// with new master keys. Works only if key material is not stored internally in file /// footers. Not supported in local key wrapping mode. Method can be run by multiple /// threads, but each thread must work on different files. void RotateMasterKeys(const KmsConnectionConfig& kms_connection_config, const std::string& parquet_file_path, const std::shared_ptr<::arrow::fs::FileSystem>& file_system, bool double_wrapping, double cache_lifetime_seconds);
private: TwoLevelCacheWithExpiration<std::shared_ptr<KmsClient>> kms_client_cache_; TwoLevelCacheWithExpiration<KeyEncryptionKey> key_encryption_key_write_cache_; TwoLevelCacheWithExpiration<std::string> key_encryption_key_read_cache_; std::shared_ptr<KmsClientFactory> kms_client_factory_; mutable ::arrow::util::Mutex last_cache_clean_for_key_rotation_time_mutex_; internal::TimePoint last_cache_clean_for_key_rotation_time_;};
// "data encryption key" and "master key identifier" are paired together as output when// parsing from "key material"class PARQUET_EXPORT KeyWithMasterId { public: KeyWithMasterId(std::string key_bytes, std::string master_id) : key_bytes_(std::move(key_bytes)), master_id_(std::move(master_id)) {}
const std::string& data_key() const { return key_bytes_; } const std::string& master_id() const { return master_id_; }
private: const std::string key_bytes_; const std::string master_id_;};
} // namespace parquet::encryption123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293// 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.
#pragma once
#include <memory>#include <string>#include <unordered_map>
#include "arrow/util/mutex.h"
#include "parquet/exception.h"#include "parquet/platform.h"
namespace parquet::encryption {
/// This class wraps the key access token of a KMS server. If your token changes over/// time, you should keep the reference to the KeyAccessToken object and call Refresh()/// method every time you have a new token.class PARQUET_EXPORT KeyAccessToken { public: KeyAccessToken() = default;
explicit KeyAccessToken(const std::string value) : value_(value) {}
void Refresh(const std::string& new_value) { auto lock = mutex_.Lock(); value_ = new_value; }
const std::string& value() const { auto lock = mutex_.Lock(); return value_; }
private: std::string value_; mutable ::arrow::util::Mutex mutex_;};
struct PARQUET_EXPORT KmsConnectionConfig { std::string kms_instance_id; std::string kms_instance_url; /// If the access token is changed in the future, you should keep a reference to /// this object and call Refresh() on it whenever there is a new access token. std::shared_ptr<KeyAccessToken> refreshable_key_access_token; std::unordered_map<std::string, std::string> custom_kms_conf;
KmsConnectionConfig();
const std::string& key_access_token() const { if (refreshable_key_access_token == NULLPTR || refreshable_key_access_token->value().empty()) { throw ParquetException("key access token is not set!"); } return refreshable_key_access_token->value(); }
void SetDefaultIfEmpty();};
class PARQUET_EXPORT KmsClient { public: static constexpr const char kKmsInstanceIdDefault[] = "DEFAULT"; static constexpr const char kKmsInstanceUrlDefault[] = "DEFAULT"; static constexpr const char kKeyAccessTokenDefault[] = "DEFAULT";
/// Wraps a key - encrypts it with the master key, encodes the result /// and potentially adds a KMS-specific metadata. virtual std::string WrapKey(const std::string& key_bytes, const std::string& master_key_identifier) = 0;
/// Decrypts (unwraps) a key with the master key. virtual std::string UnwrapKey(const std::string& wrapped_key, const std::string& master_key_identifier) = 0; virtual ~KmsClient() {}};
} // namespace parquet::encryption1234567891011121314151617181920212223242526272829303132333435363738// 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.
#pragma once
#include "parquet/encryption/kms_client.h"#include "parquet/platform.h"
namespace parquet::encryption {
class PARQUET_EXPORT KmsClientFactory { public: explicit KmsClientFactory(bool wrap_locally = false) : wrap_locally_(wrap_locally) {}
virtual ~KmsClientFactory() = default;
virtual std::shared_ptr<KmsClient> CreateKmsClient( const KmsConnectionConfig& kms_connection_config) = 0;
protected: bool wrap_locally_;};
} // namespace parquet::encryption12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394// 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.
#pragma once
#include <unordered_map>#include <vector>
#include "arrow/util/concurrent_map.h"
#include "parquet/encryption/kms_client.h"#include "parquet/platform.h"
namespace parquet::encryption {
/// This class supports local wrapping mode, master keys will be fetched from the KMS/// server and used to encrypt other keys (data encryption keys or key encryption keys).class PARQUET_EXPORT LocalWrapKmsClient : public KmsClient { public: static constexpr const char kLocalWrapNoKeyVersion[] = "NO_VERSION";
explicit LocalWrapKmsClient(const KmsConnectionConfig& kms_connection_config);
std::string WrapKey(const std::string& key_bytes, const std::string& master_key_identifier) override;
std::string UnwrapKey(const std::string& wrapped_key, const std::string& master_key_identifier) override;
protected: /// Get master key from the remote KMS server. /// Note: this function might be called by multiple threads virtual std::string GetMasterKeyFromServer( const std::string& master_key_identifier) = 0;
private: /// KMS systems wrap keys by encrypting them by master keys, and attaching additional /// information (such as the version number of the masker key) to the result of /// encryption. The master key version is required in key rotation. Currently, the /// local wrapping mode does not support key rotation (because not all KMS systems allow /// to fetch a master key by its ID and version number). Still, the local wrapping mode /// adds a placeholder for the master key version, that will enable support for key /// rotation in this mode in the future, with appropriate KMS systems. This will also /// enable backward compatibility, where future readers will be able to extract master /// key version in the files written by the current code. /// /// LocalKeyWrap class writes (and reads) the "key wrap" as a flat json with the /// following fields: /// 1. "masterKeyVersion" - a String, with the master key version. In the current /// version, only one value is allowed - "NO_VERSION". /// 2. "encryptedKey" - a String, with the key encrypted by the master key /// (base64-encoded). class LocalKeyWrap { public: static constexpr const char kLocalWrapKeyVersionField[] = "masterKeyVersion"; static constexpr const char kLocalWrapEncryptedKeyField[] = "encryptedKey";
LocalKeyWrap(std::string master_key_version, std::string encrypted_encoded_key);
static std::string CreateSerialized(const std::string& encrypted_encoded_key);
static LocalKeyWrap Parse(const std::string& wrapped_key);
const std::string& master_key_version() const { return master_key_version_; }
const std::string& encrypted_encoded_key() const { return encrypted_encoded_key_; }
private: std::string encrypted_encoded_key_; std::string master_key_version_; };
std::string GetKeyFromServer(const std::string& key_identifier);
protected: KmsConnectionConfig kms_connection_config_; ::arrow::util::ConcurrentMap<std::string, std::string> master_key_cache_;};
} // namespace parquet::encryption123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133// 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.
// This module defines an abstract interface for iterating through pages in a// Parquet column chunk within a row group. It could be extended in the future// to iterate through all data pages in all chunks in a file.
#pragma once
#include <memory>#include <string>#include <unordered_map>
#include <gtest/gtest.h>
#include "arrow/filesystem/filesystem.h"#include "arrow/filesystem/localfs.h"#include "arrow/status.h"#include "arrow/util/io_util.h"
#include "parquet/encryption/encryption.h"#include "parquet/test_util.h"
namespace parquet {class ParquetFileReader;namespace encryption::test {
using ::arrow::internal::TemporaryDir;
constexpr int kFixedLength = 10;
const char kFooterEncryptionKey[] = "0123456789012345"; // 128bit/16const char kColumnEncryptionKey1[] = "1234567890123450";const char kColumnEncryptionKey2[] = "1234567890123451";const char kFileName[] = "tester";
// Get the path of file inside parquet test data directorystd::string data_file(const char* file);
// A temporary directory that contains the encrypted files generated in the tests.extern std::unique_ptr<TemporaryDir> temp_dir;
inline ::arrow::Result<std::unique_ptr<TemporaryDir>> temp_data_dir() { return TemporaryDir::Make("parquet-encryption-test-");}
const char kDoubleFieldName[] = "double_field";const char kFloatFieldName[] = "float_field";const char kBooleanFieldName[] = "boolean_field";const char kInt32FieldName[] = "int32_field";const char kInt64FieldName[] = "int64_field";const char kInt96FieldName[] = "int96_field";const char kByteArrayFieldName[] = "ba_field";const char kFixedLenByteArrayFieldName[] = "flba_field";
const char kFooterMasterKey[] = "0123456789012345";const char kFooterMasterKeyId[] = "kf";const char* const kColumnMasterKeys[] = {"1234567890123450", "1234567890123451", "1234567890123452", "1234567890123453", "1234567890123454", "1234567890123455"};const char* const kColumnMasterKeyIds[] = {"kc1", "kc2", "kc3", "kc4", "kc5", "kc6"};
// New master key values used to simulate key rotationconst char kNewFooterMasterKey[] = "9123456789012345";const char* const kNewColumnMasterKeys[] = {"9234567890123450", "9234567890123451", "9234567890123452", "9234567890123453", "9234567890123454", "9234567890123455"};
// The result of this function will be used to set into TestOnlyInMemoryKmsClientFactory// as the key mapping to look at.std::unordered_map<std::string, std::string> BuildKeyMap(const char* const* column_ids, const char* const* column_keys, const char* footer_id, const char* footer_key);
// The result of this function will be used to set into EncryptionConfiguration// as column keys.std::string BuildColumnKeyMapping();
// FileEncryptor and FileDecryptor are helper classes to write/read an encrypted parquet// file corresponding to each pair of FileEncryptionProperties/FileDecryptionProperties.// FileEncryptor writes the file with fixed data values and FileDecryptor reads the file// and verify the correctness of data values.class FileEncryptor { public: FileEncryptor();
void EncryptFile( std::string file, std::shared_ptr<parquet::FileEncryptionProperties> encryption_configurations);
private: std::shared_ptr<schema::GroupNode> SetupEncryptionSchema();
int num_rowgroups_ = 5; int rows_per_rowgroup_ = 50; std::shared_ptr<schema::GroupNode> schema_;};
class FileDecryptor { public: void DecryptFile( const std::string& file_name, const std::shared_ptr<FileDecryptionProperties>& file_decryption_properties); void DecryptPageIndex( const std::string& file_name, const std::shared_ptr<FileDecryptionProperties>& file_decryption_properties);
private: void CheckFile( parquet::ParquetFileReader* file_reader, const std::shared_ptr<FileDecryptionProperties>& file_decryption_properties); void CheckPageIndex( parquet::ParquetFileReader* file_reader, const std::shared_ptr<FileDecryptionProperties>& file_decryption_properties);};
} // namespace encryption::test} // namespace parquet12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394// 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.
#pragma once
#include <unordered_map>
#include "arrow/util/base64.h"
#include "parquet/encryption/kms_client_factory.h"#include "parquet/encryption/local_wrap_kms_client.h"#include "parquet/platform.h"
namespace parquet::encryption {
// This is a mock class, built for testing only. Don't use it as an example of// LocalWrapKmsClient implementation.class TestOnlyLocalWrapInMemoryKms : public LocalWrapKmsClient { public: explicit TestOnlyLocalWrapInMemoryKms(const KmsConnectionConfig& kms_connection_config);
static void InitializeMasterKeys( const std::unordered_map<std::string, std::string>& master_keys_map);
protected: std::string GetMasterKeyFromServer(const std::string& master_key_identifier) override;
private: static std::unordered_map<std::string, std::string> master_key_map_;};
// This is a mock class, built for testing only. Don't use it as an example of KmsClient// implementation.class TestOnlyInServerWrapKms : public KmsClient { public: static void InitializeMasterKeys( const std::unordered_map<std::string, std::string>& master_keys_map);
std::string WrapKey(const std::string& key_bytes, const std::string& master_key_identifier) override;
std::string UnwrapKey(const std::string& wrapped_key, const std::string& master_key_identifier) override;
static void StartKeyRotation( const std::unordered_map<std::string, std::string>& new_master_keys_map); static void FinishKeyRotation();
private: std::string GetMasterKeyFromServer(const std::string& master_key_identifier);
// Different wrapping and unwrapping key maps to imitate versioning // and support key rotation. static std::unordered_map<std::string, std::string> unwrapping_master_key_map_; static std::unordered_map<std::string, std::string> wrapping_master_key_map_;};
// This is a mock class, built for testing only. Don't use it as an example of// KmsClientFactory implementation.class TestOnlyInMemoryKmsClientFactory : public KmsClientFactory { public: TestOnlyInMemoryKmsClientFactory( bool wrap_locally, const std::unordered_map<std::string, std::string>& master_keys_map) : KmsClientFactory(wrap_locally) { TestOnlyLocalWrapInMemoryKms::InitializeMasterKeys(master_keys_map); TestOnlyInServerWrapKms::InitializeMasterKeys(master_keys_map); }
std::shared_ptr<KmsClient> CreateKmsClient( const KmsConnectionConfig& kms_connection_config) { if (wrap_locally_) { return std::make_shared<TestOnlyLocalWrapInMemoryKms>(kms_connection_config); } else { return std::make_shared<TestOnlyInServerWrapKms>(); } }};
} // namespace parquet::encryption123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157// 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.
#pragma once
#include <chrono>#include <unordered_map>
#include "arrow/util/concurrent_map.h"#include "arrow/util/mutex.h"
namespace parquet::encryption {
using ::arrow::util::ConcurrentMap;
namespace internal {
using TimePoint = std::chrono::time_point<std::chrono::system_clock, std::chrono::duration<double>>;
inline TimePoint CurrentTimePoint() { return std::chrono::system_clock::now(); }
template <typename E>class ExpiringCacheEntry { public: ExpiringCacheEntry() = default;
ExpiringCacheEntry(E cached_item, double expiration_interval_seconds) : expiration_timestamp_(CurrentTimePoint() + std::chrono::duration<double>(expiration_interval_seconds)), cached_item_(std::move(cached_item)) {}
bool IsExpired() const { const auto now = CurrentTimePoint(); return (now > expiration_timestamp_); }
E cached_item() { return cached_item_; }
private: const TimePoint expiration_timestamp_; E cached_item_;};
// This class is to avoid the below warning when compiling KeyToolkit class with VS2015// warning C4503: decorated name length exceeded, name was truncatedtemplate <typename V>class ExpiringCacheMapEntry { public: ExpiringCacheMapEntry() = default;
explicit ExpiringCacheMapEntry( std::shared_ptr<ConcurrentMap<std::string, V>> cached_item, double expiration_interval_seconds) : map_cache_(cached_item, expiration_interval_seconds) {}
bool IsExpired() { return map_cache_.IsExpired(); }
std::shared_ptr<ConcurrentMap<std::string, V>> cached_item() { return map_cache_.cached_item(); }
private: // ConcurrentMap object may be accessed and modified at many places at the same time, // from multiple threads, or even removed from cache. ExpiringCacheEntry<std::shared_ptr<ConcurrentMap<std::string, V>>> map_cache_;};
} // namespace internal
// Two-level cache with expiration of internal caches according to token lifetime.// External cache is per token, internal is per string key.// Wrapper class around:// std::unordered_map<std::string,// internal::ExpiringCacheEntry<std::unordered_map<std::string, V>>>// This cache is safe to be shared between threads.template <typename V>class TwoLevelCacheWithExpiration { public: TwoLevelCacheWithExpiration() { last_cache_cleanup_timestamp_ = internal::CurrentTimePoint(); }
std::shared_ptr<ConcurrentMap<std::string, V>> GetOrCreateInternalCache( const std::string& access_token, double cache_entry_lifetime_seconds) { auto lock = mutex_.Lock();
auto external_cache_entry = cache_.find(access_token); if (external_cache_entry == cache_.end() || external_cache_entry->second.IsExpired()) { cache_.insert({access_token, internal::ExpiringCacheMapEntry<V>( std::shared_ptr<ConcurrentMap<std::string, V>>( new ConcurrentMap<std::string, V>()), cache_entry_lifetime_seconds)}); }
return cache_[access_token].cached_item(); }
void CheckCacheForExpiredTokens(double cache_cleanup_period_seconds) { auto lock = mutex_.Lock();
const auto now = internal::CurrentTimePoint(); if (now > (last_cache_cleanup_timestamp_ + std::chrono::duration<double>(cache_cleanup_period_seconds))) { RemoveExpiredEntriesNoMutex(); last_cache_cleanup_timestamp_ = now + std::chrono::duration<double>(cache_cleanup_period_seconds); } }
void RemoveExpiredEntriesFromCache() { auto lock = mutex_.Lock();
RemoveExpiredEntriesNoMutex(); }
void Remove(const std::string& access_token) { auto lock = mutex_.Lock(); cache_.erase(access_token); }
void Clear() { auto lock = mutex_.Lock(); cache_.clear(); }
private: void RemoveExpiredEntriesNoMutex() { for (auto it = cache_.begin(); it != cache_.end();) { if (it->second.IsExpired()) { it = cache_.erase(it); } else { ++it; } } } std::unordered_map<std::string, internal::ExpiringCacheMapEntry<V>> cache_; internal::TimePoint last_cache_cleanup_timestamp_; ::arrow::util::Mutex mutex_;};
} // namespace parquet::encryptionparrot/lib/python3.10/site-packages/pyarrow/__pycache__/__init__.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/_compute_docstrings.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/_generated_version.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/acero.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/cffi.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/conftest.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/cuda.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/ipc.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/json.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/jvm.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/pandas_compat.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/substrait.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/__pycache__/util.cpython-310.pycAdded
parrot/lib/python3.10/site-packages/pyarrow/include/arrow/builder.hAdded+33
parrot/lib/python3.10/site-packages/pyarrow/include/arrow/chunked_array.hAdded+275
parrot/lib/python3.10/site-packages/pyarrow/include/arrow/stl_iterator.hAdded+304
parrot/lib/python3.10/site-packages/pyarrow/include/arrow/table_builder.hAdded+107
parrot/lib/python3.10/site-packages/pyarrow/include/arrow/type.hAdded+2556
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/io.hAdded+20
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/reader.hAdded+35
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/schema.hAdded+21
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/writer.hAdded+25
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/reader.hAdded+379
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/schema.hAdded+184
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/test_util.hAdded+524
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/writer.hAdded+190
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/benchmark_util.hAdded+47
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter.hAdded+363
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter_reader.hAdded+68
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_page.hAdded+171
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_reader.hAdded+501
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_scanner.hAdded+264
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_writer.hAdded+307
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encoding.hAdded+476
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/crypto_factory.hAdded+152
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/encryption.hAdded+518
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_material_store.hAdded+57
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_unwrapper.hAdded+94
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_wrapper.hAdded+84
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_system_key_material_store.hAdded+89
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_encryption_key.hAdded+57
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_material.hAdded+129
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_metadata.hAdded+91
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_toolkit.hAdded+106
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client.hAdded+93
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client_factory.hAdded+38
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/local_wrap_kms_client.hAdded+94
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/test_encryption_util.hAdded+133
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/test_in_memory_kms.hAdded+94
parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/two_level_cache_with_expiration.hAdded+157