diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c222c0afb7aab37ad6faab5808862c88c40ffb23 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/_compute_docstrings.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/_compute_docstrings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0489dfbd2b41178788f6f7f627d832da5a9f4b1b Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/_compute_docstrings.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/_generated_version.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/_generated_version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6949315ee06d5637b428e1a84575169dabddae2f Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/_generated_version.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/acero.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/acero.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34d32475a3f202f6ca4866bb48e54e7089643fc2 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/acero.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/cffi.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/cffi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc45740cdebbe1c0dcdea4a4125fbd62d151bafb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/cffi.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/conftest.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/conftest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3118ef56f75e30f0796d2feedc4721147c9927f Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/conftest.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/cuda.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/cuda.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59ccf824073d825c7e679e2542069de729dce65d Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/cuda.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/ipc.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/ipc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd9687f015f8b1e8de7073a1bb6519f7be8d3953 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/ipc.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/json.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/json.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d82b2ac1745c225141dd9febabc20283d2566f5 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/json.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/jvm.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/jvm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d17b5eea85cc8733f7bea1f89d075295c367bd7a Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/jvm.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/pandas_compat.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/pandas_compat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0575afb2a85613fa5205a1bbf52c0981e84f8509 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/pandas_compat.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/substrait.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/substrait.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57ac7004320579453776a474e10c2257294d9676 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/substrait.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/util.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b4bd8c69e860efaaad604599d233d633fd88d26 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/util.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/builder.h b/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/builder.h new file mode 100644 index 0000000000000000000000000000000000000000..f0aa14c1e0612d1872a5959998651a12668f449f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/builder.h @@ -0,0 +1,33 @@ +// 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 + +#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" diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/chunked_array.h b/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/chunked_array.h new file mode 100644 index 0000000000000000000000000000000000000000..5d300861d85c2c5d66d6689bfd010b275d50c745 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/chunked_array.h @@ -0,0 +1,275 @@ +// 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 +#include +#include +#include +#include + +#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 +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 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 type = NULLPTR); + + // \brief Constructor with basic input validation. + static Result> Make( + ArrayVector chunks, std::shared_ptr 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> MakeEmpty( + std::shared_ptr 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(chunks_.size()); } + + /// \return chunk a particular chunk from the chunked array + const std::shared_ptr& 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 + std::shared_ptr Slice(int64_t offset, int64_t length) const; + + /// \brief Slice from offset until end of the chunked array + std::shared_ptr 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>> 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> View(const std::shared_ptr& type) const; + + /// \brief Return the type of the chunked array + const std::shared_ptr& type() const { return type_; } + + /// \brief Return a Scalar containing the value of this array at index + Result> 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& 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 type_; + int64_t length_; + int64_t null_count_; + + private: + template + 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 objects +class 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* next_left, std::shared_ptr* 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 +Status ApplyBinaryChunked(const ChunkedArray& left, const ChunkedArray& right, + Action&& action) { + MultipleChunkIterator iterator(left, right); + std::shared_ptr 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 arrow diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/stl_iterator.h b/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/stl_iterator.h new file mode 100644 index 0000000000000000000000000000000000000000..5f2acfb071b299db4ac46f5f69a1db31d60ccac3 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/stl_iterator.h @@ -0,0 +1,304 @@ +// 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 +#include +#include +#include +#include + +#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 +struct DefaultValueAccessor { + using ValueType = decltype(std::declval().GetView(0)); + + ValueType operator()(const ArrayType& array, int64_t index) { + return array.GetView(index); + } +}; + +} // namespace detail + +template > +class ArrayIterator { + public: + using value_type = std::optional; + 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 > +class ChunkedArrayIterator { + public: + using value_type = std::optional; + 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 target_iterator{ + arrow::internal::checked_cast( + *chunked_array_->chunk(static_cast(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 array +template ::ArrayType> +ChunkedArrayIterator Begin(const ChunkedArray& chunked_array) { + return ChunkedArrayIterator(chunked_array); +} + +/// Return an iterator to the end of the chunked array +template ::ArrayType> +ChunkedArrayIterator End(const ChunkedArray& chunked_array) { + return ChunkedArrayIterator(chunked_array, chunked_array.length()); +} + +template +struct ChunkedArrayRange { + const ChunkedArray* chunked_array; + + ChunkedArrayIterator begin() { + return stl::ChunkedArrayIterator(*chunked_array); + } + ChunkedArrayIterator end() { + return stl::ChunkedArrayIterator(*chunked_array, chunked_array->length()); + } +}; + +/// Return an iterable range over the chunked array +template ::ArrayType> +ChunkedArrayRange Iterate(const ChunkedArray& chunked_array) { + return stl::ChunkedArrayRange{&chunked_array}; +} + +} // namespace stl +} // namespace arrow + +namespace std { + +template +struct iterator_traits<::arrow::stl::ArrayIterator> { + using IteratorType = ::arrow::stl::ArrayIterator; + 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 +struct iterator_traits<::arrow::stl::ChunkedArrayIterator> { + using IteratorType = ::arrow::stl::ChunkedArrayIterator; + 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 std diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/table_builder.h b/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/table_builder.h new file mode 100644 index 0000000000000000000000000000000000000000..671cc4ab97996e0eabe5b86af62af4340f1223f6 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/table_builder.h @@ -0,0 +1,107 @@ +// 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 +#include +#include + +#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 +/// schema +class 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> Make( + const std::shared_ptr& 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> Make( + const std::shared_ptr& 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 + T* GetFieldAs(int i) { + return internal::checked_cast(raw_field_builders_[i]); + } + + /// \brief Finish current batch and optionally reset + /// \param[in] reset_builders the resulting RecordBatch + /// \return the resulting RecordBatch + Result> Flush(bool reset_builders); + + /// \brief Finish current batch and reset + /// \return the resulting RecordBatch + Result> 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() const { return schema_; } + + private: + ARROW_DISALLOW_COPY_AND_ASSIGN(RecordBatchBuilder); + + RecordBatchBuilder(const std::shared_ptr& schema, MemoryPool* pool, + int64_t initial_capacity); + + Status CreateBuilders(); + Status InitBuilders(); + + std::shared_ptr schema_; + int64_t initial_capacity_; + MemoryPool* pool_; + + std::vector> field_builders_; + std::vector raw_field_builders_; +}; + +} // namespace arrow diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/type.h b/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/type.h new file mode 100644 index 0000000000000000000000000000000000000000..e087c8ca1c387df7afc437ff057adc4990f197aa --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/arrow/type.h @@ -0,0 +1,2556 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 fingerprint_{NULLPTR}; + mutable std::atomic metadata_fingerprint_{NULLPTR}; +}; + +} // namespace detail + +/// EXPERIMENTAL: Layout specification for a data type +struct 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 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 variadic_spec; + + explicit DataTypeLayout(std::vector buffers, + std::optional 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, + public detail::Fingerprintable, + public util::EqualityComparable { + 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 + /// 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& other, bool check_metadata = false) const; + + /// \brief Return the child field at index i. + const std::shared_ptr& 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(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 from a const + // context. + std::shared_ptr GetSharedPtr() const { + return const_cast(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 if it needs to. +struct ARROW_EXPORT TypeHolder { + const DataType* type = NULLPTR; + std::shared_ptr 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 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 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& 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) : ""; + } + + static std::string ToString(const std::vector&, bool show_metadata = false); + + static std::vector FromTypes( + const std::vector>& types); +}; + +ARROW_EXPORT +std::ostream& operator<<(std::ostream& os, const DataType& type); + +ARROW_EXPORT +std::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 GetPhysicalType(const std::shared_ptr& type); + +/// \brief Base class for all fixed-width data types +class 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 values +class 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 types +class 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 types +class 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 types +class 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 types +class 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 { + public: + Field(std::string name, std::shared_ptr type, bool nullable = true, + std::shared_ptr 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 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 WithMetadata( + const std::shared_ptr& 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 WithMergedMetadata( + const std::shared_ptr& metadata) const; + + /// \brief Return a copy of this field without any metadata attached to it + std::shared_ptr RemoveMetadata() const; + + /// \brief Return a copy of this field with the replaced type. + std::shared_ptr WithType(const std::shared_ptr& type) const; + + /// \brief Return a copy of this field with the replaced name. + std::shared_ptr WithName(const std::string& name) const; + + /// \brief Return a copy of this field with the replaced nullability. + std::shared_ptr 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 { + /// 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> MergeWith( + const Field& other, MergeOptions options = MergeOptions::Defaults()) const; + Result> MergeWith( + const std::shared_ptr& 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& 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& 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& type() const { return type_; } + /// \brief Return whether the field is nullable + bool nullable() const { return nullable_; } + + std::shared_ptr 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 type_; + + // Fields can be nullable + bool nullable_; + + // The field's metadata, if any + std::shared_ptr metadata_; + + ARROW_DISALLOW_COPY_AND_ASSIGN(Field); +}; + +ARROW_EXPORT void PrintTo(const Field& field, std::ostream* os); + +namespace detail { + +template +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(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 +constexpr Type::type CTypeImpl::type_id; + +template +class IntegerTypeImpl : public detail::CTypeImpl { + bool is_signed() const override { return std::is_signed::value; } +}; + +} // namespace detail + +/// Concrete type class for always-null data +class 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 data +class ARROW_EXPORT BooleanType + : public detail::CTypeImpl { + 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 data +class ARROW_EXPORT UInt8Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "uint8"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for signed 8-bit integer data +class ARROW_EXPORT Int8Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "int8"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for unsigned 16-bit integer data +class ARROW_EXPORT UInt16Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "uint16"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for signed 16-bit integer data +class ARROW_EXPORT Int16Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "int16"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for unsigned 32-bit integer data +class ARROW_EXPORT UInt32Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "uint32"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for signed 32-bit integer data +class ARROW_EXPORT Int32Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "int32"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for unsigned 64-bit integer data +class ARROW_EXPORT UInt64Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "uint64"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for signed 64-bit integer data +class ARROW_EXPORT Int64Type + : public detail::IntegerTypeImpl { + public: + static constexpr const char* type_name() { return "int64"; } + + protected: + std::string ComputeFingerprint() const override; +}; + +/// Concrete type class for 16-bit floating-point data +class ARROW_EXPORT HalfFloatType + : public detail::CTypeImpl { + 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 { + 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 { + 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 types +class 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::max() - 1; + +/// \addtogroup binary-datatypes +/// +/// @{ + +/// \brief Concrete type class for variable-size binary data +class 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 data +class 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 data; + } inlined; + + struct { + int32_t size; + std::array 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); + + 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 data +class 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-encoded +class 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-encoded +class 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-encoded +class 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 data +class 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> 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 data +class 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> 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> 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> 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 types +class 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& value_field() const { return children_[0]; } + + const std::shared_ptr& 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 value_type) + : ListType(std::make_shared("item", std::move(value_type))) {} + + explicit ListType(std::shared_ptr 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 value_type) + : LargeListType(std::make_shared("item", std::move(value_type))) {} + + explicit LargeListType(std::shared_ptr 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 views +class 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& value_type) + : ListViewType(std::make_shared("item", value_type)) {} + + explicit ListViewType(const std::shared_ptr& 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& value_type) + : LargeListViewType(std::make_shared("item", value_type)) {} + + explicit LargeListViewType(const std::shared_ptr& 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 key_type, std::shared_ptr item_type, + bool keys_sorted = false); + + MapType(std::shared_ptr key_type, std::shared_ptr item_field, + bool keys_sorted = false); + + MapType(std::shared_ptr key_field, std::shared_ptr item_field, + bool keys_sorted = false); + + explicit MapType(std::shared_ptr value_field, bool keys_sorted = false); + + // Validating constructor + static Result> Make(std::shared_ptr value_field, + bool keys_sorted = false); + + std::shared_ptr key_field() const { return value_type()->field(0); } + std::shared_ptr key_type() const { return key_field()->type(); } + + std::shared_ptr item_field() const { return value_type()->field(1); } + std::shared_ptr 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 data +class 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 value_type, int32_t list_size) + : FixedSizeListType(std::make_shared("item", std::move(value_type)), + list_size) {} + + FixedSizeListType(std::shared_ptr 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 data +class 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 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 GetAllFieldIndices(const std::string& name) const; + + /// \brief Create a new StructType with field added at given index + Result> AddField(int i, + const std::shared_ptr& field) const; + /// \brief Create a new StructType by removing the field at given index + Result> RemoveField(int i) const; + /// \brief Create a new StructType by changing the field at given index + Result> SetField(int i, + const std::shared_ptr& field) const; + + private: + std::string ComputeFingerprint() const override; + + class Impl; + std::unique_ptr impl_; +}; + +/// \brief Base type class for union data +class ARROW_EXPORT UnionType : public NestedType { + public: + static constexpr int8_t kMaxTypeCode = 127; + static constexpr int kInvalidChildId = -1; + + static Result> Make( + const FieldVector& fields, const std::vector& 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& type_codes() const { return type_codes_; } + + /// An array mapping logical type ids to physical child ids. + const std::vector& child_ids() const { return child_ids_; } + + uint8_t max_type_code() const; + + UnionMode::type mode() const; + + protected: + UnionType(FieldVector fields, std::vector type_codes, Type::type id); + + static Status ValidateParameters(const FieldVector& fields, + const std::vector& type_codes, + UnionMode::type mode); + + private: + std::string ComputeFingerprint() const override; + + std::vector type_codes_; + std::vector 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 type_codes); + + // A constructor variant that validates input parameters + static Result> Make(FieldVector fields, + std::vector 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 type_codes); + + // A constructor variant that validates input parameters + static Result> Make(FieldVector fields, + std::vector type_codes); + + std::string name() const override { return "dense_union"; } +}; + +/// \brief Type class for run-end encoded data +class 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 run_end_type, + std::shared_ptr 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& run_end_type() const { return fields()[0]->type(); } + const std::shared_ptr& 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 types +class 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 data +class 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(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(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_EXPORT +std::ostream& operator<<(std::ostream& os, TimeUnit::type unit); + +/// Base type class for time data +class 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(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(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(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(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(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_EXPORT +std::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(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_EXPORT +std::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(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& index_type, + const std::shared_ptr& value_type, bool ordered = false); + + // A constructor variant that validates its input parameters + static Result> Make( + const std::shared_ptr& index_type, + const std::shared_ptr& 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& index_type() const { return index_type_; } + const std::shared_ptr& 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 index_type_; + std::shared_ptr 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 indices) // NOLINT runtime/explicit + : indices_(std::move(indices)) {} + + FieldPath(std::initializer_list 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& indices() const { return indices_; } + int operator[](size_t i) const { return indices_[i]; } + std::vector::const_iterator begin() const { return indices_.begin(); } + std::vector::const_iterator end() const { return indices_.end(); } + + /// \brief Retrieve the referenced child Field from a Schema, Field, or DataType + Result> Get(const Schema& schema) const; + Result> Get(const Field& field) const; + Result> Get(const DataType& type) const; + Result> Get(const FieldVector& fields) const; + + static Result> GetAll(const Schema& schema, + const std::vector& paths); + + /// \brief Retrieve the referenced column from a RecordBatch or Table + Result> Get(const RecordBatch& batch) const; + Result> Get(const Table& table) const; + + /// \brief Retrieve the referenced child from an Array or ArrayData + Result> Get(const Array& array) const; + Result> Get(const ArrayData& data) const; + + /// \brief Retrieve the referenced child from a ChunkedArray + Result> 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> GetFlattened(const Array& array, + MemoryPool* pool = NULLPTR) const; + Result> GetFlattened(const ArrayData& data, + MemoryPool* pool = NULLPTR) const; + Result> GetFlattened(const ChunkedArray& chunked_array, + MemoryPool* pool = NULLPTR) const; + Result> GetFlattened(const RecordBatch& batch, + MemoryPool* pool = NULLPTR) const; + Result> GetFlattened(const Table& table, + MemoryPool* pool = NULLPTR) const; + + private: + std::vector 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 { + 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 refs) { Flatten(std::move(refs)); } + + /// Convenience constructor for nested FieldRefs: each argument will be used to + /// construct a FieldRef + template + FieldRef(A0&& a0, A1&& a1, A&&... a) { + Flatten({// cpplint thinks the following are constructor decls + FieldRef(std::forward(a0)), // NOLINT runtime/explicit + FieldRef(std::forward(a1)), // NOLINT runtime/explicit + FieldRef(std::forward(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 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(impl_); } + bool IsName() const { return std::holds_alternative(impl_); } + bool IsNested() const { + if (IsName()) return false; + if (IsFieldPath()) return std::get(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(impl_) : NULLPTR; + } + const std::string* name() const { + return IsName() ? &std::get(impl_) : NULLPTR; + } + const std::vector* nested_refs() const { + return std::holds_alternative>(impl_) + ? &std::get>(impl_) + : NULLPTR; + } + + /// \brief Retrieve FieldPath of every child field which matches this FieldRef. + std::vector FindAll(const Schema& schema) const; + std::vector FindAll(const Field& field) const; + std::vector FindAll(const DataType& type) const; + std::vector FindAll(const FieldVector& fields) const; + + /// \brief Convenience function which applies FindAll to arg's type or schema. + std::vector FindAll(const ArrayData& array) const; + std::vector FindAll(const Array& array) const; + std::vector FindAll(const ChunkedArray& chunked_array) const; + std::vector FindAll(const RecordBatch& batch) const; + std::vector FindAll(const Table& table) const; + + /// \brief Convenience function: raise an error if matches is empty. + template + Status CheckNonEmpty(const std::vector& 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 + Status CheckNonMultiple(const std::vector& 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 + Result 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 + Result 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 + using GetType = decltype(std::declval().Get(std::declval()).ValueOrDie()); + + /// \brief Get all children matching this FieldRef. + template + std::vector> GetAll(const T& root) const { + std::vector> 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 + Result>> GetAllFlattened(const T& root, + MemoryPool* pool = NULLPTR) const { + std::vector> 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 + Result> 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 + Result> 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 + Result> GetOneOrNone(const T& root) const { + ARROW_ASSIGN_OR_RAISE(auto match, FindOneOrNone(root)); + if (match.empty()) { + return static_cast>(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 + Result> GetOneOrNoneFlattened(const T& root, + MemoryPool* pool = NULLPTR) const { + ARROW_ASSIGN_OR_RAISE(auto match, FindOneOrNone(root)); + if (match.empty()) { + return static_cast>(NULLPTR); + } + return match.GetFlattened(root, pool); + } + + private: + void Flatten(std::vector children); + + std::variant> impl_; +}; + +ARROW_EXPORT void PrintTo(const FieldRef& ref, std::ostream* os); + +ARROW_EXPORT +std::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 structure +class ARROW_EXPORT Schema : public detail::Fingerprintable, + public util::EqualityComparable, + public util::ToStringOstreamable { + public: + explicit Schema(FieldVector fields, Endianness endianness, + std::shared_ptr metadata = NULLPTR); + + explicit Schema(FieldVector fields, + std::shared_ptr 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& other, bool check_metadata = false) const; + + /// \brief Set endianness in the schema + /// + /// \return new Schema + std::shared_ptr 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(int i) const; + + const FieldVector& fields() const; + + std::vector field_names() const; + + /// Returns null if name not found + std::shared_ptr 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 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& names) const; + + /// \brief The custom key-value metadata, if any + /// + /// \return metadata may be null + const std::shared_ptr& 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> AddField(int i, + const std::shared_ptr& field) const; + Result> RemoveField(int i) const; + Result> SetField(int i, + const std::shared_ptr& field) const; + + /// \brief Replace field names with new names + /// + /// \param[in] names new names + /// \return new Schema + Result> WithNames(const std::vector& names) const; + + /// \brief Replace key-value metadata with new metadata + /// + /// \param[in] metadata new KeyValueMetadata + /// \return new Schema + std::shared_ptr WithMetadata( + const std::shared_ptr& metadata) const; + + /// \brief Return copy of Schema without the KeyValueMetadata + std::shared_ptr 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_; +}; + +ARROW_EXPORT void PrintTo(const Schema& s, std::ostream* os); + +ARROW_EXPORT +std::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, + 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); + + /// \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); + + /// \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>& 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> Finish() const; + + /// \brief Merge schemas in a unified schema according to policy. + static Result> Merge( + const std::vector>& schemas, + ConflictPolicy policy = CONFLICT_MERGE); + + /// \brief Indicate if schemas are compatible to merge according to policy. + static Status AreCompatible(const std::vector>& 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_; + + Status AppendField(const std::shared_ptr& 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_EXPORT +Result> UnifySchemas( + const std::vector>& 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_EXPORT +std::string ToString(Type::type id); + +ARROW_EXPORT +std::string ToTypeName(Type::type id); + +ARROW_EXPORT +std::string ToString(TimeUnit::type unit); + +} // namespace internal + +// Helpers to get instances of data types based on general categories + +/// \brief Signed integer types +ARROW_EXPORT +const std::vector>& SignedIntTypes(); +/// \brief Unsigned integer types +ARROW_EXPORT +const std::vector>& UnsignedIntTypes(); +/// \brief Signed and unsigned integer types +ARROW_EXPORT +const std::vector>& IntTypes(); +/// \brief Floating point types +ARROW_EXPORT +const std::vector>& FloatingPointTypes(); +/// \brief Number types without boolean - integer and floating point types +ARROW_EXPORT +const std::vector>& NumericTypes(); +/// \brief Binary and string-like types (except fixed-size binary) +ARROW_EXPORT +const std::vector>& BaseBinaryTypes(); +/// \brief Binary and large-binary types +ARROW_EXPORT +const std::vector>& BinaryTypes(); +/// \brief String and large-string types +ARROW_EXPORT +const std::vector>& StringTypes(); +/// \brief Temporal types including date, time and timestamps for each unit +ARROW_EXPORT +const std::vector>& TemporalTypes(); +/// \brief Interval types +ARROW_EXPORT +const std::vector>& IntervalTypes(); +/// \brief Duration types for each unit +ARROW_EXPORT +const std::vector>& DurationTypes(); +/// \brief Numeric, base binary, date, boolean and null types +ARROW_EXPORT +const std::vector>& PrimitiveTypes(); + +} // namespace arrow diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/io.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/io.h new file mode 100644 index 0000000000000000000000000000000000000000..28a00f12a7a616136beb328d20120d6458294eab --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/io.h @@ -0,0 +1,20 @@ +// 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" diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/reader.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/reader.h new file mode 100644 index 0000000000000000000000000000000000000000..7e746e8c5bbf551e84431552f688a493e2d62bc4 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/reader.h @@ -0,0 +1,35 @@ +// 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" diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/schema.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/schema.h new file mode 100644 index 0000000000000000000000000000000000000000..7ca714f47b5448974c460e424ab3821d10f7a384 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/schema.h @@ -0,0 +1,21 @@ +// 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" diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/writer.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/writer.h new file mode 100644 index 0000000000000000000000000000000000000000..b072dcf74dea7233723ae55599d95be47c674716 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/api/writer.h @@ -0,0 +1,25 @@ +// 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" diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/reader.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/reader.h new file mode 100644 index 0000000000000000000000000000000000000000..6e46ca43f7b18ce0021cdd8064efde70f39f8eaa --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/reader.h @@ -0,0 +1,379 @@ +// 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 +// N.B. we don't include async_generator.h as it's relatively heavy +#include +#include +#include + +#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), +// 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 +// arrays +class 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 reader, + const ArrowReaderProperties& properties, + std::unique_ptr* out); + + /// Factory function to create a FileReader from a ParquetFileReader + static ::arrow::Status Make(::arrow::MemoryPool* pool, + std::unique_ptr reader, + std::unique_ptr* 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* 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& 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& row_group_indices, const std::vector& 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& row_group_indices, + const std::vector& column_indices, + std::shared_ptr<::arrow::RecordBatchReader>* out); + ::arrow::Status GetRecordBatchReader(const std::vector& 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>()>> + GetRecordBatchGenerator(std::shared_ptr reader, + const std::vector row_group_indices, + const std::vector 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& column_indices, + std::shared_ptr<::arrow::Table>* out) = 0; + + virtual ::arrow::Status ReadRowGroup(int i, const std::vector& 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& row_groups, + const std::vector& column_indices, + std::shared_ptr<::arrow::Table>* out) = 0; + + virtual ::arrow::Status ReadRowGroups(const std::vector& 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 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 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 Column(int column_index) = 0; + virtual ::arrow::Status ReadTable(const std::vector& 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++ exceptions +class 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 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 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* out); + ::arrow::Result> Build(); + + private: + ::arrow::MemoryPool* pool_; + ArrowReaderProperties properties_; + std::unique_ptr 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* 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 parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/schema.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/schema.h new file mode 100644 index 0000000000000000000000000000000000000000..dd60fde43422889c53ebd7cf86fbac99c8c6f282 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/schema.h @@ -0,0 +1,184 @@ +// 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 +#include +#include +#include +#include + +#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* out); + +PARQUET_EXPORT +::arrow::Status ToParquetSchema(const ::arrow::Schema* arrow_schema, + const WriterProperties& properties, + std::shared_ptr* 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& 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 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& metadata, + const ArrowReaderProperties& properties, SchemaManifest* manifest); + + const SchemaDescriptor* descr; + std::shared_ptr<::arrow::Schema> origin_schema; + std::shared_ptr schema_metadata; + std::vector schema_fields; + + std::unordered_map column_index_to_field; + std::unordered_map 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> GetFieldIndices( + const std::vector& column_indices) const { + const schema::GroupNode* group = descr->group_node(); + std::unordered_set already_added; + + std::vector 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 parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/test_util.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/test_util.h new file mode 100644 index 0000000000000000000000000000000000000000..b2be1b3c5354d7a28c6fad23dd745a9d32bbb7d2 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/test_util.h @@ -0,0 +1,524 @@ +// 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 +#include +#include +#include +#include +#include + +#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 +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 +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 +::arrow::enable_if_floating_point NonNullArray( + size_t size, std::shared_ptr* out) { + using c_type = typename ArrowType::c_type; + std::vector values; + if constexpr (::arrow::is_half_float_type::value) { + values.resize(size); + test::random_float16_numbers(static_cast(size), 0, ::arrow::util::Float16(0.0f), + ::arrow::util::Float16(1.0f), values.data()); + } else { + ::arrow::random_real(size, 0, static_cast(0), static_cast(1), + &values); + } + ::arrow::NumericBuilder builder; + RETURN_NOT_OK(builder.AppendValues(values.data(), values.size())); + return builder.Finish(out); +} + +template +::arrow::enable_if_integer NonNullArray(size_t size, + std::shared_ptr* out) { + std::vector values; + ::arrow::randint(size, 0, 64, &values); + + // Passing data type so this will work with TimestampType too + ::arrow::NumericBuilder builder(std::make_shared(), + ::arrow::default_memory_pool()); + RETURN_NOT_OK(builder.AppendValues(values.data(), values.size())); + return builder.Finish(out); +} + +template +::arrow::enable_if_date NonNullArray(size_t size, + std::shared_ptr* out) { + std::vector 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 builder(std::make_shared(), + ::arrow::default_memory_pool()); + RETURN_NOT_OK(builder.AppendValues(values.data(), values.size())); + return builder.Finish(out); +} + +template +::arrow::enable_if_base_binary NonNullArray( + size_t size, std::shared_ptr* out) { + using BuilderType = typename ::arrow::TypeTraits::BuilderType; + BuilderType builder; + for (size_t i = 0; i < size; i++) { + RETURN_NOT_OK(builder.Append("test-string")); + } + return builder.Finish(out); +} + +template +::arrow::enable_if_fixed_size_binary NonNullArray( + size_t size, std::shared_ptr* out) { + using BuilderType = typename ::arrow::TypeTraits::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 +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 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(1, 0), byte_width * n); +} + +template +::arrow::enable_if_t< + std::is_same>::value, Status> +NonNullArray(size_t size, std::shared_ptr* out) { + constexpr int32_t kDecimalPrecision = precision; + constexpr int32_t kDecimalScale = DecimalWithPrecisionAndScale::scale; + + const auto type = ::arrow::decimal(kDecimalPrecision, kDecimalScale); + ::arrow::Decimal128Builder builder(type); + const int32_t byte_width = + static_cast(*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 +::arrow::enable_if_t< + std::is_same>::value, Status> +NonNullArray(size_t size, std::shared_ptr* out) { + constexpr int32_t kDecimalPrecision = precision; + constexpr int32_t kDecimalScale = Decimal256WithPrecisionAndScale::scale; + + const auto type = ::arrow::decimal256(kDecimalPrecision, kDecimalScale); + ::arrow::Decimal256Builder builder(type); + const int32_t byte_width = + static_cast(*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 +::arrow::enable_if_boolean NonNullArray(size_t size, + std::shared_ptr* out) { + std::vector 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 +::arrow::enable_if_floating_point NullableArray( + size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr* out) { + using c_type = typename ArrowType::c_type; + std::vector values; + if constexpr (::arrow::is_half_float_type::value) { + values.resize(size); + test::random_float16_numbers(static_cast(size), 0, ::arrow::util::Float16(-1e4f), + ::arrow::util::Float16(1e4f), values.data()); + } else { + ::arrow::random_real(size, seed, static_cast(-1e10), + static_cast(1e10), &values); + } + std::vector valid_bytes(size, 1); + + for (size_t i = 0; i < num_nulls; i++) { + valid_bytes[i * 2] = 0; + } + + ::arrow::NumericBuilder 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 +::arrow::enable_if_integer NullableArray(size_t size, size_t num_nulls, + uint32_t seed, + std::shared_ptr* out) { + std::vector values; + + // Seed is random in Arrow right now + (void)seed; + ::arrow::randint(size, 0, 64, &values); + std::vector 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 builder(std::make_shared(), + ::arrow::default_memory_pool()); + RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data())); + return builder.Finish(out); +} + +template +::arrow::enable_if_date NullableArray(size_t size, size_t num_nulls, + uint32_t seed, + std::shared_ptr* out) { + std::vector 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 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 builder(std::make_shared(), + ::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 +::arrow::enable_if_base_binary NullableArray( + size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<::arrow::Array>* out) { + std::vector valid_bytes(size, 1); + + for (size_t i = 0; i < num_nulls; i++) { + valid_bytes[i * 2] = 0; + } + + using BuilderType = typename ::arrow::TypeTraits::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(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(..) +template +::arrow::enable_if_fixed_size_binary NullableArray( + size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<::arrow::Array>* out) { + std::vector valid_bytes(size, 1); + + for (size_t i = 0; i < num_nulls; i++) { + valid_bytes[i * 2] = 0; + } + + using BuilderType = typename ::arrow::TypeTraits::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(i), buffer); + RETURN_NOT_OK(builder.Append(buffer)); + } + } + return builder.Finish(out); +} + +template +::arrow::enable_if_t< + std::is_same>::value, Status> +NullableArray(size_t size, size_t num_nulls, uint32_t seed, + std::shared_ptr<::arrow::Array>* out) { + std::vector 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::scale; + const auto type = ::arrow::decimal(kDecimalPrecision, kDecimalScale); + const int32_t byte_width = + static_cast(*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 +::arrow::enable_if_t< + std::is_same>::value, Status> +NullableArray(size_t size, size_t num_nulls, uint32_t seed, + std::shared_ptr<::arrow::Array>* out) { + std::vector 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::scale; + const auto type = ::arrow::decimal256(kDecimalPrecision, kDecimalScale); + const int32_t byte_width = + static_cast(*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 +::arrow::enable_if_boolean NullableArray(size_t size, size_t num_nulls, + uint32_t seed, + std::shared_ptr* out) { + std::vector values; + + // Seed is random in Arrow right now + (void)seed; + + ::arrow::randint(size, 0, 1, &values); + std::vector 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& 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(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(length_per_entry); + } + } + } + offsets_ptr[size] = static_cast(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 array +Status MakeEmptyListsArray(int64_t size, std::shared_ptr* 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> child_buffers = {nullptr /* null bitmap */, + nullptr /* values */}; + auto child_data = + ::arrow::ArrayData::Make(value_field->type(), 0, std::move(child_buffers)); + + std::vector> 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& 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& values, + bool nullable) { + auto carr = std::make_shared<::arrow::ChunkedArray>(values); + return MakeSimpleTable(carr, nullable); +} + +template +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(p_array->values()->data())[i]); + } +} + +template +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(expected)[i], + reinterpret_cast( + p_array->values()->data())[i]); + } +} + +template <> +void ExpectArrayT<::arrow::BooleanType>(void* expected, Array* result) { + ::arrow::BooleanBuilder builder; + ARROW_EXPECT_OK( + builder.AppendValues(reinterpret_cast(expected), result->length())); + + std::shared_ptr expected_array; + ARROW_EXPECT_OK(builder.Finish(&expected_array)); + EXPECT_TRUE(result->Equals(*expected_array)); +} + +} // namespace arrow + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/writer.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/writer.h new file mode 100644 index 0000000000000000000000000000000000000000..4a1a033a7b7b8711998bf074e7715c849e4cb2ff --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/writer.h @@ -0,0 +1,190 @@ +// 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 +#include + +#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 writer, + std::shared_ptr<::arrow::Schema> schema, + std::shared_ptr arrow_properties, + std::unique_ptr* 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> Open( + const ::arrow::Schema& schema, MemoryPool* pool, + std::shared_ptr<::arrow::io::OutputStream> sink, + std::shared_ptr properties = default_writer_properties(), + std::shared_ptr 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 properties, + std::unique_ptr* 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 properties, + std::shared_ptr arrow_properties, + std::unique_ptr* 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& key_value_metadata) = 0; + /// \brief Return the file metadata, only available after calling Close(). + virtual const std::shared_ptr metadata() const = 0; +}; + +/// \brief Write Parquet file metadata only to indicated Arrow OutputStream +PARQUET_EXPORT +::arrow::Status WriteFileMetaData(const FileMetaData& file_metadata, + ::arrow::io::OutputStream* sink); + +/// \brief Write metadata-only Parquet file to indicated Arrow OutputStream +PARQUET_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_EXPORT +WriteTable(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 properties = default_writer_properties(), + std::shared_ptr arrow_properties = + default_arrow_writer_properties()); + +} // namespace arrow +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/benchmark_util.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/benchmark_util.h new file mode 100644 index 0000000000000000000000000000000000000000..7996f7f85e8986052c1e9bc33a1ea0fc776aa202 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/benchmark_util.h @@ -0,0 +1,47 @@ +// 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 +#include +#include + +#include "parquet/types.h" + +namespace parquet::benchmark { + +template +void GenerateBenchmarkData(uint32_t size, uint32_t seed, T* data, + std::vector* 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* 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::benchmark diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter.h new file mode 100644 index 0000000000000000000000000000000000000000..909563d013fedcc6604ec8decc3d7384e0b2d693 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter.h @@ -0,0 +1,363 @@ +// 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 +#include +#include + +#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(kMaximumBloomFilterBytes << 3); + } else { + num_bits = static_cast(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(::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 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 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_; +}; + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter_reader.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter_reader.h new file mode 100644 index 0000000000000000000000000000000000000000..cbd267dd1972dcde98382dda3c84a6a544ddc3e3 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/bloom_filter_reader.h @@ -0,0 +1,68 @@ +// 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 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 Make( + std::shared_ptr<::arrow::io::RandomAccessFile> input, + std::shared_ptr file_metadata, const ReaderProperties& properties, + std::shared_ptr 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 RowGroup(int i) = 0; +}; + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_page.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_page.h new file mode 100644 index 0000000000000000000000000000000000000000..b389ffd98e6c79bd11f173a77643fd3ed3d270b7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_page.h @@ -0,0 +1,171 @@ +// 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 +#include +#include +#include + +#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 path +class Page { + public: + Page(const std::shared_ptr& buffer, PageType::type type) + : buffer_(buffer), type_(type) {} + + PageType::type type() const { return type_; } + + std::shared_ptr 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(buffer_->size()); } + + private: + std::shared_ptr buffer_; + PageType::type type_; +}; + +/// \brief Base type for DataPageV1 and DataPageV2 including common attributes +class 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 first_row_index() const { return first_row_index_; } + + virtual ~DataPage() = default; + + protected: + DataPage(PageType::type type, const std::shared_ptr& buffer, int32_t num_values, + Encoding::type encoding, int64_t uncompressed_size, + EncodedStatistics statistics = EncodedStatistics(), + std::optional 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 first_row_index_; +}; + +class DataPageV1 : public DataPage { + public: + DataPageV1(const std::shared_ptr& 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 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, 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 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, 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 parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_reader.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_reader.h new file mode 100644 index 0000000000000000000000000000000000000000..29e1b2a25e43798188af82b588614ee46ccc16ca --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_reader.h @@ -0,0 +1,501 @@ +// 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 +#include +#include +#include + +#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 size +static constexpr uint32_t kDefaultMaxPageHeaderSize = 16 * 1024 * 1024; + +// 16 KB is the default expected page header size +static 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 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 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 meta, std::shared_ptr 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 meta_decryptor; + std::shared_ptr data_decryptor; +}; + +// Abstract page iterator interface. This way, we can feed column pages to the +// ColumnReader through whatever mechanism we choose +class PARQUET_EXPORT PageReader { + using DataPageFilter = std::function; + + public: + virtual ~PageReader() = default; + + static std::unique_ptr Open( + std::shared_ptr 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 Open(std::shared_ptr 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(nullptr) on EOS, std::shared_ptr + // 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 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 Make( + const ColumnDescriptor* descr, std::unique_ptr 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 +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.0 +class 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 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 ReleaseValues() = 0; + + /// \brief Transfer filled validity bitmap buffer to caller. A new one will + /// be allocated in subsequent ReadRecords calls + virtual std::shared_ptr 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 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(ReadDictionary(&len)); + /// or: + /// const float* dict = reinterpret_cast(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(def_levels_->mutable_data()); + } + + /// \brief Decoded repetition levels + int16_t* rep_levels() const { + return reinterpret_cast(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> GetBuilderChunks() = 0; +}; + +/// \brief Read records directly to dictionary-encoded Arrow form (int32 +/// indices). Only valid for BYTE_ARRAY columns +class DictionaryRecordReader : virtual public RecordReader { + public: + virtual std::shared_ptr<::arrow::ChunkedArray> GetResult() = 0; +}; + +} // namespace internal + +using BoolReader = TypedColumnReader; +using Int32Reader = TypedColumnReader; +using Int64Reader = TypedColumnReader; +using Int96Reader = TypedColumnReader; +using FloatReader = TypedColumnReader; +using DoubleReader = TypedColumnReader; +using ByteArrayReader = TypedColumnReader; +using FixedLenByteArrayReader = TypedColumnReader; + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_scanner.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_scanner.h new file mode 100644 index 0000000000000000000000000000000000000000..a9953866fab22ee6db13a92578f85556ea6f99ba --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_scanner.h @@ -0,0 +1,264 @@ +// 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 + +#include +#include +#include +#include +#include +#include + +#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 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(batch_size_) : 0); + rep_levels_.resize( + descr()->max_repetition_level() > 0 ? static_cast(batch_size_) : 0); + } + + virtual ~Scanner() {} + + static std::shared_ptr Make( + std::shared_ptr 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 def_levels_; + std::vector rep_levels_; + int level_offset_; + int levels_buffered_; + + std::shared_ptr value_buffer_; + int value_offset_; + int64_t values_buffered_; + std::shared_ptr reader_; +}; + +template +class PARQUET_TEMPLATE_CLASS_EXPORT TypedScanner : public Scanner { + public: + typedef typename DType::c_type T; + + explicit TypedScanner(std::shared_ptr 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*>(reader_.get()); + int value_byte_size = type_traits::value_byte_size; + PARQUET_THROW_NOT_OK(value_buffer_->Resize(batch_size_ * value_byte_size)); + values_ = reinterpret_cast(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( + typed_reader_->ReadBatch(static_cast(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(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* typed_reader_; + + inline void FormatValue(void* val, char* buffer, int bufsize, int width); + + T* values_; +}; + +template +inline void TypedScanner::FormatValue(void* val, char* buffer, int bufsize, + int width) { + std::string fmt = format_fwf(width); + snprintf(buffer, bufsize, fmt.c_str(), *reinterpret_cast(val)); +} + +template <> +inline void TypedScanner::FormatValue(void* val, char* buffer, int bufsize, + int width) { + std::string fmt = format_fwf(width); + std::string result = Int96ToString(*reinterpret_cast(val)); + snprintf(buffer, bufsize, fmt.c_str(), result.c_str()); +} + +template <> +inline void TypedScanner::FormatValue(void* val, char* buffer, int bufsize, + int width) { + std::string fmt = format_fwf(width); + std::string result = ByteArrayToString(*reinterpret_cast(val)); + snprintf(buffer, bufsize, fmt.c_str(), result.c_str()); +} + +template <> +inline void TypedScanner::FormatValue(void* val, char* buffer, int bufsize, + int width) { + std::string fmt = format_fwf(width); + std::string result = FixedLenByteArrayToString( + *reinterpret_cast(val), descr()->type_length()); + snprintf(buffer, bufsize, fmt.c_str(), result.c_str()); +} + +typedef TypedScanner BoolScanner; +typedef TypedScanner Int32Scanner; +typedef TypedScanner Int64Scanner; +typedef TypedScanner Int96Scanner; +typedef TypedScanner FloatScanner; +typedef TypedScanner DoubleScanner; +typedef TypedScanner ByteArrayScanner; +typedef TypedScanner FixedLenByteArrayScanner; + +template +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(reader); + auto vals = reinterpret_cast(&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 parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_writer.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_writer.h new file mode 100644 index 0000000000000000000000000000000000000000..a278670fa81c681a34958f27136654799895bb38 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/column_writer.h @@ -0,0 +1,307 @@ +// 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 +#include +#include + +#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 Open( + std::shared_ptr 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 header_encryptor = NULLPTR, + std::shared_ptr 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 Open( + std::shared_ptr 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 header_encryptor = NULLPTR, + std::shared_ptr 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 Make(ColumnChunkMetaDataBuilder*, + std::unique_ptr, + 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 +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; +using Int32Writer = TypedColumnWriter; +using Int64Writer = TypedColumnWriter; +using Int96Writer = TypedColumnWriter; +using FloatWriter = TypedColumnWriter; +using DoubleWriter = TypedColumnWriter; +using ByteArrayWriter = TypedColumnWriter; +using FixedLenByteArrayWriter = TypedColumnWriter; + +namespace internal { + +/** + * Timestamp conversion constants + */ +constexpr int64_t kJulianEpochOffsetDays = INT64_C(2440588); + +template +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(seconds, + impala_timestamp); +} + +constexpr int64_t kMillisecondsInNanos = kSecondsInNanos / INT64_C(1000); + +inline void MillisecondsToImpalaTimestamp(const int64_t milliseconds, + Int96* impala_timestamp) { + ArrowTimestampToImpalaTimestamp( + milliseconds, impala_timestamp); +} + +constexpr int64_t kMicrosecondsInNanos = kMillisecondsInNanos / INT64_C(1000); + +inline void MicrosecondsToImpalaTimestamp(const int64_t microseconds, + Int96* impala_timestamp) { + ArrowTimestampToImpalaTimestamp( + microseconds, impala_timestamp); +} + +constexpr int64_t kNanosecondsInNanos = INT64_C(1); + +inline void NanosecondsToImpalaTimestamp(const int64_t nanoseconds, + Int96* impala_timestamp) { + ArrowTimestampToImpalaTimestamp( + nanoseconds, impala_timestamp); +} + +} // namespace internal +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encoding.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encoding.h new file mode 100644 index 0000000000000000000000000000000000000000..493c4044ddc1c07d61b3c362cfeef1936320b860 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encoding.h @@ -0,0 +1,476 @@ +// 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 +#include +#include +#include + +#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 +class NumericBuilder; +class FixedSizeBinaryBuilder; +template +class Dictionary32Builder; + +} // namespace arrow + +namespace parquet { + +template +class TypedEncoder; + +using BooleanEncoder = TypedEncoder; +using Int32Encoder = TypedEncoder; +using Int64Encoder = TypedEncoder; +using Int96Encoder = TypedEncoder; +using FloatEncoder = TypedEncoder; +using DoubleEncoder = TypedEncoder; +using ByteArrayEncoder = TypedEncoder; +using FLBAEncoder = TypedEncoder; + +template +class TypedDecoder; + +class BooleanDecoder; +using Int32Decoder = TypedDecoder; +using Int64Decoder = TypedDecoder; +using Int96Decoder = TypedDecoder; +using FloatDecoder = TypedDecoder; +using DoubleDecoder = TypedDecoder; +using ByteArrayDecoder = TypedDecoder; +class FLBADecoder; + +template +struct EncodingTraits; + +template <> +struct EncodingTraits { + using Encoder = BooleanEncoder; + using Decoder = BooleanDecoder; + + using ArrowType = ::arrow::BooleanType; + using Accumulator = ::arrow::BooleanBuilder; + struct DictAccumulator {}; +}; + +template <> +struct EncodingTraits { + 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 { + 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 { + using Encoder = Int96Encoder; + using Decoder = Int96Decoder; + + struct Accumulator {}; + struct DictAccumulator {}; +}; + +template <> +struct EncodingTraits { + 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 { + 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 { + 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> chunks; + }; + using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::BinaryType>; +}; + +template <> +struct EncodingTraits { + 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 encoders +class Encoder { + public: + virtual ~Encoder() = default; + + virtual int64_t EstimatedDataEncodedSize() = 0; + virtual std::shared_ptr 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 +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& 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 +void TypedEncoder::Put(const std::vector& src, int num_values) { + if (num_values == -1) { + num_values = static_cast(src.size()); + } + Put(src.data(), num_values); +} + +template <> +inline void TypedEncoder::Put(const std::vector& 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 encoders +template +class DictEncoder : virtual public TypedEncoder { + 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 +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(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::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::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::DictAccumulator* builder) = 0; + + /// \brief Decode into a DictionaryBuilder ignoring nulls + /// + /// \return number of values decoded + int DecodeArrowNonNull(int num_values, + typename EncodingTraits::DictAccumulator* builder) { + return DecodeArrow(num_values, 0, /*valid_bits=*/NULLPTR, 0, builder); + } +}; + +template +class DictDecoder : virtual public TypedDecoder { + public: + using T = typename DType::c_type; + + virtual void SetDict(TypedDecoder* 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 { + public: + using TypedDecoder::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 { + public: + using TypedDecoder::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_EXPORT +std::unique_ptr MakeEncoder( + Type::type type_num, Encoding::type encoding, bool use_dictionary = false, + const ColumnDescriptor* descr = NULLPTR, + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()); + +template +std::unique_ptr::Encoder> MakeTypedEncoder( + Encoding::type encoding, bool use_dictionary = false, + const ColumnDescriptor* descr = NULLPTR, + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) { + using OutType = typename EncodingTraits::Encoder; + std::unique_ptr base = + MakeEncoder(DType::type_num, encoding, use_dictionary, descr, pool); + return std::unique_ptr(dynamic_cast(base.release())); +} + +PARQUET_EXPORT +std::unique_ptr MakeDecoder( + Type::type type_num, Encoding::type encoding, const ColumnDescriptor* descr = NULLPTR, + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()); + +namespace detail { + +PARQUET_EXPORT +std::unique_ptr MakeDictDecoder(Type::type type_num, + const ColumnDescriptor* descr, + ::arrow::MemoryPool* pool); + +} // namespace detail + +template +std::unique_ptr> MakeDictDecoder( + const ColumnDescriptor* descr = NULLPTR, + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) { + using OutType = DictDecoder; + auto decoder = detail::MakeDictDecoder(DType::type_num, descr, pool); + return std::unique_ptr(dynamic_cast(decoder.release())); +} + +template +std::unique_ptr::Decoder> MakeTypedDecoder( + Encoding::type encoding, const ColumnDescriptor* descr = NULLPTR, + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) { + using OutType = typename EncodingTraits::Decoder; + std::unique_ptr base = MakeDecoder(DType::type_num, encoding, descr, pool); + return std::unique_ptr(dynamic_cast(base.release())); +} + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/crypto_factory.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/crypto_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..01172c2b3dd4089bf9fb494892282d8574e6cebf --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/crypto_factory.h @@ -0,0 +1,152 @@ +// 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 + +#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 minutes +static 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 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 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 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 key_toolkit_ = std::make_shared(); +}; + +} // namespace parquet::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/encryption.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/encryption.h new file mode 100644 index 0000000000000000000000000000000000000000..1ddef9e8236db26ea93a36451d02b30b47f6d233 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/encryption.h @@ -0,0 +1,518 @@ +// 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 +#include +#include +#include + +#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>; + +class ColumnEncryptionProperties; +using ColumnPathToEncryptionPropertiesMap = + std::map>; + +class PARQUET_EXPORT DecryptionKeyRetriever { + public: + virtual std::string GetKey(const std::string& key_metadata) = 0; + virtual ~DecryptionKeyRetriever() {} +}; + +/// Simple integer key retriever +class 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 key_map_; +}; + +// Simple string key retriever +class 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 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(str.c_str()); + return reinterpret_cast(cbytes); +} + +inline ::arrow::util::span str2span(const std::string& str) { + if (str.empty()) { + return {}; + } + + return {reinterpret_cast(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& 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 build() { + return std::shared_ptr( + 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 DeepClone() { + std::string key_copy = key_; + return std::shared_ptr(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& 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 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 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& 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 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 build() { + return std::shared_ptr(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 aad_prefix_verifier_; + ColumnPathToDecryptionPropertiesMap column_decryption_properties_; + + std::shared_ptr 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& 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& 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 DeepClone(std::string new_aad_prefix = ""); + + private: + std::string footer_key_; + std::string aad_prefix_; + std::shared_ptr aad_prefix_verifier_; + + const std::string empty_string_ = ""; + ColumnPathToDecryptionPropertiesMap column_decryption_properties_; + + std::shared_ptr key_retriever_; + bool check_plaintext_footer_integrity_; + bool plaintext_files_allowed_; + bool utilized_; + + FileDecryptionProperties( + const std::string& footer_key, + std::shared_ptr key_retriever, + bool check_plaintext_footer_integrity, const std::string& aad_prefix, + std::shared_ptr 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 build() { + return std::shared_ptr(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 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 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 parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_material_store.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_material_store.h new file mode 100644 index 0000000000000000000000000000000000000000..83f028a4bc1e9e0d24e21e7acfb785af0e5b37f7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_material_store.h @@ -0,0 +1,57 @@ +// 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 +#include +#include + +#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 target_key_store) = 0; + + /// Returns the Set of all key IDs in this store (for the given Parquet file) + virtual std::vector GetKeyIDSet() = 0; + + virtual ~FileKeyMaterialStore() {} +}; + +} // namespace parquet::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_unwrapper.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_unwrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..6147abbecd3e6a72a1d5c8fb65d1ccd1e0f6170e --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_unwrapper.h @@ -0,0 +1,94 @@ +// 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 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 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 key_toolkit_owner, KeyToolkit* key_toolkit, + const KmsConnectionConfig& kms_connection_config, + double cache_lifetime_seconds, + std::shared_ptr key_material_store, + const std::string& file_path, + const std::shared_ptr<::arrow::fs::FileSystem>& file_system); + + std::shared_ptr 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> kek_per_kek_id_; + std::shared_ptr key_toolkit_owner_; + KeyToolkit* key_toolkit_; + KmsConnectionConfig kms_connection_config_; + const double cache_entry_lifetime_seconds_; + std::shared_ptr key_material_store_; + const std::string file_path_; + std::shared_ptr<::arrow::fs::FileSystem> file_system_; +}; + +} // namespace parquet::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_wrapper.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_wrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..26b9719de64dbafe39123c214d74f35301f8713b --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_wrapper.h @@ -0,0 +1,84 @@ +// 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 +#include +#include + +#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 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> + kek_per_master_key_id_; + + std::shared_ptr kms_client_; + KmsConnectionConfig kms_connection_config_; + std::shared_ptr key_material_store_; + const double cache_entry_lifetime_seconds_; + const bool double_wrapping_; + uint16_t key_counter_; +}; + +} // namespace parquet::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_system_key_material_store.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_system_key_material_store.h new file mode 100644 index 0000000000000000000000000000000000000000..896a53202f589158ae684aa5df9c1f69cae86b28 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_system_key_material_store.h @@ -0,0 +1,89 @@ +// 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 +#include +#include + +#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 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 target_key_store); + + /// Returns the Set of all key IDs in this store (for the given Parquet file) + std::vector 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 key_material_map_; +}; + +} // namespace parquet::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_encryption_key.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_encryption_key.h new file mode 100644 index 0000000000000000000000000000000000000000..62263ee3cd5062ece20ac0f79b89d3cf0312f360 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_encryption_key.h @@ -0,0 +1,57 @@ +// 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 +#include + +#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 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::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_material.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_material.h new file mode 100644 index 0000000000000000000000000000000000000000..3e7e862c996d3f0b0c016f3953dc40dcb314a8a0 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_material.h @@ -0,0 +1,129 @@ +// 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 + +#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::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_metadata.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..6fe8ac7ccb9db3fb92da42064f9fe2aeabdbfb52 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_metadata.h @@ -0,0 +1,91 @@ +// 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 +#include + +#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(key_material_or_reference_); + } + + const std::string& key_reference() const { + if (is_internal_storage_) { + throw ParquetException("key material is stored internally."); + } + return ::std::get(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 key_material_or_reference_; +}; + +} // namespace parquet::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_toolkit.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_toolkit.h new file mode 100644 index 0000000000000000000000000000000000000000..339692a99a33d9dfe3fb266352423aa2e5f4589a --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/key_toolkit.h @@ -0,0 +1,106 @@ +// 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 +#include + +#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>& kms_client_cache_per_token() { + return kms_client_cache_; + } + /// Key encryption key two level cache for wrapping: token -> MasterEncryptionKeyId -> + /// KeyEncryptionKey + TwoLevelCacheWithExpiration& kek_write_cache_per_token() { + return key_encryption_key_write_cache_; + } + + /// Key encryption key two level cache for unwrapping: token -> KeyEncryptionKeyId -> + /// KeyEncryptionKeyBytes + TwoLevelCacheWithExpiration& kek_read_cache_per_token() { + return key_encryption_key_read_cache_; + } + + std::shared_ptr 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 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> kms_client_cache_; + TwoLevelCacheWithExpiration key_encryption_key_write_cache_; + TwoLevelCacheWithExpiration key_encryption_key_read_cache_; + std::shared_ptr 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::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client.h new file mode 100644 index 0000000000000000000000000000000000000000..ef363d9c2cda1e8aef06b2ceebab61a1e0916870 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client.h @@ -0,0 +1,93 @@ +// 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 +#include +#include + +#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 refreshable_key_access_token; + std::unordered_map 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::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client_factory.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..7a7c77c7eebbfbb687575acb12b89c1c2e99461a --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/kms_client_factory.h @@ -0,0 +1,38 @@ +// 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 CreateKmsClient( + const KmsConnectionConfig& kms_connection_config) = 0; + + protected: + bool wrap_locally_; +}; + +} // namespace parquet::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/local_wrap_kms_client.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/local_wrap_kms_client.h new file mode 100644 index 0000000000000000000000000000000000000000..3c90d82960525bf10c0dc23ea6a2c96c78104fea --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/local_wrap_kms_client.h @@ -0,0 +1,94 @@ +// 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 +#include + +#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 master_key_cache_; +}; + +} // namespace parquet::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/test_encryption_util.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/test_encryption_util.h new file mode 100644 index 0000000000000000000000000000000000000000..9bfc774278dde9ac42699339fb1a056e3fd14a70 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/test_encryption_util.h @@ -0,0 +1,133 @@ +// 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 +#include +#include + +#include + +#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/16 +const char kColumnEncryptionKey1[] = "1234567890123450"; +const char kColumnEncryptionKey2[] = "1234567890123451"; +const char kFileName[] = "tester"; + +// Get the path of file inside parquet test data directory +std::string data_file(const char* file); + +// A temporary directory that contains the encrypted files generated in the tests. +extern std::unique_ptr temp_dir; + +inline ::arrow::Result> 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 rotation +const 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 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 encryption_configurations); + + private: + std::shared_ptr SetupEncryptionSchema(); + + int num_rowgroups_ = 5; + int rows_per_rowgroup_ = 50; + std::shared_ptr schema_; +}; + +class FileDecryptor { + public: + void DecryptFile( + const std::string& file_name, + const std::shared_ptr& file_decryption_properties); + void DecryptPageIndex( + const std::string& file_name, + const std::shared_ptr& file_decryption_properties); + + private: + void CheckFile( + parquet::ParquetFileReader* file_reader, + const std::shared_ptr& file_decryption_properties); + void CheckPageIndex( + parquet::ParquetFileReader* file_reader, + const std::shared_ptr& file_decryption_properties); +}; + +} // namespace encryption::test +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/test_in_memory_kms.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/test_in_memory_kms.h new file mode 100644 index 0000000000000000000000000000000000000000..c5fdc797b8ca78a7eddbbdd57dc5a56cb8745526 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/test_in_memory_kms.h @@ -0,0 +1,94 @@ +// 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 + +#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& master_keys_map); + + protected: + std::string GetMasterKeyFromServer(const std::string& master_key_identifier) override; + + private: + static std::unordered_map 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& 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& 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 unwrapping_master_key_map_; + static std::unordered_map 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& master_keys_map) + : KmsClientFactory(wrap_locally) { + TestOnlyLocalWrapInMemoryKms::InitializeMasterKeys(master_keys_map); + TestOnlyInServerWrapKms::InitializeMasterKeys(master_keys_map); + } + + std::shared_ptr CreateKmsClient( + const KmsConnectionConfig& kms_connection_config) { + if (wrap_locally_) { + return std::make_shared(kms_connection_config); + } else { + return std::make_shared(); + } + } +}; + +} // namespace parquet::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/two_level_cache_with_expiration.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/two_level_cache_with_expiration.h new file mode 100644 index 0000000000000000000000000000000000000000..76c2b8277000052865787ee148191b73fe37fcb0 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/two_level_cache_with_expiration.h @@ -0,0 +1,157 @@ +// 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 +#include + +#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>; + +inline TimePoint CurrentTimePoint() { return std::chrono::system_clock::now(); } + +template +class ExpiringCacheEntry { + public: + ExpiringCacheEntry() = default; + + ExpiringCacheEntry(E cached_item, double expiration_interval_seconds) + : expiration_timestamp_(CurrentTimePoint() + + std::chrono::duration(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 truncated +template +class ExpiringCacheMapEntry { + public: + ExpiringCacheMapEntry() = default; + + explicit ExpiringCacheMapEntry( + std::shared_ptr> cached_item, + double expiration_interval_seconds) + : map_cache_(cached_item, expiration_interval_seconds) {} + + bool IsExpired() { return map_cache_.IsExpired(); } + + std::shared_ptr> 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>> 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>> +// This cache is safe to be shared between threads. +template +class TwoLevelCacheWithExpiration { + public: + TwoLevelCacheWithExpiration() { + last_cache_cleanup_timestamp_ = internal::CurrentTimePoint(); + } + + std::shared_ptr> 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( + std::shared_ptr>( + new ConcurrentMap()), + 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(cache_cleanup_period_seconds))) { + RemoveExpiredEntriesNoMutex(); + last_cache_cleanup_timestamp_ = + now + std::chrono::duration(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> cache_; + internal::TimePoint last_cache_cleanup_timestamp_; + ::arrow::util::Mutex mutex_; +}; + +} // namespace parquet::encryption diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/type_fwd.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/type_fwd.h new file mode 100644 index 0000000000000000000000000000000000000000..623811718482c591e708a297dff9eb35ae0c85a9 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/type_fwd.h @@ -0,0 +1,28 @@ +// 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 + +namespace parquet { + +class Decryptor; +class Encryptor; + +class InternalFileDecryptor; +class InternalFileEncryptor; + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/exception.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/exception.h new file mode 100644 index 0000000000000000000000000000000000000000..826f5bdc8bf73741ac37d457d6013dfc8d0fb5a6 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/exception.h @@ -0,0 +1,158 @@ +// 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 +#include +#include +#include + +#include "arrow/type_fwd.h" +#include "arrow/util/string_builder.h" +#include "parquet/platform.h" + +// PARQUET-1085 +#if !defined(ARROW_UNUSED) +#define ARROW_UNUSED(x) UNUSED(x) +#endif + +// Parquet exception to Arrow Status + +#define BEGIN_PARQUET_CATCH_EXCEPTIONS try { +#define END_PARQUET_CATCH_EXCEPTIONS \ + } \ + catch (const ::parquet::ParquetStatusException& e) { \ + return e.status(); \ + } \ + catch (const ::parquet::ParquetException& e) { \ + return ::arrow::Status::IOError(e.what()); \ + } + +// clang-format off + +#define PARQUET_CATCH_NOT_OK(s) \ + BEGIN_PARQUET_CATCH_EXCEPTIONS \ + (s); \ + END_PARQUET_CATCH_EXCEPTIONS + +// clang-format on + +#define PARQUET_CATCH_AND_RETURN(s) \ + BEGIN_PARQUET_CATCH_EXCEPTIONS \ + return (s); \ + END_PARQUET_CATCH_EXCEPTIONS + +// Arrow Status to Parquet exception + +#define PARQUET_IGNORE_NOT_OK(s) \ + do { \ + ::arrow::Status _s = ::arrow::internal::GenericToStatus(s); \ + ARROW_UNUSED(_s); \ + } while (0) + +#define PARQUET_THROW_NOT_OK(s) \ + do { \ + ::arrow::Status _s = ::arrow::internal::GenericToStatus(s); \ + if (!_s.ok()) { \ + throw ::parquet::ParquetStatusException(std::move(_s)); \ + } \ + } while (0) + +#define PARQUET_ASSIGN_OR_THROW_IMPL(status_name, lhs, rexpr) \ + auto status_name = (rexpr); \ + PARQUET_THROW_NOT_OK(status_name.status()); \ + lhs = std::move(status_name).ValueOrDie(); + +#define PARQUET_ASSIGN_OR_THROW(lhs, rexpr) \ + PARQUET_ASSIGN_OR_THROW_IMPL(ARROW_ASSIGN_OR_RAISE_NAME(_error_or_value, __COUNTER__), \ + lhs, rexpr); + +namespace parquet { + +class ParquetException : public std::exception { + public: + PARQUET_NORETURN static void EofException(const std::string& msg = "") { + static std::string prefix = "Unexpected end of stream"; + if (msg.empty()) { + throw ParquetException(prefix); + } + throw ParquetException(prefix, ": ", msg); + } + + PARQUET_NORETURN static void NYI(const std::string& msg = "") { + throw ParquetException("Not yet implemented: ", msg, "."); + } + + template + explicit ParquetException(Args&&... args) + : msg_(::arrow::util::StringBuilder(std::forward(args)...)) {} + + explicit ParquetException(std::string msg) : msg_(std::move(msg)) {} + + explicit ParquetException(const char* msg, const std::exception&) : msg_(msg) {} + + ParquetException(const ParquetException&) = default; + ParquetException& operator=(const ParquetException&) = default; + ParquetException(ParquetException&&) = default; + ParquetException& operator=(ParquetException&&) = default; + + const char* what() const noexcept override { return msg_.c_str(); } + + private: + std::string msg_; +}; + +// Support printing a ParquetException. +// This is needed for clang-on-MSVC as there operator<< is not defined for +// std::exception. +PARQUET_EXPORT +std::ostream& operator<<(std::ostream& os, const ParquetException& exception); + +class ParquetStatusException : public ParquetException { + public: + explicit ParquetStatusException(::arrow::Status status) + : ParquetException(status.ToString()), status_(std::move(status)) {} + + const ::arrow::Status& status() const { return status_; } + + private: + ::arrow::Status status_; +}; + +// This class exists for the purpose of detecting an invalid or corrupted file. +class ParquetInvalidOrCorruptedFileException : public ParquetStatusException { + public: + ParquetInvalidOrCorruptedFileException(const ParquetInvalidOrCorruptedFileException&) = + default; + + template ::value, + int>::type = 0, + typename... Args> + explicit ParquetInvalidOrCorruptedFileException(Arg arg, Args&&... args) + : ParquetStatusException(::arrow::Status::Invalid(std::forward(arg), + std::forward(args)...)) {} +}; + +template +void ThrowNotOk(StatusReturnBlock&& b) { + PARQUET_THROW_NOT_OK(b()); +} + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/file_reader.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/file_reader.h new file mode 100644 index 0000000000000000000000000000000000000000..b59b59f95c2d8766f216a9cd923847d5483de4ee --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/file_reader.h @@ -0,0 +1,231 @@ +// 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 +#include +#include +#include + +#include "arrow/io/caching.h" +#include "arrow/util/type_fwd.h" +#include "parquet/metadata.h" // IWYU pragma: keep +#include "parquet/platform.h" +#include "parquet/properties.h" + +namespace parquet { + +class ColumnReader; +class FileMetaData; +class PageIndexReader; +class BloomFilterReader; +class PageReader; +class RowGroupMetaData; + +namespace internal { +class RecordReader; +} + +class PARQUET_EXPORT RowGroupReader { + public: + // Forward declare a virtual class 'Contents' to aid dependency injection and more + // easily create test fixtures + // An implementation of the Contents class is defined in the .cc file + struct Contents { + virtual ~Contents() {} + virtual std::unique_ptr GetColumnPageReader(int i) = 0; + virtual const RowGroupMetaData* metadata() const = 0; + virtual const ReaderProperties* properties() const = 0; + }; + + explicit RowGroupReader(std::unique_ptr contents); + + // Returns the rowgroup metadata + const RowGroupMetaData* metadata() const; + + // Construct a ColumnReader for the indicated row group-relative + // column. Ownership is shared with the RowGroupReader. + std::shared_ptr Column(int i); + + // EXPERIMENTAL: Construct a RecordReader for the indicated column of the row group. + // Ownership is shared with the RowGroupReader. + std::shared_ptr RecordReader(int i, + bool read_dictionary = false); + + // Construct a ColumnReader, trying to enable exposed encoding. + // + // For dictionary encoding, currently we only support column chunks that are fully + // dictionary encoded, i.e., all data pages in the column chunk are dictionary encoded. + // If a column chunk uses dictionary encoding but then falls back to plain encoding, the + // encoding will not be exposed. + // + // The returned column reader provides an API GetExposedEncoding() for the + // users to check the exposed encoding and determine how to read the batches. + // + // \note API EXPERIMENTAL + std::shared_ptr ColumnWithExposeEncoding( + int i, ExposedEncoding encoding_to_expose); + + // Construct a RecordReader, trying to enable exposed encoding. + // + // For dictionary encoding, currently we only support column chunks that are + // fully dictionary encoded byte arrays. The caller should verify if the reader can read + // and expose the dictionary by checking the reader's read_dictionary(). If a column + // chunk uses dictionary encoding but then falls back to plain encoding, the returned + // reader will read decoded data without exposing the dictionary. + // + // \note API EXPERIMENTAL + std::shared_ptr RecordReaderWithExposeEncoding( + int i, ExposedEncoding encoding_to_expose); + + std::unique_ptr GetColumnPageReader(int i); + + private: + // Holds a pointer to an instance of Contents implementation + std::unique_ptr contents_; +}; + +class PARQUET_EXPORT ParquetFileReader { + public: + // Declare a virtual class 'Contents' to aid dependency injection and more + // easily create test fixtures + // An implementation of the Contents class is defined in the .cc file + struct PARQUET_EXPORT Contents { + static std::unique_ptr Open( + std::shared_ptr<::arrow::io::RandomAccessFile> source, + const ReaderProperties& props = default_reader_properties(), + std::shared_ptr metadata = NULLPTR); + + static ::arrow::Future> OpenAsync( + std::shared_ptr<::arrow::io::RandomAccessFile> source, + const ReaderProperties& props = default_reader_properties(), + std::shared_ptr metadata = NULLPTR); + + virtual ~Contents() = default; + // Perform any cleanup associated with the file contents + virtual void Close() = 0; + virtual std::shared_ptr GetRowGroup(int i) = 0; + virtual std::shared_ptr metadata() const = 0; + virtual std::shared_ptr GetPageIndexReader() = 0; + virtual BloomFilterReader& GetBloomFilterReader() = 0; + }; + + ParquetFileReader(); + ~ParquetFileReader(); + + // Create a file reader instance from an Arrow file object. Thread-safety is + // the responsibility of the file implementation + static std::unique_ptr Open( + std::shared_ptr<::arrow::io::RandomAccessFile> source, + const ReaderProperties& props = default_reader_properties(), + std::shared_ptr metadata = NULLPTR); + + // API Convenience to open a serialized Parquet file on disk, using Arrow IO + // interfaces. + static std::unique_ptr OpenFile( + const std::string& path, bool memory_map = false, + const ReaderProperties& props = default_reader_properties(), + std::shared_ptr metadata = NULLPTR); + + // Asynchronously open a file reader from an Arrow file object. + // Does not throw - all errors are reported through the Future. + static ::arrow::Future> OpenAsync( + std::shared_ptr<::arrow::io::RandomAccessFile> source, + const ReaderProperties& props = default_reader_properties(), + std::shared_ptr metadata = NULLPTR); + + void Open(std::unique_ptr contents); + void Close(); + + // The RowGroupReader is owned by the FileReader + std::shared_ptr RowGroup(int i); + + // Returns the file metadata. Only one instance is ever created + std::shared_ptr metadata() const; + + /// Returns the PageIndexReader. Only one instance is ever created. + /// + /// If the file does not have the page index, nullptr may be returned. + /// Because it pays to check existence of page index in the file, it + /// is possible to return a non null value even if page index does + /// not exist. It is the caller's responsibility to check the return + /// value and follow-up calls to PageIndexReader. + /// + /// WARNING: The returned PageIndexReader must not outlive the ParquetFileReader. + /// Initialize GetPageIndexReader() is not thread-safety. + std::shared_ptr GetPageIndexReader(); + + /// Returns the BloomFilterReader. Only one instance is ever created. + /// + /// WARNING: The returned BloomFilterReader must not outlive the ParquetFileReader. + /// Initialize GetBloomFilterReader() is not thread-safety. + BloomFilterReader& GetBloomFilterReader(); + + /// Pre-buffer the specified column indices in all row groups. + /// + /// Readers can optionally call this to cache the necessary slices + /// of the file in-memory before deserialization. Arrow readers can + /// automatically do this via an option. This is intended to + /// increase performance when reading from high-latency filesystems + /// (e.g. Amazon S3). + /// + /// After calling this, creating readers for row groups/column + /// indices that were not buffered may fail. Creating multiple + /// readers for the a subset of the buffered regions is + /// acceptable. This may be called again to buffer a different set + /// of row groups/columns. + /// + /// If memory usage is a concern, note that data will remain + /// buffered in memory until either \a PreBuffer() is called again, + /// or the reader itself is destructed. Reading - and buffering - + /// only one row group at a time may be useful. + /// + /// This method may throw. + void PreBuffer(const std::vector& row_groups, + const std::vector& column_indices, + const ::arrow::io::IOContext& ctx, + const ::arrow::io::CacheOptions& options); + + /// Wait for the specified row groups and column indices to be pre-buffered. + /// + /// After the returned Future completes, reading the specified row + /// groups/columns will not block. + /// + /// PreBuffer must be called first. This method does not throw. + ::arrow::Future<> WhenBuffered(const std::vector& row_groups, + const std::vector& column_indices) const; + + private: + // Holds a pointer to an instance of Contents implementation + std::unique_ptr contents_; +}; + +// Read only Parquet file metadata +std::shared_ptr PARQUET_EXPORT +ReadMetaData(const std::shared_ptr<::arrow::io::RandomAccessFile>& source); + +/// \brief Scan all values in file. Useful for performance testing +/// \param[in] columns the column numbers to scan. If empty scans all +/// \param[in] column_batch_size number of values to read at a time when scanning column +/// \param[in] reader a ParquetFileReader instance +/// \return number of semantic rows in file +PARQUET_EXPORT +int64_t ScanFileContents(std::vector columns, const int32_t column_batch_size, + ParquetFileReader* reader); + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/file_writer.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/file_writer.h new file mode 100644 index 0000000000000000000000000000000000000000..d5ea1d7c98a0ef8509b4821ab111007d7601996b --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/file_writer.h @@ -0,0 +1,245 @@ +// 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 +#include +#include + +#include "parquet/metadata.h" +#include "parquet/platform.h" +#include "parquet/properties.h" +#include "parquet/schema.h" + +namespace parquet { + +class ColumnWriter; + +// FIXME: copied from reader-internal.cc +static constexpr uint8_t kParquetMagic[4] = {'P', 'A', 'R', '1'}; +static constexpr uint8_t kParquetEMagic[4] = {'P', 'A', 'R', 'E'}; + +class PARQUET_EXPORT RowGroupWriter { + public: + // Forward declare a virtual class 'Contents' to aid dependency injection and more + // easily create test fixtures + // An implementation of the Contents class is defined in the .cc file + struct Contents { + virtual ~Contents() = default; + virtual int num_columns() const = 0; + virtual int64_t num_rows() const = 0; + + // to be used only with ParquetFileWriter::AppendRowGroup + virtual ColumnWriter* NextColumn() = 0; + // to be used only with ParquetFileWriter::AppendBufferedRowGroup + virtual ColumnWriter* column(int i) = 0; + + virtual int current_column() const = 0; + virtual void Close() = 0; + + /// \brief total uncompressed bytes written by the page writer + virtual int64_t total_bytes_written() const = 0; + /// \brief total bytes still compressed but not written by the page writer + virtual int64_t total_compressed_bytes() const = 0; + /// \brief total compressed bytes written by the page writer + virtual int64_t total_compressed_bytes_written() const = 0; + + virtual bool buffered() const = 0; + }; + + explicit RowGroupWriter(std::unique_ptr contents); + + /// Construct a ColumnWriter for the indicated row group-relative column. + /// + /// To be used only with ParquetFileWriter::AppendRowGroup + /// Ownership is solely within the RowGroupWriter. The ColumnWriter is only + /// valid until the next call to NextColumn or Close. As the contents are + /// directly written to the sink, once a new column is started, the contents + /// of the previous one cannot be modified anymore. + ColumnWriter* NextColumn(); + /// Index of currently written column. Equal to -1 if NextColumn() + /// has not been called yet. + int current_column(); + void Close(); + + int num_columns() const; + + /// Construct a ColumnWriter for the indicated row group column. + /// + /// To be used only with ParquetFileWriter::AppendBufferedRowGroup + /// Ownership is solely within the RowGroupWriter. The ColumnWriter is + /// valid until Close. The contents are buffered in memory and written to sink + /// on Close + ColumnWriter* column(int i); + + /** + * Number of rows that shall be written as part of this RowGroup. + */ + int64_t num_rows() const; + + /// \brief total uncompressed bytes written by the page writer + int64_t total_bytes_written() const; + /// \brief total bytes still compressed but not written by the page writer. + /// It will always return 0 from the SerializedPageWriter. + int64_t total_compressed_bytes() const; + /// \brief total compressed bytes written by the page writer + int64_t total_compressed_bytes_written() const; + + /// Returns whether the current RowGroupWriter is in the buffered mode and is created + /// by calling ParquetFileWriter::AppendBufferedRowGroup. + bool buffered() const; + + private: + // Holds a pointer to an instance of Contents implementation + std::unique_ptr contents_; +}; + +PARQUET_EXPORT +void WriteFileMetaData(const FileMetaData& file_metadata, + ::arrow::io::OutputStream* sink); + +PARQUET_EXPORT +void WriteMetaDataFile(const FileMetaData& file_metadata, + ::arrow::io::OutputStream* sink); + +PARQUET_EXPORT +void WriteEncryptedFileMetadata(const FileMetaData& file_metadata, + ArrowOutputStream* sink, + const std::shared_ptr& encryptor, + bool encrypt_footer); + +PARQUET_EXPORT +void WriteEncryptedFileMetadata(const FileMetaData& file_metadata, + ::arrow::io::OutputStream* sink, + const std::shared_ptr& encryptor = NULLPTR, + bool encrypt_footer = false); +PARQUET_EXPORT +void WriteFileCryptoMetaData(const FileCryptoMetaData& crypto_metadata, + ::arrow::io::OutputStream* sink); + +class PARQUET_EXPORT ParquetFileWriter { + public: + // Forward declare a virtual class 'Contents' to aid dependency injection and more + // easily create test fixtures + // An implementation of the Contents class is defined in the .cc file + struct Contents { + Contents(std::shared_ptr<::parquet::schema::GroupNode> schema, + std::shared_ptr key_value_metadata) + : schema_(), key_value_metadata_(std::move(key_value_metadata)) { + schema_.Init(std::move(schema)); + } + virtual ~Contents() {} + // Perform any cleanup associated with the file contents + virtual void Close() = 0; + + virtual RowGroupWriter* AppendRowGroup() = 0; + virtual RowGroupWriter* AppendBufferedRowGroup() = 0; + + virtual int64_t num_rows() const = 0; + virtual int num_columns() const = 0; + virtual int num_row_groups() const = 0; + + virtual const std::shared_ptr& properties() const = 0; + + const std::shared_ptr& key_value_metadata() const { + return key_value_metadata_; + } + + virtual void AddKeyValueMetadata( + const std::shared_ptr& key_value_metadata) = 0; + + // Return const-pointer to make it clear that this object is not to be copied + const SchemaDescriptor* schema() const { return &schema_; } + + SchemaDescriptor schema_; + + /// This should be the only place this is stored. Everything else is a const reference + std::shared_ptr key_value_metadata_; + + const std::shared_ptr& metadata() const { return file_metadata_; } + std::shared_ptr file_metadata_; + }; + + ParquetFileWriter(); + ~ParquetFileWriter(); + + static std::unique_ptr Open( + std::shared_ptr<::arrow::io::OutputStream> sink, + std::shared_ptr schema, + std::shared_ptr properties = default_writer_properties(), + std::shared_ptr key_value_metadata = NULLPTR); + + void Open(std::unique_ptr contents); + void Close(); + + /// Construct a RowGroupWriter with an arbitrary number of rows. + /// + /// Ownership is solely within the ParquetFileWriter. The RowGroupWriter is only valid + /// until the next call to AppendRowGroup or AppendBufferedRowGroup or Close. + RowGroupWriter* AppendRowGroup(); + + /// Construct a RowGroupWriter that buffers all the values until the RowGroup is ready. + /// Use this if you want to write a RowGroup based on a certain size + /// + /// Ownership is solely within the ParquetFileWriter. The RowGroupWriter is only valid + /// until the next call to AppendRowGroup or AppendBufferedRowGroup or Close. + RowGroupWriter* AppendBufferedRowGroup(); + + /// \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(s). + /// \throw ParquetException if Close() has been called. + void AddKeyValueMetadata( + const std::shared_ptr& key_value_metadata); + + /// Number of columns. + /// + /// This number is fixed during the lifetime of the writer as it is determined via + /// the schema. + int num_columns() const; + + /// Number of rows in the yet started RowGroups. + /// + /// Changes on the addition of a new RowGroup. + int64_t num_rows() const; + + /// Number of started RowGroups. + int num_row_groups() const; + + /// Configuration passed to the writer, e.g. the used Parquet format version. + const std::shared_ptr& properties() const; + + /// Returns the file schema descriptor + const SchemaDescriptor* schema() const; + + /// Returns a column descriptor in schema + const ColumnDescriptor* descr(int i) const; + + /// Returns the file custom metadata + const std::shared_ptr& key_value_metadata() const; + + /// Returns the file metadata, only available after calling Close(). + const std::shared_ptr metadata() const; + + private: + // Holds a pointer to an instance of Contents implementation + std::unique_ptr contents_; + std::shared_ptr file_metadata_; +}; + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/hasher.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/hasher.h new file mode 100644 index 0000000000000000000000000000000000000000..519eb459b9ca832d382bc4f9c764b64b47dbd6b0 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/hasher.h @@ -0,0 +1,131 @@ +// 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 +#include "parquet/types.h" + +namespace parquet { +// Abstract class for hash +class Hasher { + public: + /// 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. + 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 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 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 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 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 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 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 the value address. + /// @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 ~Hasher() = default; +}; + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_comparison.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_comparison.h new file mode 100644 index 0000000000000000000000000000000000000000..3ae442dd46e57b7f86b405d9502442d3195719e8 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_comparison.h @@ -0,0 +1,38 @@ +// 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 +#include + +#include "parquet/platform.h" + +namespace parquet::internal { + +/// Builds a bitmap where each set bit indicates the corresponding level is greater +/// than rhs. +uint64_t PARQUET_EXPORT GreaterThanBitmap(const int16_t* levels, int64_t num_levels, + int16_t rhs); + +struct MinMax { + int16_t min; + int16_t max; +}; + +MinMax FindMinMax(const int16_t* levels, int64_t num_levels); + +} // namespace parquet::internal diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_comparison_inc.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_comparison_inc.h new file mode 100644 index 0000000000000000000000000000000000000000..cfee50665433182571a659fbd805f27532a3f7e3 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_comparison_inc.h @@ -0,0 +1,61 @@ +// 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/bit_util.h" +#include "arrow/util/endian.h" +#include "parquet/level_comparison.h" + +// Used to make sure ODR rule isn't violated. +#ifndef PARQUET_IMPL_NAMESPACE +#error "PARQUET_IMPL_NAMESPACE must be defined" +#endif +namespace parquet::internal::PARQUET_IMPL_NAMESPACE { +/// Builds a bitmap by applying predicate to the level vector provided. +/// +/// \param[in] levels Rep or def level array. +/// \param[in] num_levels The number of levels to process (must be [0, 64]) +/// \param[in] predicate The predicate to apply (must have the signature `bool +/// predicate(int16_t)`. +/// \returns The bitmap using least significant "bit" ordering. +/// +template +inline uint64_t LevelsToBitmap(const int16_t* levels, int64_t num_levels, + Predicate predicate) { + // Both clang and GCC can vectorize this automatically with SSE4/AVX2. + uint64_t mask = 0; + for (int x = 0; x < num_levels; x++) { + mask |= static_cast(predicate(levels[x]) ? 1 : 0) << x; + } + return ::arrow::bit_util::ToLittleEndian(mask); +} + +inline MinMax FindMinMaxImpl(const int16_t* levels, int64_t num_levels) { + MinMax out{std::numeric_limits::max(), std::numeric_limits::min()}; + for (int x = 0; x < num_levels; x++) { + out.min = std::min(levels[x], out.min); + out.max = std::max(levels[x], out.max); + } + return out; +} + +inline uint64_t GreaterThanBitmapImpl(const int16_t* levels, int64_t num_levels, + int16_t rhs) { + return LevelsToBitmap(levels, num_levels, [rhs](int16_t value) { return value > rhs; }); +} + +} // namespace parquet::internal::PARQUET_IMPL_NAMESPACE diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_conversion.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_conversion.h new file mode 100644 index 0000000000000000000000000000000000000000..31de95be41c473814c52cd9d2f5902d63f1b944b --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_conversion.h @@ -0,0 +1,216 @@ +// 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 + +#include "arrow/util/endian.h" +#include "parquet/platform.h" +#include "parquet/schema.h" + +namespace parquet::internal { + +struct PARQUET_EXPORT LevelInfo { + LevelInfo() + : null_slot_usage(1), def_level(0), rep_level(0), repeated_ancestor_def_level(0) {} + LevelInfo(int32_t null_slots, int32_t definition_level, int32_t repetition_level, + int32_t repeated_ancestor_definition_level) + : null_slot_usage(null_slots), + def_level(static_cast(definition_level)), + rep_level(static_cast(repetition_level)), + repeated_ancestor_def_level( + static_cast(repeated_ancestor_definition_level)) {} + + bool operator==(const LevelInfo& b) const { + return null_slot_usage == b.null_slot_usage && def_level == b.def_level && + rep_level == b.rep_level && + repeated_ancestor_def_level == b.repeated_ancestor_def_level; + } + + bool HasNullableValues() const { return repeated_ancestor_def_level < def_level; } + + // How many slots an undefined but present (i.e. null) element in + // parquet consumes when decoding to Arrow. + // "Slot" is used in the same context as the Arrow specification + // (i.e. a value holder). + // This is only ever >1 for descendents of FixedSizeList. + int32_t null_slot_usage = 1; + + // The definition level at which the value for the field + // is considered not null (definition levels greater than + // or equal to this value indicate a not-null + // value for the field). For list fields definition levels + // greater than or equal to this field indicate a present, + // possibly null, child value. + int16_t def_level = 0; + + // The repetition level corresponding to this element + // or the closest repeated ancestor. Any repetition + // level less than this indicates either a new list OR + // an empty list (which is determined in conjunction + // with definition levels). + int16_t rep_level = 0; + + // The definition level indicating the level at which the closest + // repeated ancestor is not empty. This is used to discriminate + // between a value less than |def_level| being null or excluded entirely. + // For instance if we have an arrow schema like: + // list(struct(f0: int)). Then then there are the following + // definition levels: + // 0 = null list + // 1 = present but empty list. + // 2 = a null value in the list + // 3 = a non null struct but null integer. + // 4 = a present integer. + // When reconstructing, the struct and integer arrays' + // repeated_ancestor_def_level would be 2. Any + // def_level < 2 indicates that there isn't a corresponding + // child value in the list. + // i.e. [null, [], [null], [{f0: null}], [{f0: 1}]] + // has the def levels [0, 1, 2, 3, 4]. The actual + // struct array is only of length 3: [not-set, set, set] and + // the int array is also of length 3: [N/A, null, 1]. + // + int16_t repeated_ancestor_def_level = 0; + + /// Increments levels according to the cardinality of node. + void Increment(const schema::Node& node) { + if (node.is_repeated()) { + IncrementRepeated(); + return; + } + if (node.is_optional()) { + IncrementOptional(); + return; + } + } + + /// Increments level for a optional node. + void IncrementOptional() { def_level++; } + + /// Increments levels for the repeated node. Returns + /// the previous ancestor_list_def_level. + int16_t IncrementRepeated() { + int16_t last_repeated_ancestor = repeated_ancestor_def_level; + + // Repeated fields add both a repetition and definition level. This is used + // to distinguish between an empty list and a list with an item in it. + ++rep_level; + ++def_level; + // For levels >= repeated_ancestor_def_level it indicates the list was + // non-null and had at least one element. This is important + // for later decoding because we need to add a slot for these + // values. for levels < current_def_level no slots are added + // to arrays. + repeated_ancestor_def_level = def_level; + return last_repeated_ancestor; + } + + // Calculates and returns LevelInfo for a column descriptor. + static LevelInfo ComputeLevelInfo(const ColumnDescriptor* descr) { + LevelInfo level_info; + level_info.def_level = descr->max_definition_level(); + level_info.rep_level = descr->max_repetition_level(); + + int16_t min_spaced_def_level = descr->max_definition_level(); + const ::parquet::schema::Node* node = descr->schema_node().get(); + while (node && !node->is_repeated()) { + if (node->is_optional()) { + min_spaced_def_level--; + } + node = node->parent(); + } + level_info.repeated_ancestor_def_level = min_spaced_def_level; + return level_info; + } + + friend std::ostream& operator<<(std::ostream& os, const LevelInfo& levels) { + // This print method is to silence valgrind issues. What's printed + // is not important because all asserts happen directly on + // members. + os << "{def=" << levels.def_level << ", rep=" << levels.rep_level + << ", repeated_ancestor_def=" << levels.repeated_ancestor_def_level; + if (levels.null_slot_usage > 1) { + os << ", null_slot_usage=" << levels.null_slot_usage; + } + os << "}"; + return os; + } +}; + +// Input/Output structure for reconstructed validity bitmaps. +struct PARQUET_EXPORT ValidityBitmapInputOutput { + // Input only. + // The maximum number of values_read expected (actual + // values read must be less than or equal to this value). + // If this number is exceeded methods will throw a + // ParquetException. Exceeding this limit indicates + // either a corrupt or incorrectly written file. + int64_t values_read_upper_bound = 0; + // Output only. The number of values added to the encountered + // (this is logically the count of the number of elements + // for an Arrow array). + int64_t values_read = 0; + // Input/Output. The number of nulls encountered. + int64_t null_count = 0; + // Output only. The validity bitmap to populate. Maybe be null only + // for DefRepLevelsToListInfo (if all that is needed is list offsets). + uint8_t* valid_bits = NULLPTR; + // Input only, offset into valid_bits to start at. + int64_t valid_bits_offset = 0; +}; + +// Converts def_levels to validity bitmaps for non-list arrays and structs that have +// at least one member that is not a list and has no list descendents. +// For lists use DefRepLevelsToList and structs where all descendants contain +// a list use DefRepLevelsToBitmap. +void PARQUET_EXPORT DefLevelsToBitmap(const int16_t* def_levels, int64_t num_def_levels, + LevelInfo level_info, + ValidityBitmapInputOutput* output); + +// Reconstructs a validity bitmap and list offsets for a list arrays based on +// def/rep levels. The first element of offsets will not be modified if rep_levels +// starts with a new list. The first element of offsets will be used when calculating +// the next offset. See documentation onf DefLevelsToBitmap for when to use this +// method vs the other ones in this file for reconstruction. +// +// Offsets must be sized to 1 + values_read_upper_bound. +void PARQUET_EXPORT DefRepLevelsToList(const int16_t* def_levels, + const int16_t* rep_levels, int64_t num_def_levels, + LevelInfo level_info, + ValidityBitmapInputOutput* output, + int32_t* offsets); +void PARQUET_EXPORT DefRepLevelsToList(const int16_t* def_levels, + const int16_t* rep_levels, int64_t num_def_levels, + LevelInfo level_info, + ValidityBitmapInputOutput* output, + int64_t* offsets); + +// Reconstructs a validity bitmap for a struct every member is a list or has +// a list descendant. See documentation on DefLevelsToBitmap for when more +// details on this method compared to the other ones defined above. +void PARQUET_EXPORT DefRepLevelsToBitmap(const int16_t* def_levels, + const int16_t* rep_levels, + int64_t num_def_levels, LevelInfo level_info, + ValidityBitmapInputOutput* output); + +// This is exposed to ensure we can properly test a software simulated pext function +// (i.e. it isn't hidden by runtime dispatch). +uint64_t PARQUET_EXPORT TestOnlyExtractBitsSoftware(uint64_t bitmap, uint64_t selection); + +} // namespace parquet::internal diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_conversion_inc.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_conversion_inc.h new file mode 100644 index 0000000000000000000000000000000000000000..d1ccedabfde5084ab5c02c2314098122c68ffa81 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/level_conversion_inc.h @@ -0,0 +1,354 @@ +// 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/level_conversion.h" + +#include +#include +#include + +#include "arrow/util/bit_run_reader.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/bitmap_writer.h" +#include "arrow/util/logging.h" +#include "arrow/util/simd.h" +#include "parquet/exception.h" +#include "parquet/level_comparison.h" + +#ifndef PARQUET_IMPL_NAMESPACE +#error "PARQUET_IMPL_NAMESPACE must be defined" +#endif + +namespace parquet::internal::PARQUET_IMPL_NAMESPACE { + +// clang-format off +/* Python code to generate lookup table: + +kLookupBits = 5 +count = 0 +print('constexpr int kLookupBits = {};'.format(kLookupBits)) +print('constexpr uint8_t kPextTable[1 << kLookupBits][1 << kLookupBits] = {') +print(' ', end = '') +for mask in range(1 << kLookupBits): + for data in range(1 << kLookupBits): + bit_value = 0 + bit_len = 0 + for i in range(kLookupBits): + if mask & (1 << i): + bit_value |= (((data >> i) & 1) << bit_len) + bit_len += 1 + out = '0x{:02X},'.format(bit_value) + count += 1 + if count % (1 << kLookupBits) == 1: + print(' {') + if count % 8 == 1: + print(' ', end = '') + if count % 8 == 0: + print(out, end = '\n') + else: + print(out, end = ' ') + if count % (1 << kLookupBits) == 0: + print(' },', end = '') +print('\n};') + +*/ +// clang-format on + +constexpr int kLookupBits = 5; +constexpr uint8_t kPextTable[1 << kLookupBits][1 << kLookupBits] = { + { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }, + { + 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, + 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, + 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, + }, + { + 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, + 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, + 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, + }, + { + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, + 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, + 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, + }, + { + 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, + 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, + }, + { + 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x02, 0x03, 0x00, 0x01, 0x00, + 0x01, 0x02, 0x03, 0x02, 0x03, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, + 0x02, 0x03, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x02, 0x03, + }, + { + 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x00, 0x00, 0x01, + 0x01, 0x02, 0x02, 0x03, 0x03, 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, + 0x03, 0x03, 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, + }, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, + 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + }, + { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + }, + { + 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x02, + 0x03, 0x02, 0x03, 0x02, 0x03, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, + 0x00, 0x01, 0x02, 0x03, 0x02, 0x03, 0x02, 0x03, 0x02, 0x03, + }, + { + 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, + 0x03, 0x02, 0x02, 0x03, 0x03, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, + 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x02, 0x02, 0x03, 0x03, + }, + { + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, + 0x07, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x04, 0x05, 0x06, 0x07, + }, + { + 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, + 0x02, 0x03, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, + 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, + }, + { + 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x02, 0x03, 0x04, 0x05, 0x04, + 0x05, 0x06, 0x07, 0x06, 0x07, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, + 0x02, 0x03, 0x04, 0x05, 0x04, 0x05, 0x06, 0x07, 0x06, 0x07, + }, + { + 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, + 0x05, 0x06, 0x06, 0x07, 0x07, 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, + 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, 0x06, 0x06, 0x07, 0x07, + }, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, + 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + }, + { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, + }, + { + 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, + 0x01, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x02, 0x03, 0x02, 0x03, + 0x02, 0x03, 0x02, 0x03, 0x02, 0x03, 0x02, 0x03, 0x02, 0x03, + }, + { + 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, + 0x01, 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x02, 0x02, + 0x03, 0x03, 0x02, 0x02, 0x03, 0x03, 0x02, 0x02, 0x03, 0x03, + }, + { + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, + 0x03, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x04, 0x05, + 0x06, 0x07, 0x04, 0x05, 0x06, 0x07, 0x04, 0x05, 0x06, 0x07, + }, + { + 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, + 0x03, 0x03, 0x02, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, + }, + { + 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x02, 0x03, 0x00, 0x01, 0x00, + 0x01, 0x02, 0x03, 0x02, 0x03, 0x04, 0x05, 0x04, 0x05, 0x06, 0x07, + 0x06, 0x07, 0x04, 0x05, 0x04, 0x05, 0x06, 0x07, 0x06, 0x07, + }, + { + 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x00, 0x00, 0x01, + 0x01, 0x02, 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, 0x06, 0x06, + 0x07, 0x07, 0x04, 0x04, 0x05, 0x05, 0x06, 0x06, 0x07, 0x07, + }, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, + 0x0E, 0x0F, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + }, + { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, + 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, + 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, + }, + { + 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x02, + 0x03, 0x02, 0x03, 0x02, 0x03, 0x04, 0x05, 0x04, 0x05, 0x04, 0x05, + 0x04, 0x05, 0x06, 0x07, 0x06, 0x07, 0x06, 0x07, 0x06, 0x07, + }, + { + 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, + 0x03, 0x02, 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, 0x05, 0x04, 0x04, + 0x05, 0x05, 0x06, 0x06, 0x07, 0x07, 0x06, 0x06, 0x07, 0x07, + }, + { + 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, + 0x07, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x08, 0x09, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x0C, 0x0D, 0x0E, 0x0F, + }, + { + 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, + 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x05, 0x05, + 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, + }, + { + 0x00, 0x01, 0x00, 0x01, 0x02, 0x03, 0x02, 0x03, 0x04, 0x05, 0x04, + 0x05, 0x06, 0x07, 0x06, 0x07, 0x08, 0x09, 0x08, 0x09, 0x0A, 0x0B, + 0x0A, 0x0B, 0x0C, 0x0D, 0x0C, 0x0D, 0x0E, 0x0F, 0x0E, 0x0F, + }, + { + 0x00, 0x00, 0x01, 0x01, 0x02, 0x02, 0x03, 0x03, 0x04, 0x04, 0x05, + 0x05, 0x06, 0x06, 0x07, 0x07, 0x08, 0x08, 0x09, 0x09, 0x0A, 0x0A, + 0x0B, 0x0B, 0x0C, 0x0C, 0x0D, 0x0D, 0x0E, 0x0E, 0x0F, 0x0F, + }, + { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, + 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, + }, +}; + +inline uint64_t ExtractBitsSoftware(uint64_t bitmap, uint64_t select_bitmap) { + // A software emulation of _pext_u64 + + // These checks should be inline and are likely to be common cases. + if (select_bitmap == ~uint64_t{0}) { + return bitmap; + } else if (select_bitmap == 0) { + return 0; + } + + // Fallback to lookup table method + uint64_t bit_value = 0; + int bit_len = 0; + constexpr uint8_t kLookupMask = (1U << kLookupBits) - 1; + while (select_bitmap != 0) { + const auto mask_len = ARROW_POPCOUNT32(select_bitmap & kLookupMask); + const uint64_t value = kPextTable[select_bitmap & kLookupMask][bitmap & kLookupMask]; + bit_value |= (value << bit_len); + bit_len += mask_len; + bitmap >>= kLookupBits; + select_bitmap >>= kLookupBits; + } + return bit_value; +} + +#ifdef ARROW_HAVE_BMI2 + +// Use _pext_u64 on 64-bit builds, _pext_u32 on 32-bit builds, +#if UINTPTR_MAX == 0xFFFFFFFF + +using extract_bitmap_t = uint32_t; +inline extract_bitmap_t ExtractBits(extract_bitmap_t bitmap, + extract_bitmap_t select_bitmap) { + return _pext_u32(bitmap, select_bitmap); +} + +#else + +using extract_bitmap_t = uint64_t; +inline extract_bitmap_t ExtractBits(extract_bitmap_t bitmap, + extract_bitmap_t select_bitmap) { + return _pext_u64(bitmap, select_bitmap); +} + +#endif + +#else // !defined(ARROW_HAVE_BMI2) + +// Use 64-bit pext emulation when BMI2 isn't available. +using extract_bitmap_t = uint64_t; +inline extract_bitmap_t ExtractBits(extract_bitmap_t bitmap, + extract_bitmap_t select_bitmap) { + return ExtractBitsSoftware(bitmap, select_bitmap); +} + +#endif + +static constexpr int64_t kExtractBitsSize = 8 * sizeof(extract_bitmap_t); + +template +int64_t DefLevelsBatchToBitmap(const int16_t* def_levels, const int64_t batch_size, + int64_t upper_bound_remaining, LevelInfo level_info, + ::arrow::internal::FirstTimeBitmapWriter* writer) { + DCHECK_LE(batch_size, kExtractBitsSize); + + // Greater than level_info.def_level - 1 implies >= the def_level + auto defined_bitmap = static_cast( + internal::GreaterThanBitmap(def_levels, batch_size, level_info.def_level - 1)); + + if (has_repeated_parent) { + // Greater than level_info.repeated_ancestor_def_level - 1 implies >= the + // repeated_ancestor_def_level + auto present_bitmap = static_cast(internal::GreaterThanBitmap( + def_levels, batch_size, level_info.repeated_ancestor_def_level - 1)); + auto selected_bits = ExtractBits(defined_bitmap, present_bitmap); + int64_t selected_count = ::arrow::bit_util::PopCount(present_bitmap); + if (ARROW_PREDICT_FALSE(selected_count > upper_bound_remaining)) { + throw ParquetException("Values read exceeded upper bound"); + } + writer->AppendWord(selected_bits, selected_count); + return ::arrow::bit_util::PopCount(selected_bits); + } else { + if (ARROW_PREDICT_FALSE(batch_size > upper_bound_remaining)) { + std::stringstream ss; + ss << "Values read exceeded upper bound"; + throw ParquetException(ss.str()); + } + + writer->AppendWord(defined_bitmap, batch_size); + return ::arrow::bit_util::PopCount(defined_bitmap); + } +} + +template +void DefLevelsToBitmapSimd(const int16_t* def_levels, int64_t num_def_levels, + LevelInfo level_info, ValidityBitmapInputOutput* output) { + ::arrow::internal::FirstTimeBitmapWriter writer( + output->valid_bits, + /*start_offset=*/output->valid_bits_offset, + /*length=*/output->values_read_upper_bound); + int64_t set_count = 0; + output->values_read = 0; + int64_t values_read_remaining = output->values_read_upper_bound; + while (num_def_levels > kExtractBitsSize) { + set_count += DefLevelsBatchToBitmap( + def_levels, kExtractBitsSize, values_read_remaining, level_info, &writer); + def_levels += kExtractBitsSize; + num_def_levels -= kExtractBitsSize; + values_read_remaining = output->values_read_upper_bound - writer.position(); + } + set_count += DefLevelsBatchToBitmap( + def_levels, num_def_levels, values_read_remaining, level_info, &writer); + + output->values_read = writer.position(); + output->null_count += output->values_read - set_count; + writer.Finish(); +} + +} // namespace parquet::internal::PARQUET_IMPL_NAMESPACE diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/page_index.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/page_index.h new file mode 100644 index 0000000000000000000000000000000000000000..d45c59cab223f13a217c37ed33c6ab3984881b62 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/page_index.h @@ -0,0 +1,372 @@ +// 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/encryption/type_fwd.h" +#include "parquet/types.h" + +#include +#include + +namespace parquet { + +class EncodedStatistics; +struct PageIndexLocation; + +/// \brief ColumnIndex is a proxy around format::ColumnIndex. +class PARQUET_EXPORT ColumnIndex { + public: + /// \brief Create a ColumnIndex from a serialized thrift message. + static std::unique_ptr Make(const ColumnDescriptor& descr, + const void* serialized_index, + uint32_t index_len, + const ReaderProperties& properties, + Decryptor* decryptor = NULLPTR); + + virtual ~ColumnIndex() = default; + + /// \brief A bitmap with a bit set for each data page that has only null values. + /// + /// The length of this vector is equal to the number of data pages in the column. + virtual const std::vector& null_pages() const = 0; + + /// \brief A vector of encoded lower bounds for each data page in this column. + /// + /// `null_pages` should be inspected first, as only pages with non-null values + /// may have their lower bounds populated. + virtual const std::vector& encoded_min_values() const = 0; + + /// \brief A vector of encoded upper bounds for each data page in this column. + /// + /// `null_pages` should be inspected first, as only pages with non-null values + /// may have their upper bounds populated. + virtual const std::vector& encoded_max_values() const = 0; + + /// \brief The ordering of lower and upper bounds. + /// + /// The boundary order applies across all lower bounds, and all upper bounds, + /// respectively. However, the order between lower bounds and upper bounds + /// cannot be derived from this. + virtual BoundaryOrder::type boundary_order() const = 0; + + /// \brief Whether per-page null count information is available. + virtual bool has_null_counts() const = 0; + + /// \brief An optional vector with the number of null values in each data page. + /// + /// `has_null_counts` should be called first to determine if this information is + /// available. + virtual const std::vector& null_counts() const = 0; + + /// \brief A vector of page indices for non-null pages. + virtual const std::vector& non_null_page_indices() const = 0; +}; + +/// \brief Typed implementation of ColumnIndex. +template +class PARQUET_EXPORT TypedColumnIndex : public ColumnIndex { + public: + using T = typename DType::c_type; + + /// \brief A vector of lower bounds for each data page in this column. + /// + /// This is like `encoded_min_values`, but with the values decoded according to + /// the column's physical type. + /// `min_values` and `max_values` can be used together with `boundary_order` + /// in order to prune some data pages when searching for specific values. + virtual const std::vector& min_values() const = 0; + + /// \brief A vector of upper bounds for each data page in this column. + /// + /// Just like `min_values`, but for upper bounds instead of lower bounds. + virtual const std::vector& max_values() const = 0; +}; + +using BoolColumnIndex = TypedColumnIndex; +using Int32ColumnIndex = TypedColumnIndex; +using Int64ColumnIndex = TypedColumnIndex; +using FloatColumnIndex = TypedColumnIndex; +using DoubleColumnIndex = TypedColumnIndex; +using ByteArrayColumnIndex = TypedColumnIndex; +using FLBAColumnIndex = TypedColumnIndex; + +/// \brief PageLocation is a proxy around format::PageLocation. +struct PARQUET_EXPORT PageLocation { + /// File offset of the data page. + int64_t offset; + /// Total compressed size of the data page and header. + int32_t compressed_page_size; + /// Row id of the first row in the page within the row group. + int64_t first_row_index; +}; + +/// \brief OffsetIndex is a proxy around format::OffsetIndex. +class PARQUET_EXPORT OffsetIndex { + public: + /// \brief Create a OffsetIndex from a serialized thrift message. + static std::unique_ptr Make(const void* serialized_index, + uint32_t index_len, + const ReaderProperties& properties, + Decryptor* decryptor = NULLPTR); + + virtual ~OffsetIndex() = default; + + /// \brief A vector of locations for each data page in this column. + virtual const std::vector& page_locations() const = 0; +}; + +/// \brief Interface for reading the page index for a Parquet row group. +class PARQUET_EXPORT RowGroupPageIndexReader { + public: + virtual ~RowGroupPageIndexReader() = default; + + /// \brief Read column index of a column chunk. + /// + /// \param[in] i column ordinal of the column chunk. + /// \returns column index of the column or nullptr if it does not exist. + /// \throws ParquetException if the index is out of bound. + virtual std::shared_ptr GetColumnIndex(int32_t i) = 0; + + /// \brief Read offset index of a column chunk. + /// + /// \param[in] i column ordinal of the column chunk. + /// \returns offset index of the column or nullptr if it does not exist. + /// \throws ParquetException if the index is out of bound. + virtual std::shared_ptr GetOffsetIndex(int32_t i) = 0; +}; + +struct PageIndexSelection { + /// Specifies whether to read the column index. + bool column_index = false; + /// Specifies whether to read the offset index. + bool offset_index = false; +}; + +PARQUET_EXPORT +std::ostream& operator<<(std::ostream& out, const PageIndexSelection& params); + +struct RowGroupIndexReadRange { + /// Base start and total size of column index of all column chunks in a row group. + /// If none of the column chunks have column index, it is set to std::nullopt. + std::optional<::arrow::io::ReadRange> column_index = std::nullopt; + /// Base start and total size of offset index of all column chunks in a row group. + /// If none of the column chunks have offset index, it is set to std::nullopt. + std::optional<::arrow::io::ReadRange> offset_index = std::nullopt; +}; + +/// \brief Interface for reading the page index for a Parquet file. +class PARQUET_EXPORT PageIndexReader { + public: + virtual ~PageIndexReader() = default; + + /// \brief Create a PageIndexReader instance. + /// \returns a PageIndexReader instance. + /// WARNING: The returned PageIndexReader 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 PageIndexReader. + static std::shared_ptr Make( + ::arrow::io::RandomAccessFile* input, std::shared_ptr file_metadata, + const ReaderProperties& properties, + InternalFileDecryptor* file_decryptor = NULLPTR); + + /// \brief Get the page index reader of a specific row group. + /// \param[in] i row group ordinal to get page index reader. + /// \returns RowGroupPageIndexReader of the specified row group. A nullptr may or may + /// not be returned if the page index for the row group is unavailable. It is + /// the caller's responsibility to check the return value of follow-up calls + /// to the RowGroupPageIndexReader. + /// \throws ParquetException if the index is out of bound. + virtual std::shared_ptr RowGroup(int i) = 0; + + /// \brief Advise the reader which part of page index will be read later. + /// + /// The PageIndexReader can optionally prefetch and cache page index that + /// may be read later to get better performance. + /// + /// The contract of this function is as below: + /// 1) If WillNeed() has not been called for a specific row group and the page index + /// exists, follow-up calls to get column index or offset index of all columns in + /// this row group SHOULD NOT FAIL, but the performance may not be optimal. + /// 2) If WillNeed() has been called for a specific row group, follow-up calls to get + /// page index are limited to columns and index type requested by WillNeed(). + /// So it MAY FAIL if columns that are not requested by WillNeed() are requested. + /// 3) Later calls to WillNeed() MAY OVERRIDE previous calls of same row groups. + /// For example, + /// 1) If WillNeed() is not called for row group 0, then follow-up calls to read + /// column index and/or offset index of all columns of row group 0 should not + /// fail if its page index exists. + /// 2) If WillNeed() is called for columns 0 and 1 for row group 0, then follow-up + /// call to read page index of column 2 for row group 0 MAY FAIL even if its + /// page index exists. + /// 3) If WillNeed() is called for row group 0 with offset index only, then + /// follow-up call to read column index of row group 0 MAY FAIL even if + /// the column index of this column exists. + /// 4) If WillNeed() is called for columns 0 and 1 for row group 0, then later + /// call to WillNeed() for columns 1 and 2 for row group 0. The later one + /// overrides previous call and only columns 1 and 2 of row group 0 are allowed + /// to access. + /// + /// \param[in] row_group_indices list of row group ordinal to read page index later. + /// \param[in] column_indices list of column ordinal to read page index later. If it is + /// empty, it means all columns in the row group will be read. + /// \param[in] selection which kind of page index is required later. + virtual void WillNeed(const std::vector& row_group_indices, + const std::vector& column_indices, + const PageIndexSelection& selection) = 0; + + /// \brief Advise the reader page index of these row groups will not be read anymore. + /// + /// The PageIndexReader implementation has the opportunity to cancel any prefetch or + /// release resource that are related to these row groups. + /// + /// \param[in] row_group_indices list of row group ordinal that whose page index will + /// not be accessed anymore. + virtual void WillNotNeed(const std::vector& row_group_indices) = 0; + + /// \brief Determine the column index and offset index ranges for the given row group. + /// + /// \param[in] row_group_metadata row group metadata to get column chunk metadata. + /// \param[in] columns list of column ordinals to get page index. If the list is empty, + /// it means all columns in the row group. + /// \returns RowGroupIndexReadRange of the specified row group. Throws ParquetException + /// if the selected column ordinal is out of bound or metadata of page index + /// is corrupted. + static RowGroupIndexReadRange DeterminePageIndexRangesInRowGroup( + const RowGroupMetaData& row_group_metadata, const std::vector& columns); +}; + +/// \brief Interface for collecting column index of data pages in a column chunk. +class PARQUET_EXPORT ColumnIndexBuilder { + public: + /// \brief API convenience to create a ColumnIndexBuilder. + static std::unique_ptr Make(const ColumnDescriptor* descr); + + virtual ~ColumnIndexBuilder() = default; + + /// \brief Add statistics of a data page. + /// + /// If the ColumnIndexBuilder has seen any corrupted statistics, it will + /// not update statistics anymore. + /// + /// \param stats Page statistics in the encoded form. + virtual void AddPage(const EncodedStatistics& stats) = 0; + + /// \brief Complete the column index. + /// + /// Once called, AddPage() can no longer be called. + /// WriteTo() and Build() can only called after Finish() has been called. + virtual void Finish() = 0; + + /// \brief Serialize the column index thrift message. + /// + /// If the ColumnIndexBuilder has seen any corrupted statistics, it will + /// not write any data to the sink. + /// + /// \param[out] sink output stream to write the serialized message. + /// \param[in] encryptor encryptor to encrypt the serialized column index. + virtual void WriteTo(::arrow::io::OutputStream* sink, + Encryptor* encryptor = NULLPTR) const = 0; + + /// \brief Create a ColumnIndex directly. + /// + /// \return If the ColumnIndexBuilder has seen any corrupted statistics, it simply + /// returns nullptr. Otherwise the column index is built and returned. + virtual std::unique_ptr Build() const = 0; +}; + +/// \brief Interface for collecting offset index of data pages in a column chunk. +class PARQUET_EXPORT OffsetIndexBuilder { + public: + /// \brief API convenience to create a OffsetIndexBuilder. + static std::unique_ptr Make(); + + virtual ~OffsetIndexBuilder() = default; + + /// \brief Add page location of a data page. + virtual void AddPage(int64_t offset, int32_t compressed_page_size, + int64_t first_row_index) = 0; + + /// \brief Add page location of a data page. + void AddPage(const PageLocation& page_location) { + AddPage(page_location.offset, page_location.compressed_page_size, + page_location.first_row_index); + } + + /// \brief Complete the offset index. + /// + /// In the buffered row group mode, data pages are flushed into memory + /// sink and the OffsetIndexBuilder has only collected the relative offset + /// which requires adjustment once they are flushed to the file. + /// + /// \param final_position Final stream offset to add for page offset adjustment. + virtual void Finish(int64_t final_position) = 0; + + /// \brief Serialize the offset index thrift message. + /// + /// \param[out] sink output stream to write the serialized message. + /// \param[in] encryptor encryptor to encrypt the serialized offset index. + virtual void WriteTo(::arrow::io::OutputStream* sink, + Encryptor* encryptor = NULLPTR) const = 0; + + /// \brief Create an OffsetIndex directly. + virtual std::unique_ptr Build() const = 0; +}; + +/// \brief Interface for collecting page index of a parquet file. +class PARQUET_EXPORT PageIndexBuilder { + public: + /// \brief API convenience to create a PageIndexBuilder. + static std::unique_ptr Make( + const SchemaDescriptor* schema, InternalFileEncryptor* file_encryptor = NULLPTR); + + virtual ~PageIndexBuilder() = default; + + /// \brief Start a new row group. + virtual void AppendRowGroup() = 0; + + /// \brief Get the ColumnIndexBuilder from column ordinal. + /// + /// \param i Column ordinal. + /// \return ColumnIndexBuilder for the column and its memory ownership belongs to + /// the PageIndexBuilder. + virtual ColumnIndexBuilder* GetColumnIndexBuilder(int32_t i) = 0; + + /// \brief Get the OffsetIndexBuilder from column ordinal. + /// + /// \param i Column ordinal. + /// \return OffsetIndexBuilder for the column and its memory ownership belongs to + /// the PageIndexBuilder. + virtual OffsetIndexBuilder* GetOffsetIndexBuilder(int32_t i) = 0; + + /// \brief Complete the page index builder and no more write is allowed. + virtual void Finish() = 0; + + /// \brief Serialize the page index thrift message. + /// + /// Only valid column indexes and offset indexes are serialized and their locations + /// are set. + /// + /// \param[out] sink The output stream to write the page index. + /// \param[out] location The location of all page index to the start of sink. + virtual void WriteTo(::arrow::io::OutputStream* sink, + PageIndexLocation* location) const = 0; +}; + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/parquet_version.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/parquet_version.h new file mode 100644 index 0000000000000000000000000000000000000000..01128941e132102ef7e6f5c90202b16d863e91fc --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/parquet_version.h @@ -0,0 +1,31 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef PARQUET_VERSION_H +#define PARQUET_VERSION_H + +#define PARQUET_VERSION_MAJOR 17 +#define PARQUET_VERSION_MINOR 0 +#define PARQUET_VERSION_PATCH 0 + +#define PARQUET_SO_VERSION "1700" +#define PARQUET_FULL_SO_VERSION "1700.0.0" + +// define the parquet created by version +#define CREATED_BY_VERSION "parquet-cpp-arrow version 17.0.0" + +#endif // PARQUET_VERSION_H diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/pch.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/pch.h new file mode 100644 index 0000000000000000000000000000000000000000..59e64bfc6e64d2091949af2fee840548695cc498 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/pch.h @@ -0,0 +1,28 @@ +// 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. + +// Often-used headers, for precompiling. +// If updating this header, please make sure you check compilation speed +// before checking in. Adding headers which are not used extremely often +// may incur a slowdown, since it makes the precompiled header heavier to load. + +#include "parquet/encoding.h" +#include "parquet/exception.h" +#include "parquet/metadata.h" +#include "parquet/properties.h" +#include "parquet/schema.h" +#include "parquet/types.h" diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/platform.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/platform.h new file mode 100644 index 0000000000000000000000000000000000000000..b085e57cd9918e3c156bb6f6dc367f931d156fc2 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/platform.h @@ -0,0 +1,112 @@ +// 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 +#include + +#include "arrow/buffer.h" // IWYU pragma: export +#include "arrow/io/interfaces.h" // IWYU pragma: export +#include "arrow/status.h" // IWYU pragma: export +#include "arrow/type_fwd.h" // IWYU pragma: export +#include "arrow/util/macros.h" // IWYU pragma: export + +#if defined(_WIN32) || defined(__CYGWIN__) + +#if defined(_MSC_VER) +#pragma warning(push) +// Disable warning for STL types usage in DLL interface +// https://web.archive.org/web/20130317015847/http://connect.microsoft.com/VisualStudio/feedback/details/696593/vc-10-vs-2010-basic-string-exports +#pragma warning(disable : 4275 4251) +// Disable diamond inheritance warnings +#pragma warning(disable : 4250) +// Disable macro redefinition warnings +#pragma warning(disable : 4005) +// Disable extern before exported template warnings +#pragma warning(disable : 4910) +#else +#pragma GCC diagnostic ignored "-Wattributes" +#endif + +#ifdef PARQUET_STATIC +#define PARQUET_EXPORT +#elif defined(PARQUET_EXPORTING) +#define PARQUET_EXPORT __declspec(dllexport) +#else +#define PARQUET_EXPORT __declspec(dllimport) +#endif + +#define PARQUET_NO_EXPORT + +#else // Not Windows +#ifndef PARQUET_EXPORT +#define PARQUET_EXPORT __attribute__((visibility("default"))) +#endif +#ifndef PARQUET_NO_EXPORT +#define PARQUET_NO_EXPORT __attribute__((visibility("hidden"))) +#endif +#endif // Non-Windows + +// This is a complicated topic, some reading on it: +// http://www.codesynthesis.com/~boris/blog/2010/01/18/dll-export-cxx-templates/ +#if defined(_MSC_VER) || defined(__clang__) +#define PARQUET_TEMPLATE_CLASS_EXPORT +#define PARQUET_TEMPLATE_EXPORT PARQUET_EXPORT +#else +#define PARQUET_TEMPLATE_CLASS_EXPORT PARQUET_EXPORT +#define PARQUET_TEMPLATE_EXPORT +#endif + +#define PARQUET_DISALLOW_COPY_AND_ASSIGN ARROW_DISALLOW_COPY_AND_ASSIGN + +#define PARQUET_NORETURN ARROW_NORETURN +#define PARQUET_DEPRECATED ARROW_DEPRECATED + +// If ARROW_VALGRIND set when compiling unit tests, also define +// PARQUET_VALGRIND +#ifdef ARROW_VALGRIND +#define PARQUET_VALGRIND +#endif + +namespace parquet { + +using Buffer = ::arrow::Buffer; +using Codec = ::arrow::util::Codec; +using CodecOptions = ::arrow::util::CodecOptions; +using Compression = ::arrow::Compression; +using MemoryPool = ::arrow::MemoryPool; +using MutableBuffer = ::arrow::MutableBuffer; +using ResizableBuffer = ::arrow::ResizableBuffer; +using ResizableBuffer = ::arrow::ResizableBuffer; +using ArrowInputFile = ::arrow::io::RandomAccessFile; +using ArrowInputStream = ::arrow::io::InputStream; +using ArrowOutputStream = ::arrow::io::OutputStream; + +constexpr int64_t kDefaultOutputStreamSize = 1024; + +constexpr int16_t kNonPageOrdinal = static_cast(-1); + +PARQUET_EXPORT +std::shared_ptr<::arrow::io::BufferOutputStream> CreateOutputStream( + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()); + +PARQUET_EXPORT +std::shared_ptr AllocateBuffer( + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool(), int64_t size = 0); + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/printer.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/printer.h new file mode 100644 index 0000000000000000000000000000000000000000..6bdf5b456fa6b2d5f478e3880762810f52fbab65 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/printer.h @@ -0,0 +1,46 @@ +// 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 +#include + +#include "parquet/platform.h" + +namespace parquet { + +class ParquetFileReader; + +class PARQUET_EXPORT ParquetFilePrinter { + private: + ParquetFileReader* fileReader; + + public: + explicit ParquetFilePrinter(ParquetFileReader* reader) : fileReader(reader) {} + ~ParquetFilePrinter() {} + + void DebugPrint(std::ostream& stream, std::list selected_columns, + bool print_values = false, bool format_dump = false, + bool print_key_value_metadata = false, + const char* filename = "No Name"); + + void JSONPrint(std::ostream& stream, std::list selected_columns, + const char* filename = "No Name"); +}; + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/properties.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/properties.h new file mode 100644 index 0000000000000000000000000000000000000000..4d3acb491e3906c4183dfcb0a8d9637a47fd082f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/properties.h @@ -0,0 +1,1183 @@ +// 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 +#include +#include +#include +#include + +#include "arrow/io/caching.h" +#include "arrow/type.h" +#include "arrow/util/compression.h" +#include "arrow/util/type_fwd.h" +#include "parquet/encryption/encryption.h" +#include "parquet/exception.h" +#include "parquet/parquet_version.h" +#include "parquet/platform.h" +#include "parquet/schema.h" +#include "parquet/type_fwd.h" +#include "parquet/types.h" + +namespace parquet { + +/// Controls serialization format of data pages. parquet-format v2.0.0 +/// introduced a new data page metadata type DataPageV2 and serialized page +/// structure (for example, encoded levels are no longer compressed). Prior to +/// the completion of PARQUET-457 in 2020, this library did not implement +/// DataPageV2 correctly, so if you use the V2 data page format, you may have +/// forward compatibility issues (older versions of the library will be unable +/// to read the files). Note that some Parquet implementations do not implement +/// DataPageV2 at all. +enum class ParquetDataPageVersion { V1, V2 }; + +/// Align the default buffer size to a small multiple of a page size. +constexpr int64_t kDefaultBufferSize = 4096 * 4; + +constexpr int32_t kDefaultThriftStringSizeLimit = 100 * 1000 * 1000; +// Structs in the thrift definition are relatively large (at least 300 bytes). +// This limits total memory to the same order of magnitude as +// kDefaultStringSizeLimit. +constexpr int32_t kDefaultThriftContainerSizeLimit = 1000 * 1000; + +class PARQUET_EXPORT ReaderProperties { + public: + explicit ReaderProperties(MemoryPool* pool = ::arrow::default_memory_pool()) + : pool_(pool) {} + + MemoryPool* memory_pool() const { return pool_; } + + std::shared_ptr GetStream(std::shared_ptr source, + int64_t start, int64_t num_bytes); + + /// Buffered stream reading allows the user to control the memory usage of + /// parquet readers. This ensure that all `RandomAccessFile::ReadAt` calls are + /// wrapped in a buffered reader that uses a fix sized buffer (of size + /// `buffer_size()`) instead of the full size of the ReadAt. + /// + /// The primary reason for this control knobs is for resource control and not + /// performance. + bool is_buffered_stream_enabled() const { return buffered_stream_enabled_; } + /// Enable buffered stream reading. + void enable_buffered_stream() { buffered_stream_enabled_ = true; } + /// Disable buffered stream reading. + void disable_buffered_stream() { buffered_stream_enabled_ = false; } + + bool read_dense_for_nullable() const { return read_dense_for_nullable_; } + void enable_read_dense_for_nullable() { read_dense_for_nullable_ = true; } + void disable_read_dense_for_nullable() { read_dense_for_nullable_ = false; } + + /// Return the size of the buffered stream buffer. + int64_t buffer_size() const { return buffer_size_; } + /// Set the size of the buffered stream buffer in bytes. + void set_buffer_size(int64_t size) { buffer_size_ = size; } + + /// \brief Return the size limit on thrift strings. + /// + /// This limit helps prevent space and time bombs in files, but may need to + /// be increased in order to read files with especially large headers. + int32_t thrift_string_size_limit() const { return thrift_string_size_limit_; } + /// Set the size limit on thrift strings. + void set_thrift_string_size_limit(int32_t size) { thrift_string_size_limit_ = size; } + + /// \brief Return the size limit on thrift containers. + /// + /// This limit helps prevent space and time bombs in files, but may need to + /// be increased in order to read files with especially large headers. + int32_t thrift_container_size_limit() const { return thrift_container_size_limit_; } + /// Set the size limit on thrift containers. + void set_thrift_container_size_limit(int32_t size) { + thrift_container_size_limit_ = size; + } + + /// Set the decryption properties. + void file_decryption_properties(std::shared_ptr decryption) { + file_decryption_properties_ = std::move(decryption); + } + /// Return the decryption properties. + const std::shared_ptr& file_decryption_properties() const { + return file_decryption_properties_; + } + + bool page_checksum_verification() const { return page_checksum_verification_; } + void set_page_checksum_verification(bool check_crc) { + page_checksum_verification_ = check_crc; + } + + private: + MemoryPool* pool_; + int64_t buffer_size_ = kDefaultBufferSize; + int32_t thrift_string_size_limit_ = kDefaultThriftStringSizeLimit; + int32_t thrift_container_size_limit_ = kDefaultThriftContainerSizeLimit; + bool buffered_stream_enabled_ = false; + bool page_checksum_verification_ = false; + // Used with a RecordReader. + bool read_dense_for_nullable_ = false; + std::shared_ptr file_decryption_properties_; +}; + +ReaderProperties PARQUET_EXPORT default_reader_properties(); + +static constexpr int64_t kDefaultDataPageSize = 1024 * 1024; +static constexpr bool DEFAULT_IS_DICTIONARY_ENABLED = true; +static constexpr int64_t DEFAULT_DICTIONARY_PAGE_SIZE_LIMIT = kDefaultDataPageSize; +static constexpr int64_t DEFAULT_WRITE_BATCH_SIZE = 1024; +static constexpr int64_t DEFAULT_MAX_ROW_GROUP_LENGTH = 1024 * 1024; +static constexpr bool DEFAULT_ARE_STATISTICS_ENABLED = true; +static constexpr int64_t DEFAULT_MAX_STATISTICS_SIZE = 4096; +static constexpr Encoding::type DEFAULT_ENCODING = Encoding::UNKNOWN; +static const char DEFAULT_CREATED_BY[] = CREATED_BY_VERSION; +static constexpr Compression::type DEFAULT_COMPRESSION_TYPE = Compression::UNCOMPRESSED; +static constexpr bool DEFAULT_IS_PAGE_INDEX_ENABLED = false; + +class PARQUET_EXPORT ColumnProperties { + public: + ColumnProperties(Encoding::type encoding = DEFAULT_ENCODING, + Compression::type codec = DEFAULT_COMPRESSION_TYPE, + bool dictionary_enabled = DEFAULT_IS_DICTIONARY_ENABLED, + bool statistics_enabled = DEFAULT_ARE_STATISTICS_ENABLED, + size_t max_stats_size = DEFAULT_MAX_STATISTICS_SIZE, + bool page_index_enabled = DEFAULT_IS_PAGE_INDEX_ENABLED) + : encoding_(encoding), + codec_(codec), + dictionary_enabled_(dictionary_enabled), + statistics_enabled_(statistics_enabled), + max_stats_size_(max_stats_size), + page_index_enabled_(page_index_enabled) {} + + void set_encoding(Encoding::type encoding) { encoding_ = encoding; } + + void set_compression(Compression::type codec) { codec_ = codec; } + + void set_dictionary_enabled(bool dictionary_enabled) { + dictionary_enabled_ = dictionary_enabled; + } + + void set_statistics_enabled(bool statistics_enabled) { + statistics_enabled_ = statistics_enabled; + } + + void set_max_statistics_size(size_t max_stats_size) { + max_stats_size_ = max_stats_size; + } + + void set_compression_level(int compression_level) { + if (!codec_options_) { + codec_options_ = std::make_shared(); + } + codec_options_->compression_level = compression_level; + } + + void set_codec_options(const std::shared_ptr& codec_options) { + codec_options_ = codec_options; + } + + void set_page_index_enabled(bool page_index_enabled) { + page_index_enabled_ = page_index_enabled; + } + + Encoding::type encoding() const { return encoding_; } + + Compression::type compression() const { return codec_; } + + bool dictionary_enabled() const { return dictionary_enabled_; } + + bool statistics_enabled() const { return statistics_enabled_; } + + size_t max_statistics_size() const { return max_stats_size_; } + + int compression_level() const { + if (!codec_options_) { + return ::arrow::util::kUseDefaultCompressionLevel; + } + return codec_options_->compression_level; + } + + const std::shared_ptr& codec_options() const { return codec_options_; } + + bool page_index_enabled() const { return page_index_enabled_; } + + private: + Encoding::type encoding_; + Compression::type codec_; + bool dictionary_enabled_; + bool statistics_enabled_; + size_t max_stats_size_; + std::shared_ptr codec_options_; + bool page_index_enabled_; +}; + +class PARQUET_EXPORT WriterProperties { + public: + class Builder { + public: + Builder() + : pool_(::arrow::default_memory_pool()), + dictionary_pagesize_limit_(DEFAULT_DICTIONARY_PAGE_SIZE_LIMIT), + write_batch_size_(DEFAULT_WRITE_BATCH_SIZE), + max_row_group_length_(DEFAULT_MAX_ROW_GROUP_LENGTH), + pagesize_(kDefaultDataPageSize), + version_(ParquetVersion::PARQUET_2_6), + data_page_version_(ParquetDataPageVersion::V1), + created_by_(DEFAULT_CREATED_BY), + store_decimal_as_integer_(false), + page_checksum_enabled_(false) {} + + explicit Builder(const WriterProperties& properties) + : pool_(properties.memory_pool()), + dictionary_pagesize_limit_(properties.dictionary_pagesize_limit()), + write_batch_size_(properties.write_batch_size()), + max_row_group_length_(properties.max_row_group_length()), + pagesize_(properties.data_pagesize()), + version_(properties.version()), + data_page_version_(properties.data_page_version()), + created_by_(properties.created_by()), + store_decimal_as_integer_(properties.store_decimal_as_integer()), + page_checksum_enabled_(properties.page_checksum_enabled()), + sorting_columns_(properties.sorting_columns()), + default_column_properties_(properties.default_column_properties()) {} + + virtual ~Builder() {} + + /// Specify the memory pool for the writer. Default default_memory_pool. + Builder* memory_pool(MemoryPool* pool) { + pool_ = pool; + return this; + } + + /// Enable dictionary encoding in general for all columns. Default + /// enabled. + Builder* enable_dictionary() { + default_column_properties_.set_dictionary_enabled(true); + return this; + } + + /// Disable dictionary encoding in general for all columns. Default + /// enabled. + Builder* disable_dictionary() { + default_column_properties_.set_dictionary_enabled(false); + return this; + } + + /// Enable dictionary encoding for column specified by `path`. Default + /// enabled. + Builder* enable_dictionary(const std::string& path) { + dictionary_enabled_[path] = true; + return this; + } + + /// Enable dictionary encoding for column specified by `path`. Default + /// enabled. + Builder* enable_dictionary(const std::shared_ptr& path) { + return this->enable_dictionary(path->ToDotString()); + } + + /// Disable dictionary encoding for column specified by `path`. Default + /// enabled. + Builder* disable_dictionary(const std::string& path) { + dictionary_enabled_[path] = false; + return this; + } + + /// Disable dictionary encoding for column specified by `path`. Default + /// enabled. + Builder* disable_dictionary(const std::shared_ptr& path) { + return this->disable_dictionary(path->ToDotString()); + } + + /// Specify the dictionary page size limit per row group. Default 1MB. + Builder* dictionary_pagesize_limit(int64_t dictionary_psize_limit) { + dictionary_pagesize_limit_ = dictionary_psize_limit; + return this; + } + + /// Specify the write batch size while writing batches of Arrow values + /// into Parquet. Default 1024. + Builder* write_batch_size(int64_t write_batch_size) { + write_batch_size_ = write_batch_size; + return this; + } + + /// Specify the max number of rows to put in a single row group. + /// Default 1Mi rows. + Builder* max_row_group_length(int64_t max_row_group_length) { + max_row_group_length_ = max_row_group_length; + return this; + } + + /// Specify the data page size. + /// Default 1MB. + Builder* data_pagesize(int64_t pg_size) { + pagesize_ = pg_size; + return this; + } + + /// Specify the data page version. + /// Default V1. + Builder* data_page_version(ParquetDataPageVersion data_page_version) { + data_page_version_ = data_page_version; + return this; + } + + /// Specify the Parquet file version. + /// Default PARQUET_2_6. + Builder* version(ParquetVersion::type version) { + version_ = version; + return this; + } + + Builder* created_by(const std::string& created_by) { + created_by_ = created_by; + return this; + } + + Builder* enable_page_checksum() { + page_checksum_enabled_ = true; + return this; + } + + Builder* disable_page_checksum() { + page_checksum_enabled_ = false; + return this; + } + + /// \brief Define the encoding that is used when we don't utilise dictionary encoding. + // + /// This either apply if dictionary encoding is disabled or if we fallback + /// as the dictionary grew too large. + Builder* encoding(Encoding::type encoding_type) { + if (encoding_type == Encoding::PLAIN_DICTIONARY || + encoding_type == Encoding::RLE_DICTIONARY) { + throw ParquetException("Can't use dictionary encoding as fallback encoding"); + } + + default_column_properties_.set_encoding(encoding_type); + return this; + } + + /// \brief Define the encoding that is used when we don't utilise dictionary encoding. + // + /// This either apply if dictionary encoding is disabled or if we fallback + /// as the dictionary grew too large. + Builder* encoding(const std::string& path, Encoding::type encoding_type) { + if (encoding_type == Encoding::PLAIN_DICTIONARY || + encoding_type == Encoding::RLE_DICTIONARY) { + throw ParquetException("Can't use dictionary encoding as fallback encoding"); + } + + encodings_[path] = encoding_type; + return this; + } + + /// \brief Define the encoding that is used when we don't utilise dictionary encoding. + // + /// This either apply if dictionary encoding is disabled or if we fallback + /// as the dictionary grew too large. + Builder* encoding(const std::shared_ptr& path, + Encoding::type encoding_type) { + return this->encoding(path->ToDotString(), encoding_type); + } + + /// Specify compression codec in general for all columns. + /// Default UNCOMPRESSED. + Builder* compression(Compression::type codec) { + default_column_properties_.set_compression(codec); + return this; + } + + /// Specify max statistics size to store min max value. + /// Default 4KB. + Builder* max_statistics_size(size_t max_stats_sz) { + default_column_properties_.set_max_statistics_size(max_stats_sz); + return this; + } + + /// Specify compression codec for the column specified by `path`. + /// Default UNCOMPRESSED. + Builder* compression(const std::string& path, Compression::type codec) { + codecs_[path] = codec; + return this; + } + + /// Specify compression codec for the column specified by `path`. + /// Default UNCOMPRESSED. + Builder* compression(const std::shared_ptr& path, + Compression::type codec) { + return this->compression(path->ToDotString(), codec); + } + + /// \brief Specify the default compression level for the compressor in + /// every column. In case a column does not have an explicitly specified + /// compression level, the default one would be used. + /// + /// The provided compression level is compressor specific. The user would + /// have to familiarize oneself with the available levels for the selected + /// compressor. If the compressor does not allow for selecting different + /// compression levels, calling this function would not have any effect. + /// Parquet and Arrow do not validate the passed compression level. If no + /// level is selected by the user or if the special + /// std::numeric_limits::min() value is passed, then Arrow selects the + /// compression level. + /// + /// If other compressor-specific options need to be set in addition to the compression + /// level, use the codec_options method. + Builder* compression_level(int compression_level) { + default_column_properties_.set_compression_level(compression_level); + return this; + } + + /// \brief Specify a compression level for the compressor for the column + /// described by path. + /// + /// The provided compression level is compressor specific. The user would + /// have to familiarize oneself with the available levels for the selected + /// compressor. If the compressor does not allow for selecting different + /// compression levels, calling this function would not have any effect. + /// Parquet and Arrow do not validate the passed compression level. If no + /// level is selected by the user or if the special + /// std::numeric_limits::min() value is passed, then Arrow selects the + /// compression level. + Builder* compression_level(const std::string& path, int compression_level) { + if (!codec_options_[path]) { + codec_options_[path] = std::make_shared(); + } + codec_options_[path]->compression_level = compression_level; + return this; + } + + /// \brief Specify a compression level for the compressor for the column + /// described by path. + /// + /// The provided compression level is compressor specific. The user would + /// have to familiarize oneself with the available levels for the selected + /// compressor. If the compressor does not allow for selecting different + /// compression levels, calling this function would not have any effect. + /// Parquet and Arrow do not validate the passed compression level. If no + /// level is selected by the user or if the special + /// std::numeric_limits::min() value is passed, then Arrow selects the + /// compression level. + Builder* compression_level(const std::shared_ptr& path, + int compression_level) { + return this->compression_level(path->ToDotString(), compression_level); + } + + /// \brief Specify the default codec options for the compressor in + /// every column. + /// + /// The codec options allow configuring the compression level as well + /// as other codec-specific options. + Builder* codec_options( + const std::shared_ptr<::arrow::util::CodecOptions>& codec_options) { + default_column_properties_.set_codec_options(codec_options); + return this; + } + + /// \brief Specify the codec options for the compressor for the column + /// described by path. + Builder* codec_options( + const std::string& path, + const std::shared_ptr<::arrow::util::CodecOptions>& codec_options) { + codec_options_[path] = codec_options; + return this; + } + + /// \brief Specify the codec options for the compressor for the column + /// described by path. + Builder* codec_options( + const std::shared_ptr& path, + const std::shared_ptr<::arrow::util::CodecOptions>& codec_options) { + return this->codec_options(path->ToDotString(), codec_options); + } + + /// Define the file encryption properties. + /// Default NULL. + Builder* encryption( + std::shared_ptr file_encryption_properties) { + file_encryption_properties_ = std::move(file_encryption_properties); + return this; + } + + /// Enable statistics in general. + /// Default enabled. + Builder* enable_statistics() { + default_column_properties_.set_statistics_enabled(true); + return this; + } + + /// Disable statistics in general. + /// Default enabled. + Builder* disable_statistics() { + default_column_properties_.set_statistics_enabled(false); + return this; + } + + /// Enable statistics for the column specified by `path`. + /// Default enabled. + Builder* enable_statistics(const std::string& path) { + statistics_enabled_[path] = true; + return this; + } + + /// Enable statistics for the column specified by `path`. + /// Default enabled. + Builder* enable_statistics(const std::shared_ptr& path) { + return this->enable_statistics(path->ToDotString()); + } + + /// Define the sorting columns. + /// Default empty. + /// + /// If sorting columns are set, user should ensure that records + /// are sorted by sorting columns. Otherwise, the storing data + /// will be inconsistent with sorting_columns metadata. + Builder* set_sorting_columns(std::vector sorting_columns) { + sorting_columns_ = std::move(sorting_columns); + return this; + } + + /// Disable statistics for the column specified by `path`. + /// Default enabled. + Builder* disable_statistics(const std::string& path) { + statistics_enabled_[path] = false; + return this; + } + + /// Disable statistics for the column specified by `path`. + /// Default enabled. + Builder* disable_statistics(const std::shared_ptr& path) { + return this->disable_statistics(path->ToDotString()); + } + + /// Allow decimals with 1 <= precision <= 18 to be stored as integers. + /// + /// In Parquet, DECIMAL can be stored in any of the following physical types: + /// - int32: for 1 <= precision <= 9. + /// - int64: for 10 <= precision <= 18. + /// - fixed_len_byte_array: precision is limited by the array size. + /// Length n can store <= floor(log_10(2^(8*n - 1) - 1)) base-10 digits. + /// - binary: precision is unlimited. The minimum number of bytes to store + /// the unscaled value is used. + /// + /// By default, this is DISABLED and all decimal types annotate fixed_len_byte_array. + /// + /// When enabled, the C++ writer will use following physical types to store decimals: + /// - int32: for 1 <= precision <= 9. + /// - int64: for 10 <= precision <= 18. + /// - fixed_len_byte_array: for precision > 18. + /// + /// As a consequence, decimal columns stored in integer types are more compact. + Builder* enable_store_decimal_as_integer() { + store_decimal_as_integer_ = true; + return this; + } + + /// Disable decimal logical type with 1 <= precision <= 18 to be stored + /// as integer physical type. + /// + /// Default disabled. + Builder* disable_store_decimal_as_integer() { + store_decimal_as_integer_ = false; + return this; + } + + /// Enable writing page index in general for all columns. Default disabled. + /// + /// Writing statistics to the page index disables the old method of writing + /// statistics to each data page header. + /// The page index makes filtering more efficient than the page header, as + /// it gathers all the statistics for a Parquet file in a single place, + /// avoiding scattered I/O. + /// + /// Please check the link below for more details: + /// https://github.com/apache/parquet-format/blob/master/PageIndex.md + Builder* enable_write_page_index() { + default_column_properties_.set_page_index_enabled(true); + return this; + } + + /// Disable writing page index in general for all columns. Default disabled. + Builder* disable_write_page_index() { + default_column_properties_.set_page_index_enabled(false); + return this; + } + + /// Enable writing page index for column specified by `path`. Default disabled. + Builder* enable_write_page_index(const std::string& path) { + page_index_enabled_[path] = true; + return this; + } + + /// Enable writing page index for column specified by `path`. Default disabled. + Builder* enable_write_page_index(const std::shared_ptr& path) { + return this->enable_write_page_index(path->ToDotString()); + } + + /// Disable writing page index for column specified by `path`. Default disabled. + Builder* disable_write_page_index(const std::string& path) { + page_index_enabled_[path] = false; + return this; + } + + /// Disable writing page index for column specified by `path`. Default disabled. + Builder* disable_write_page_index(const std::shared_ptr& path) { + return this->disable_write_page_index(path->ToDotString()); + } + + /// \brief Build the WriterProperties with the builder parameters. + /// \return The WriterProperties defined by the builder. + std::shared_ptr build() { + std::unordered_map column_properties; + auto get = [&](const std::string& key) -> ColumnProperties& { + auto it = column_properties.find(key); + if (it == column_properties.end()) + return column_properties[key] = default_column_properties_; + else + return it->second; + }; + + for (const auto& item : encodings_) get(item.first).set_encoding(item.second); + for (const auto& item : codecs_) get(item.first).set_compression(item.second); + for (const auto& item : codec_options_) + get(item.first).set_codec_options(item.second); + for (const auto& item : dictionary_enabled_) + get(item.first).set_dictionary_enabled(item.second); + for (const auto& item : statistics_enabled_) + get(item.first).set_statistics_enabled(item.second); + for (const auto& item : page_index_enabled_) + get(item.first).set_page_index_enabled(item.second); + + return std::shared_ptr(new WriterProperties( + pool_, dictionary_pagesize_limit_, write_batch_size_, max_row_group_length_, + pagesize_, version_, created_by_, page_checksum_enabled_, + std::move(file_encryption_properties_), default_column_properties_, + column_properties, data_page_version_, store_decimal_as_integer_, + std::move(sorting_columns_))); + } + + private: + MemoryPool* pool_; + int64_t dictionary_pagesize_limit_; + int64_t write_batch_size_; + int64_t max_row_group_length_; + int64_t pagesize_; + ParquetVersion::type version_; + ParquetDataPageVersion data_page_version_; + std::string created_by_; + bool store_decimal_as_integer_; + bool page_checksum_enabled_; + + std::shared_ptr file_encryption_properties_; + + // If empty, there is no sorting columns. + std::vector sorting_columns_; + + // Settings used for each column unless overridden in any of the maps below + ColumnProperties default_column_properties_; + std::unordered_map encodings_; + std::unordered_map codecs_; + std::unordered_map> codec_options_; + std::unordered_map dictionary_enabled_; + std::unordered_map statistics_enabled_; + std::unordered_map page_index_enabled_; + }; + + inline MemoryPool* memory_pool() const { return pool_; } + + inline int64_t dictionary_pagesize_limit() const { return dictionary_pagesize_limit_; } + + inline int64_t write_batch_size() const { return write_batch_size_; } + + inline int64_t max_row_group_length() const { return max_row_group_length_; } + + inline int64_t data_pagesize() const { return pagesize_; } + + inline ParquetDataPageVersion data_page_version() const { + return parquet_data_page_version_; + } + + inline ParquetVersion::type version() const { return parquet_version_; } + + inline std::string created_by() const { return parquet_created_by_; } + + inline bool store_decimal_as_integer() const { return store_decimal_as_integer_; } + + inline bool page_checksum_enabled() const { return page_checksum_enabled_; } + + inline Encoding::type dictionary_index_encoding() const { + if (parquet_version_ == ParquetVersion::PARQUET_1_0) { + return Encoding::PLAIN_DICTIONARY; + } else { + return Encoding::RLE_DICTIONARY; + } + } + + inline Encoding::type dictionary_page_encoding() const { + if (parquet_version_ == ParquetVersion::PARQUET_1_0) { + return Encoding::PLAIN_DICTIONARY; + } else { + return Encoding::PLAIN; + } + } + + const ColumnProperties& column_properties( + const std::shared_ptr& path) const { + auto it = column_properties_.find(path->ToDotString()); + if (it != column_properties_.end()) return it->second; + return default_column_properties_; + } + + Encoding::type encoding(const std::shared_ptr& path) const { + return column_properties(path).encoding(); + } + + Compression::type compression(const std::shared_ptr& path) const { + return column_properties(path).compression(); + } + + int compression_level(const std::shared_ptr& path) const { + return column_properties(path).compression_level(); + } + + const std::shared_ptr codec_options( + const std::shared_ptr& path) const { + return column_properties(path).codec_options(); + } + + bool dictionary_enabled(const std::shared_ptr& path) const { + return column_properties(path).dictionary_enabled(); + } + + const std::vector& sorting_columns() const { return sorting_columns_; } + + bool statistics_enabled(const std::shared_ptr& path) const { + return column_properties(path).statistics_enabled(); + } + + size_t max_statistics_size(const std::shared_ptr& path) const { + return column_properties(path).max_statistics_size(); + } + + bool page_index_enabled(const std::shared_ptr& path) const { + return column_properties(path).page_index_enabled(); + } + + bool page_index_enabled() const { + if (default_column_properties_.page_index_enabled()) { + return true; + } + for (const auto& item : column_properties_) { + if (item.second.page_index_enabled()) { + return true; + } + } + return false; + } + + inline FileEncryptionProperties* file_encryption_properties() const { + return file_encryption_properties_.get(); + } + + std::shared_ptr column_encryption_properties( + const std::string& path) const { + if (file_encryption_properties_) { + return file_encryption_properties_->column_encryption_properties(path); + } else { + return NULLPTR; + } + } + + // \brief Return the default column properties + const ColumnProperties& default_column_properties() const { + return default_column_properties_; + } + + private: + explicit WriterProperties( + MemoryPool* pool, int64_t dictionary_pagesize_limit, int64_t write_batch_size, + int64_t max_row_group_length, int64_t pagesize, ParquetVersion::type version, + const std::string& created_by, bool page_write_checksum_enabled, + std::shared_ptr file_encryption_properties, + const ColumnProperties& default_column_properties, + const std::unordered_map& column_properties, + ParquetDataPageVersion data_page_version, bool store_short_decimal_as_integer, + std::vector sorting_columns) + : pool_(pool), + dictionary_pagesize_limit_(dictionary_pagesize_limit), + write_batch_size_(write_batch_size), + max_row_group_length_(max_row_group_length), + pagesize_(pagesize), + parquet_data_page_version_(data_page_version), + parquet_version_(version), + parquet_created_by_(created_by), + store_decimal_as_integer_(store_short_decimal_as_integer), + page_checksum_enabled_(page_write_checksum_enabled), + file_encryption_properties_(file_encryption_properties), + sorting_columns_(std::move(sorting_columns)), + default_column_properties_(default_column_properties), + column_properties_(column_properties) {} + + MemoryPool* pool_; + int64_t dictionary_pagesize_limit_; + int64_t write_batch_size_; + int64_t max_row_group_length_; + int64_t pagesize_; + ParquetDataPageVersion parquet_data_page_version_; + ParquetVersion::type parquet_version_; + std::string parquet_created_by_; + bool store_decimal_as_integer_; + bool page_checksum_enabled_; + + std::shared_ptr file_encryption_properties_; + + std::vector sorting_columns_; + + ColumnProperties default_column_properties_; + std::unordered_map column_properties_; +}; + +PARQUET_EXPORT const std::shared_ptr& default_writer_properties(); + +// ---------------------------------------------------------------------- +// Properties specific to Apache Arrow columnar read and write + +static constexpr bool kArrowDefaultUseThreads = false; + +// Default number of rows to read when using ::arrow::RecordBatchReader +static constexpr int64_t kArrowDefaultBatchSize = 64 * 1024; + +/// EXPERIMENTAL: Properties for configuring FileReader behavior. +class PARQUET_EXPORT ArrowReaderProperties { + public: + explicit ArrowReaderProperties(bool use_threads = kArrowDefaultUseThreads) + : use_threads_(use_threads), + read_dict_indices_(), + batch_size_(kArrowDefaultBatchSize), + pre_buffer_(true), + cache_options_(::arrow::io::CacheOptions::LazyDefaults()), + coerce_int96_timestamp_unit_(::arrow::TimeUnit::NANO) {} + + /// \brief Set whether to use the IO thread pool to parse columns in parallel. + /// + /// Default is false. + void set_use_threads(bool use_threads) { use_threads_ = use_threads; } + /// Return whether will use multiple threads. + bool use_threads() const { return use_threads_; } + + /// \brief Set whether to read a particular column as dictionary encoded. + /// + /// If the file metadata contains a serialized Arrow schema, then ... + //// + /// This is only supported for columns with a Parquet physical type of + /// BYTE_ARRAY, such as string or binary types. + void set_read_dictionary(int column_index, bool read_dict) { + if (read_dict) { + read_dict_indices_.insert(column_index); + } else { + read_dict_indices_.erase(column_index); + } + } + /// Return whether the column at the index will be read as dictionary. + bool read_dictionary(int column_index) const { + if (read_dict_indices_.find(column_index) != read_dict_indices_.end()) { + return true; + } else { + return false; + } + } + + /// \brief Set the maximum number of rows to read into a record batch. + /// + /// Will only be fewer rows when there are no more rows in the file. + /// Note that some APIs such as ReadTable may ignore this setting. + void set_batch_size(int64_t batch_size) { batch_size_ = batch_size; } + /// Return the batch size in rows. + /// + /// Note that some APIs such as ReadTable may ignore this setting. + int64_t batch_size() const { return batch_size_; } + + /// Enable read coalescing (default false). + /// + /// When enabled, the Arrow reader will pre-buffer necessary regions + /// of the file in-memory. This is intended to improve performance on + /// high-latency filesystems (e.g. Amazon S3). + void set_pre_buffer(bool pre_buffer) { pre_buffer_ = pre_buffer; } + /// Return whether read coalescing is enabled. + bool pre_buffer() const { return pre_buffer_; } + + /// Set options for read coalescing. This can be used to tune the + /// implementation for characteristics of different filesystems. + void set_cache_options(::arrow::io::CacheOptions options) { cache_options_ = options; } + /// Return the options for read coalescing. + const ::arrow::io::CacheOptions& cache_options() const { return cache_options_; } + + /// Set execution context for read coalescing. + void set_io_context(const ::arrow::io::IOContext& ctx) { io_context_ = ctx; } + /// Return the execution context used for read coalescing. + const ::arrow::io::IOContext& io_context() const { return io_context_; } + + /// Set timestamp unit to use for deprecated INT96-encoded timestamps + /// (default is NANO). + void set_coerce_int96_timestamp_unit(::arrow::TimeUnit::type unit) { + coerce_int96_timestamp_unit_ = unit; + } + + ::arrow::TimeUnit::type coerce_int96_timestamp_unit() const { + return coerce_int96_timestamp_unit_; + } + + private: + bool use_threads_; + std::unordered_set read_dict_indices_; + int64_t batch_size_; + bool pre_buffer_; + ::arrow::io::IOContext io_context_; + ::arrow::io::CacheOptions cache_options_; + ::arrow::TimeUnit::type coerce_int96_timestamp_unit_; +}; + +/// EXPERIMENTAL: Constructs the default ArrowReaderProperties +PARQUET_EXPORT +ArrowReaderProperties default_arrow_reader_properties(); + +class PARQUET_EXPORT ArrowWriterProperties { + public: + enum EngineVersion { + V1, // Supports only nested lists. + V2 // Full support for all nesting combinations + }; + class Builder { + public: + Builder() + : write_timestamps_as_int96_(false), + coerce_timestamps_enabled_(false), + coerce_timestamps_unit_(::arrow::TimeUnit::SECOND), + truncated_timestamps_allowed_(false), + store_schema_(false), + compliant_nested_types_(true), + engine_version_(V2), + use_threads_(kArrowDefaultUseThreads), + executor_(NULLPTR) {} + virtual ~Builder() = default; + + /// \brief Disable writing legacy int96 timestamps (default disabled). + Builder* disable_deprecated_int96_timestamps() { + write_timestamps_as_int96_ = false; + return this; + } + + /// \brief Enable writing legacy int96 timestamps (default disabled). + /// + /// May be turned on to write timestamps compatible with older Parquet writers. + /// This takes precedent over coerce_timestamps. + Builder* enable_deprecated_int96_timestamps() { + write_timestamps_as_int96_ = true; + return this; + } + + /// \brief Coerce all timestamps to the specified time unit. + /// \param unit time unit to truncate to. + /// For Parquet versions 1.0 and 2.4, nanoseconds are casted to microseconds. + Builder* coerce_timestamps(::arrow::TimeUnit::type unit) { + coerce_timestamps_enabled_ = true; + coerce_timestamps_unit_ = unit; + return this; + } + + /// \brief Allow loss of data when truncating timestamps. + /// + /// This is disallowed by default and an error will be returned. + Builder* allow_truncated_timestamps() { + truncated_timestamps_allowed_ = true; + return this; + } + + /// \brief Disallow loss of data when truncating timestamps (default). + Builder* disallow_truncated_timestamps() { + truncated_timestamps_allowed_ = false; + return this; + } + + /// \brief EXPERIMENTAL: Write binary serialized Arrow schema to the file, + /// to enable certain read options (like "read_dictionary") to be set + /// automatically + Builder* store_schema() { + store_schema_ = true; + return this; + } + + /// \brief When enabled, will not preserve Arrow field names for list types. + /// + /// Instead of using the field names Arrow uses for the values array of + /// list types (default "item"), will use "element", as is specified in + /// the Parquet spec. + /// + /// This is enabled by default. + Builder* enable_compliant_nested_types() { + compliant_nested_types_ = true; + return this; + } + + /// Preserve Arrow list field name. + Builder* disable_compliant_nested_types() { + compliant_nested_types_ = false; + return this; + } + + /// Set the version of the Parquet writer engine. + Builder* set_engine_version(EngineVersion version) { + engine_version_ = version; + return this; + } + + /// \brief Set whether to use multiple threads to write columns + /// in parallel in the buffered row group mode. + /// + /// WARNING: If writing multiple files in parallel in the same + /// executor, deadlock may occur if use_threads is true. Please + /// disable it in this case. + /// + /// Default is false. + Builder* set_use_threads(bool use_threads) { + use_threads_ = use_threads; + return this; + } + + /// \brief Set the executor to write columns in parallel in the + /// buffered row group mode. + /// + /// Default is nullptr and the default cpu executor will be used. + Builder* set_executor(::arrow::internal::Executor* executor) { + executor_ = executor; + return this; + } + + /// Create the final properties. + std::shared_ptr build() { + return std::shared_ptr(new ArrowWriterProperties( + write_timestamps_as_int96_, coerce_timestamps_enabled_, coerce_timestamps_unit_, + truncated_timestamps_allowed_, store_schema_, compliant_nested_types_, + engine_version_, use_threads_, executor_)); + } + + private: + bool write_timestamps_as_int96_; + + bool coerce_timestamps_enabled_; + ::arrow::TimeUnit::type coerce_timestamps_unit_; + bool truncated_timestamps_allowed_; + + bool store_schema_; + bool compliant_nested_types_; + EngineVersion engine_version_; + + bool use_threads_; + ::arrow::internal::Executor* executor_; + }; + + bool support_deprecated_int96_timestamps() const { return write_timestamps_as_int96_; } + + bool coerce_timestamps_enabled() const { return coerce_timestamps_enabled_; } + ::arrow::TimeUnit::type coerce_timestamps_unit() const { + return coerce_timestamps_unit_; + } + + bool truncated_timestamps_allowed() const { return truncated_timestamps_allowed_; } + + bool store_schema() const { return store_schema_; } + + /// \brief Enable nested type naming according to the parquet specification. + /// + /// Older versions of arrow wrote out field names for nested lists based on the name + /// of the field. According to the parquet specification they should always be + /// "element". + bool compliant_nested_types() const { return compliant_nested_types_; } + + /// \brief The underlying engine version to use when writing Arrow data. + /// + /// V2 is currently the latest V1 is considered deprecated but left in + /// place in case there are bugs detected in V2. + EngineVersion engine_version() const { return engine_version_; } + + /// \brief Returns whether the writer will use multiple threads + /// to write columns in parallel in the buffered row group mode. + bool use_threads() const { return use_threads_; } + + /// \brief Returns the executor used to write columns in parallel. + ::arrow::internal::Executor* executor() const; + + private: + explicit ArrowWriterProperties(bool write_nanos_as_int96, + bool coerce_timestamps_enabled, + ::arrow::TimeUnit::type coerce_timestamps_unit, + bool truncated_timestamps_allowed, bool store_schema, + bool compliant_nested_types, + EngineVersion engine_version, bool use_threads, + ::arrow::internal::Executor* executor) + : write_timestamps_as_int96_(write_nanos_as_int96), + coerce_timestamps_enabled_(coerce_timestamps_enabled), + coerce_timestamps_unit_(coerce_timestamps_unit), + truncated_timestamps_allowed_(truncated_timestamps_allowed), + store_schema_(store_schema), + compliant_nested_types_(compliant_nested_types), + engine_version_(engine_version), + use_threads_(use_threads), + executor_(executor) {} + + const bool write_timestamps_as_int96_; + const bool coerce_timestamps_enabled_; + const ::arrow::TimeUnit::type coerce_timestamps_unit_; + const bool truncated_timestamps_allowed_; + const bool store_schema_; + const bool compliant_nested_types_; + const EngineVersion engine_version_; + const bool use_threads_; + ::arrow::internal::Executor* executor_; +}; + +/// \brief State object used for writing Arrow data directly to a Parquet +/// column chunk. API possibly not stable +struct ArrowWriteContext { + ArrowWriteContext(MemoryPool* memory_pool, ArrowWriterProperties* properties) + : memory_pool(memory_pool), + properties(properties), + data_buffer(AllocateBuffer(memory_pool)), + def_levels_buffer(AllocateBuffer(memory_pool)) {} + + template + ::arrow::Status GetScratchData(const int64_t num_values, T** out) { + ARROW_RETURN_NOT_OK(this->data_buffer->Resize(num_values * sizeof(T), false)); + *out = reinterpret_cast(this->data_buffer->mutable_data()); + return ::arrow::Status::OK(); + } + + MemoryPool* memory_pool; + const ArrowWriterProperties* properties; + + // Buffer used for storing the data of an array converted to the physical type + // as expected by parquet-cpp. + std::shared_ptr data_buffer; + + // We use the shared ownership of this buffer + std::shared_ptr def_levels_buffer; +}; + +PARQUET_EXPORT +std::shared_ptr default_arrow_writer_properties(); + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/schema.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/schema.h new file mode 100644 index 0000000000000000000000000000000000000000..896ec1e47968d5cb8a4f8df8fd097b035075a4f1 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/schema.h @@ -0,0 +1,492 @@ +// 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 contains the logical parquet-cpp types (independent of Thrift +// structures), schema nodes, and related type tools + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "parquet/platform.h" +#include "parquet/types.h" +#include "parquet/windows_fixup.h" // for OPTIONAL + +namespace parquet { + +class SchemaDescriptor; + +namespace schema { + +class Node; + +// List encodings: using the terminology from Impala to define different styles +// of representing logical lists (a.k.a. ARRAY types) in Parquet schemas. Since +// the converted type named in the Parquet metadata is ConvertedType::LIST we +// use that terminology here. It also helps distinguish from the *_ARRAY +// primitive types. +// +// One-level encoding: Only allows required lists with required cells +// repeated value_type name +// +// Two-level encoding: Enables optional lists with only required cells +// group list +// repeated value_type item +// +// Three-level encoding: Enables optional lists with optional cells +// group bag +// repeated group list +// value_type item +// +// 2- and 1-level encoding are respectively equivalent to 3-level encoding with +// the non-repeated nodes set to required. +// +// The "official" encoding recommended in the Parquet spec is the 3-level, and +// we use that as the default when creating list types. For semantic completeness +// we allow the other two. Since all types of encodings will occur "in the +// wild" we need to be able to interpret the associated definition levels in +// the context of the actual encoding used in the file. +// +// NB: Some Parquet writers may not set ConvertedType::LIST on the repeated +// SchemaElement, which could make things challenging if we are trying to infer +// that a sequence of nodes semantically represents an array according to one +// of these encodings (versus a struct containing an array). We should refuse +// the temptation to guess, as they say. +struct ListEncoding { + enum type { ONE_LEVEL, TWO_LEVEL, THREE_LEVEL }; +}; + +class PARQUET_EXPORT ColumnPath { + public: + ColumnPath() : path_() {} + explicit ColumnPath(const std::vector& path) : path_(path) {} + explicit ColumnPath(std::vector&& path) : path_(std::move(path)) {} + + static std::shared_ptr FromDotString(const std::string& dotstring); + static std::shared_ptr FromNode(const Node& node); + + std::shared_ptr extend(const std::string& node_name) const; + std::string ToDotString() const; + const std::vector& ToDotVector() const; + + protected: + std::vector path_; +}; + +// Base class for logical schema types. A type has a name, repetition level, +// and optionally a logical type (ConvertedType in Parquet metadata parlance) +class PARQUET_EXPORT Node { + public: + enum type { PRIMITIVE, GROUP }; + + virtual ~Node() {} + + bool is_primitive() const { return type_ == Node::PRIMITIVE; } + + bool is_group() const { return type_ == Node::GROUP; } + + bool is_optional() const { return repetition_ == Repetition::OPTIONAL; } + + bool is_repeated() const { return repetition_ == Repetition::REPEATED; } + + bool is_required() const { return repetition_ == Repetition::REQUIRED; } + + virtual bool Equals(const Node* other) const = 0; + + const std::string& name() const { return name_; } + + Node::type node_type() const { return type_; } + + Repetition::type repetition() const { return repetition_; } + + ConvertedType::type converted_type() const { return converted_type_; } + + const std::shared_ptr& logical_type() const { return logical_type_; } + + /// \brief The field_id value for the serialized SchemaElement. If the + /// field_id is less than 0 (e.g. -1), it will not be set when serialized to + /// Thrift. + int field_id() const { return field_id_; } + + const Node* parent() const { return parent_; } + + const std::shared_ptr path() const; + + virtual void ToParquet(void* element) const = 0; + + // Node::Visitor abstract class for walking schemas with the visitor pattern + class Visitor { + public: + virtual ~Visitor() {} + + virtual void Visit(Node* node) = 0; + }; + class ConstVisitor { + public: + virtual ~ConstVisitor() {} + + virtual void Visit(const Node* node) = 0; + }; + + virtual void Visit(Visitor* visitor) = 0; + virtual void VisitConst(ConstVisitor* visitor) const = 0; + + protected: + friend class GroupNode; + + Node(Node::type type, const std::string& name, Repetition::type repetition, + ConvertedType::type converted_type = ConvertedType::NONE, int field_id = -1) + : type_(type), + name_(name), + repetition_(repetition), + converted_type_(converted_type), + field_id_(field_id), + parent_(NULLPTR) {} + + Node(Node::type type, const std::string& name, Repetition::type repetition, + std::shared_ptr logical_type, int field_id = -1) + : type_(type), + name_(name), + repetition_(repetition), + logical_type_(std::move(logical_type)), + field_id_(field_id), + parent_(NULLPTR) {} + + Node::type type_; + std::string name_; + Repetition::type repetition_; + ConvertedType::type converted_type_; + std::shared_ptr logical_type_; + int field_id_; + // Nodes should not be shared, they have a single parent. + const Node* parent_; + + bool EqualsInternal(const Node* other) const; + void SetParent(const Node* p_parent); + + private: + PARQUET_DISALLOW_COPY_AND_ASSIGN(Node); +}; + +// Save our breath all over the place with these typedefs +using NodePtr = std::shared_ptr; +using NodeVector = std::vector; + +// A type that is one of the primitive Parquet storage types. In addition to +// the other type metadata (name, repetition level, logical type), also has the +// physical storage type and their type-specific metadata (byte width, decimal +// parameters) +class PARQUET_EXPORT PrimitiveNode : public Node { + public: + static std::unique_ptr FromParquet(const void* opaque_element); + + // A field_id -1 (or any negative value) will be serialized as null in Thrift + static inline NodePtr Make(const std::string& name, Repetition::type repetition, + Type::type type, + ConvertedType::type converted_type = ConvertedType::NONE, + int length = -1, int precision = -1, int scale = -1, + int field_id = -1) { + return NodePtr(new PrimitiveNode(name, repetition, type, converted_type, length, + precision, scale, field_id)); + } + + // If no logical type, pass LogicalType::None() or nullptr + // A field_id -1 (or any negative value) will be serialized as null in Thrift + static inline NodePtr Make(const std::string& name, Repetition::type repetition, + std::shared_ptr logical_type, + Type::type primitive_type, int primitive_length = -1, + int field_id = -1) { + return NodePtr(new PrimitiveNode(name, repetition, std::move(logical_type), + primitive_type, primitive_length, field_id)); + } + + bool Equals(const Node* other) const override; + + Type::type physical_type() const { return physical_type_; } + + ColumnOrder column_order() const { return column_order_; } + + void SetColumnOrder(ColumnOrder column_order) { column_order_ = column_order; } + + int32_t type_length() const { return type_length_; } + + const DecimalMetadata& decimal_metadata() const { return decimal_metadata_; } + + void ToParquet(void* element) const override; + void Visit(Visitor* visitor) override; + void VisitConst(ConstVisitor* visitor) const override; + + private: + PrimitiveNode(const std::string& name, Repetition::type repetition, Type::type type, + ConvertedType::type converted_type = ConvertedType::NONE, int length = -1, + int precision = -1, int scale = -1, int field_id = -1); + + PrimitiveNode(const std::string& name, Repetition::type repetition, + std::shared_ptr logical_type, + Type::type primitive_type, int primitive_length = -1, int field_id = -1); + + Type::type physical_type_; + int32_t type_length_; + DecimalMetadata decimal_metadata_; + ColumnOrder column_order_; + + // For FIXED_LEN_BYTE_ARRAY + void SetTypeLength(int32_t length) { type_length_ = length; } + + bool EqualsInternal(const PrimitiveNode* other) const; + + FRIEND_TEST(TestPrimitiveNode, Attrs); + FRIEND_TEST(TestPrimitiveNode, Equals); + FRIEND_TEST(TestPrimitiveNode, PhysicalLogicalMapping); + FRIEND_TEST(TestPrimitiveNode, FromParquet); +}; + +class PARQUET_EXPORT GroupNode : public Node { + public: + static std::unique_ptr FromParquet(const void* opaque_element, + NodeVector fields = {}); + + // A field_id -1 (or any negative value) will be serialized as null in Thrift + static inline NodePtr Make(const std::string& name, Repetition::type repetition, + const NodeVector& fields, + ConvertedType::type converted_type = ConvertedType::NONE, + int field_id = -1) { + return NodePtr(new GroupNode(name, repetition, fields, converted_type, field_id)); + } + + // If no logical type, pass nullptr + // A field_id -1 (or any negative value) will be serialized as null in Thrift + static inline NodePtr Make(const std::string& name, Repetition::type repetition, + const NodeVector& fields, + std::shared_ptr logical_type, + int field_id = -1) { + return NodePtr(new GroupNode(name, repetition, fields, logical_type, field_id)); + } + + bool Equals(const Node* other) const override; + + const NodePtr& field(int i) const { return fields_[i]; } + // Get the index of a field by its name, or negative value if not found. + // If several fields share the same name, it is unspecified which one + // is returned. + int FieldIndex(const std::string& name) const; + // Get the index of a field by its node, or negative value if not found. + int FieldIndex(const Node& node) const; + + int field_count() const { return static_cast(fields_.size()); } + + void ToParquet(void* element) const override; + void Visit(Visitor* visitor) override; + void VisitConst(ConstVisitor* visitor) const override; + + /// \brief Return true if this node or any child node has REPEATED repetition + /// type + bool HasRepeatedFields() const; + + private: + GroupNode(const std::string& name, Repetition::type repetition, + const NodeVector& fields, + ConvertedType::type converted_type = ConvertedType::NONE, int field_id = -1); + + GroupNode(const std::string& name, Repetition::type repetition, + const NodeVector& fields, std::shared_ptr logical_type, + int field_id = -1); + + NodeVector fields_; + bool EqualsInternal(const GroupNode* other) const; + + // Mapping between field name to the field index + std::unordered_multimap field_name_to_idx_; + + FRIEND_TEST(TestGroupNode, Attrs); + FRIEND_TEST(TestGroupNode, Equals); + FRIEND_TEST(TestGroupNode, FieldIndex); + FRIEND_TEST(TestGroupNode, FieldIndexDuplicateName); +}; + +// ---------------------------------------------------------------------- +// Convenience primitive type factory functions + +#define PRIMITIVE_FACTORY(FuncName, TYPE) \ + static inline NodePtr FuncName(const std::string& name, \ + Repetition::type repetition = Repetition::OPTIONAL, \ + int field_id = -1) { \ + return PrimitiveNode::Make(name, repetition, Type::TYPE, ConvertedType::NONE, \ + /*length=*/-1, /*precision=*/-1, /*scale=*/-1, field_id); \ + } + +PRIMITIVE_FACTORY(Boolean, BOOLEAN) +PRIMITIVE_FACTORY(Int32, INT32) +PRIMITIVE_FACTORY(Int64, INT64) +PRIMITIVE_FACTORY(Int96, INT96) +PRIMITIVE_FACTORY(Float, FLOAT) +PRIMITIVE_FACTORY(Double, DOUBLE) +PRIMITIVE_FACTORY(ByteArray, BYTE_ARRAY) + +void PARQUET_EXPORT PrintSchema(const schema::Node* schema, std::ostream& stream, + int indent_width = 2); + +} // namespace schema + +// The ColumnDescriptor encapsulates information necessary to interpret +// primitive column data in the context of a particular schema. We have to +// examine the node structure of a column's path to the root in the schema tree +// to be able to reassemble the nested structure from the repetition and +// definition levels. +class PARQUET_EXPORT ColumnDescriptor { + public: + ColumnDescriptor(schema::NodePtr node, int16_t max_definition_level, + int16_t max_repetition_level, + const SchemaDescriptor* schema_descr = NULLPTR); + + bool Equals(const ColumnDescriptor& other) const; + + int16_t max_definition_level() const { return max_definition_level_; } + + int16_t max_repetition_level() const { return max_repetition_level_; } + + Type::type physical_type() const { return primitive_node_->physical_type(); } + + ConvertedType::type converted_type() const { return primitive_node_->converted_type(); } + + const std::shared_ptr& logical_type() const { + return primitive_node_->logical_type(); + } + + ColumnOrder column_order() const { return primitive_node_->column_order(); } + + SortOrder::type sort_order() const { + auto la = logical_type(); + auto pt = physical_type(); + return la ? GetSortOrder(la, pt) : GetSortOrder(converted_type(), pt); + } + + const std::string& name() const { return primitive_node_->name(); } + + const std::shared_ptr path() const; + + const schema::NodePtr& schema_node() const { return node_; } + + std::string ToString() const; + + int type_length() const; + + int type_precision() const; + + int type_scale() const; + + private: + schema::NodePtr node_; + const schema::PrimitiveNode* primitive_node_; + + int16_t max_definition_level_; + int16_t max_repetition_level_; +}; + +// Container for the converted Parquet schema with a computed information from +// the schema analysis needed for file reading +// +// * Column index to Node +// * Max repetition / definition levels for each primitive node +// +// The ColumnDescriptor objects produced by this class can be used to assist in +// the reconstruction of fully materialized data structures from the +// repetition-definition level encoding of nested data +// +// TODO(wesm): this object can be recomputed from a Schema +class PARQUET_EXPORT SchemaDescriptor { + public: + SchemaDescriptor() {} + ~SchemaDescriptor() {} + + // Analyze the schema + void Init(std::unique_ptr schema); + void Init(schema::NodePtr schema); + + const ColumnDescriptor* Column(int i) const; + + // Get the index of a column by its dotstring path, or negative value if not found. + // If several columns share the same dotstring path, it is unspecified which one + // is returned. + int ColumnIndex(const std::string& node_path) const; + // Get the index of a column by its node, or negative value if not found. + int ColumnIndex(const schema::Node& node) const; + + bool Equals(const SchemaDescriptor& other, std::ostream* diff_output = NULLPTR) const; + + // The number of physical columns appearing in the file + int num_columns() const { return static_cast(leaves_.size()); } + + const schema::NodePtr& schema_root() const { return schema_; } + + const schema::GroupNode* group_node() const { return group_node_; } + + // Returns the root (child of the schema root) node of the leaf(column) node + const schema::Node* GetColumnRoot(int i) const; + + const std::string& name() const { return group_node_->name(); } + + std::string ToString() const; + + void updateColumnOrders(const std::vector& column_orders); + + /// \brief Return column index corresponding to a particular + /// PrimitiveNode. Returns -1 if not found + int GetColumnIndex(const schema::PrimitiveNode& node) const; + + /// \brief Return true if any field or their children have REPEATED repetition + /// type + bool HasRepeatedFields() const; + + private: + friend class ColumnDescriptor; + + // Root Node + schema::NodePtr schema_; + // Root Node + const schema::GroupNode* group_node_; + + void BuildTree(const schema::NodePtr& node, int16_t max_def_level, + int16_t max_rep_level, const schema::NodePtr& base); + + // Result of leaf node / tree analysis + std::vector leaves_; + + std::unordered_map node_to_leaf_index_; + + // Mapping between leaf nodes and root group of leaf (first node + // below the schema's root group) + // + // For example, the leaf `a.b.c.d` would have a link back to `a` + // + // -- a <------ + // -- -- b | + // -- -- -- c | + // -- -- -- -- d + std::unordered_map leaf_to_base_; + + // Mapping between ColumnPath DotString to the leaf index + std::unordered_multimap leaf_to_idx_; +}; + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/statistics.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/statistics.h new file mode 100644 index 0000000000000000000000000000000000000000..0d6ea9898f7ba2f9349b88ad7395aed85da6e8e1 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/statistics.h @@ -0,0 +1,382 @@ +// 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 +#include +#include +#include +#include +#include + +#include "parquet/platform.h" +#include "parquet/types.h" + +namespace arrow { + +class Array; +class BinaryArray; + +} // namespace arrow + +namespace parquet { + +class ColumnDescriptor; + +// ---------------------------------------------------------------------- +// Value comparator interfaces + +/// \brief Base class for value comparators. Generally used with +/// TypedComparator +class PARQUET_EXPORT Comparator { + public: + virtual ~Comparator() {} + + /// \brief Create a comparator explicitly from physical type and + /// sort order + /// \param[in] physical_type the physical type for the typed + /// comparator + /// \param[in] sort_order either SortOrder::SIGNED or + /// SortOrder::UNSIGNED + /// \param[in] type_length for FIXED_LEN_BYTE_ARRAY only + static std::shared_ptr Make(Type::type physical_type, + SortOrder::type sort_order, + int type_length = -1); + + /// \brief Create typed comparator inferring default sort order from + /// ColumnDescriptor + /// \param[in] descr the Parquet column schema + static std::shared_ptr Make(const ColumnDescriptor* descr); +}; + +/// \brief Interface for comparison of physical types according to the +/// semantics of a particular logical type. +template +class TypedComparator : public Comparator { + public: + using T = typename DType::c_type; + + /// \brief Scalar comparison of two elements, return true if first + /// is strictly less than the second + virtual bool Compare(const T& a, const T& b) const = 0; + + /// \brief Compute maximum and minimum elements in a batch of + /// elements without any nulls + virtual std::pair GetMinMax(const T* values, int64_t length) const = 0; + + /// \brief Compute minimum and maximum elements from an Arrow array. Only + /// valid for certain Parquet Type / Arrow Type combinations, like BYTE_ARRAY + /// / arrow::BinaryArray + virtual std::pair GetMinMax(const ::arrow::Array& values) const = 0; + + /// \brief Compute maximum and minimum elements in a batch of + /// elements with accompanying bitmap indicating which elements are + /// included (bit set) and excluded (bit not set) + /// + /// \param[in] values the sequence of values + /// \param[in] length the length of the sequence + /// \param[in] valid_bits a bitmap indicating which elements are + /// included (1) or excluded (0) + /// \param[in] valid_bits_offset the bit offset into the bitmap of + /// the first element in the sequence + virtual std::pair GetMinMaxSpaced(const T* values, int64_t length, + const uint8_t* valid_bits, + int64_t valid_bits_offset) const = 0; +}; + +/// \brief Typed version of Comparator::Make +template +std::shared_ptr> MakeComparator(Type::type physical_type, + SortOrder::type sort_order, + int type_length = -1) { + return std::static_pointer_cast>( + Comparator::Make(physical_type, sort_order, type_length)); +} + +/// \brief Typed version of Comparator::Make +template +std::shared_ptr> MakeComparator(const ColumnDescriptor* descr) { + return std::static_pointer_cast>(Comparator::Make(descr)); +} + +// ---------------------------------------------------------------------- + +/// \brief Structure represented encoded statistics to be written to +/// and read from Parquet serialized metadata. +class PARQUET_EXPORT EncodedStatistics { + std::string max_, min_; + bool is_signed_ = false; + + public: + EncodedStatistics() = default; + + const std::string& max() const { return max_; } + const std::string& min() const { return min_; } + + int64_t null_count = 0; + int64_t distinct_count = 0; + + bool has_min = false; + bool has_max = false; + bool has_null_count = false; + bool has_distinct_count = false; + + // When all values in the statistics are null, it is set to true. + // Otherwise, at least one value is not null, or we are not sure at all. + // Page index requires this information to decide whether a data page + // is a null page or not. + bool all_null_value = false; + + // From parquet-mr + // Don't write stats larger than the max size rather than truncating. The + // rationale is that some engines may use the minimum value in the page as + // the true minimum for aggregations and there is no way to mark that a + // value has been truncated and is a lower bound and not in the page. + void ApplyStatSizeLimits(size_t length) { + if (max_.length() > length) { + has_max = false; + max_.clear(); + } + if (min_.length() > length) { + has_min = false; + min_.clear(); + } + } + + bool is_set() const { + return has_min || has_max || has_null_count || has_distinct_count; + } + + bool is_signed() const { return is_signed_; } + + void set_is_signed(bool is_signed) { is_signed_ = is_signed; } + + EncodedStatistics& set_max(std::string value) { + max_ = std::move(value); + has_max = true; + return *this; + } + + EncodedStatistics& set_min(std::string value) { + min_ = std::move(value); + has_min = true; + return *this; + } + + EncodedStatistics& set_null_count(int64_t value) { + null_count = value; + has_null_count = true; + return *this; + } + + EncodedStatistics& set_distinct_count(int64_t value) { + distinct_count = value; + has_distinct_count = true; + return *this; + } +}; + +/// \brief Base type for computing column statistics while writing a file +class PARQUET_EXPORT Statistics { + public: + virtual ~Statistics() {} + + /// \brief Create a new statistics instance given a column schema + /// definition + /// \param[in] descr the column schema + /// \param[in] pool a memory pool to use for any memory allocations, optional + static std::shared_ptr Make( + const ColumnDescriptor* descr, + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()); + + /// \brief Create a new statistics instance given a column schema + /// definition and preexisting state + /// \param[in] descr the column schema + /// \param[in] encoded_min the encoded minimum value + /// \param[in] encoded_max the encoded maximum value + /// \param[in] num_values total number of values + /// \param[in] null_count number of null values + /// \param[in] distinct_count number of distinct values + /// \param[in] has_min_max whether the min/max statistics are set + /// \param[in] has_null_count whether the null_count statistics are set + /// \param[in] has_distinct_count whether the distinct_count statistics are set + /// \param[in] pool a memory pool to use for any memory allocations, optional + static std::shared_ptr Make( + const ColumnDescriptor* descr, const std::string& encoded_min, + const std::string& encoded_max, int64_t num_values, int64_t null_count, + int64_t distinct_count, bool has_min_max, bool has_null_count, + bool has_distinct_count, + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()); + + // Helper function to convert EncodedStatistics to Statistics. + // EncodedStatistics does not contain number of non-null values, and it can be + // passed using the num_values parameter. + static std::shared_ptr Make( + const ColumnDescriptor* descr, const EncodedStatistics* encoded_statistics, + int64_t num_values = -1, + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()); + + /// \brief Return true if the count of null values is set + virtual bool HasNullCount() const = 0; + + /// \brief The number of null values, may not be set + virtual int64_t null_count() const = 0; + + /// \brief Return true if the count of distinct values is set + virtual bool HasDistinctCount() const = 0; + + /// \brief The number of distinct values, may not be set + virtual int64_t distinct_count() const = 0; + + /// \brief The number of non-null values in the column + virtual int64_t num_values() const = 0; + + /// \brief Return true if the min and max statistics are set. Obtain + /// with TypedStatistics::min and max + virtual bool HasMinMax() const = 0; + + /// \brief Reset state of object to initial (no data observed) state + virtual void Reset() = 0; + + /// \brief Plain-encoded minimum value + virtual std::string EncodeMin() const = 0; + + /// \brief Plain-encoded maximum value + virtual std::string EncodeMax() const = 0; + + /// \brief The finalized encoded form of the statistics for transport + virtual EncodedStatistics Encode() = 0; + + /// \brief The physical type of the column schema + virtual Type::type physical_type() const = 0; + + /// \brief The full type descriptor from the column schema + virtual const ColumnDescriptor* descr() const = 0; + + /// \brief Check two Statistics for equality + virtual bool Equals(const Statistics& other) const = 0; + + protected: + static std::shared_ptr Make(Type::type physical_type, const void* min, + const void* max, int64_t num_values, + int64_t null_count, int64_t distinct_count); +}; + +/// \brief A typed implementation of Statistics +template +class TypedStatistics : public Statistics { + public: + using T = typename DType::c_type; + + /// \brief The current minimum value + virtual const T& min() const = 0; + + /// \brief The current maximum value + virtual const T& max() const = 0; + + /// \brief Update state with state of another Statistics object + virtual void Merge(const TypedStatistics& other) = 0; + + /// \brief Batch statistics update + virtual void Update(const T* values, int64_t num_values, int64_t null_count) = 0; + + /// \brief Batch statistics update with supplied validity bitmap + /// \param[in] values pointer to column values + /// \param[in] valid_bits Pointer to bitmap representing if values are non-null. + /// \param[in] valid_bits_offset Offset offset into valid_bits where the slice of + /// data begins. + /// \param[in] num_spaced_values The length of values in values/valid_bits to inspect + /// when calculating statistics. This can be smaller than + /// num_values+null_count as null_count can include nulls + /// from parents while num_spaced_values does not. + /// \param[in] num_values Number of values that are not null. + /// \param[in] null_count Number of values that are null. + virtual void UpdateSpaced(const T* values, const uint8_t* valid_bits, + int64_t valid_bits_offset, int64_t num_spaced_values, + int64_t num_values, int64_t null_count) = 0; + + /// \brief EXPERIMENTAL: Update statistics with an Arrow array without + /// conversion to a primitive Parquet C type. Only implemented for certain + /// Parquet type / Arrow type combinations like BYTE_ARRAY / + /// arrow::BinaryArray + /// + /// If update_counts is true then the null_count and num_values will be updated + /// based on the null_count of values. Set to false if these are updated + /// elsewhere (e.g. when updating a dictionary where the counts are taken from + /// the indices and not the values) + virtual void Update(const ::arrow::Array& values, bool update_counts = true) = 0; + + /// \brief Set min and max values to particular values + virtual void SetMinMax(const T& min, const T& max) = 0; + + /// \brief Increments the null count directly + /// Use Update to extract the null count from data. Use this if you determine + /// the null count through some other means (e.g. dictionary arrays where the + /// null count is determined from the indices) + virtual void IncrementNullCount(int64_t n) = 0; + + /// \brief Increments the number of values directly + /// The same note on IncrementNullCount applies here + virtual void IncrementNumValues(int64_t n) = 0; +}; + +using BoolStatistics = TypedStatistics; +using Int32Statistics = TypedStatistics; +using Int64Statistics = TypedStatistics; +using FloatStatistics = TypedStatistics; +using DoubleStatistics = TypedStatistics; +using ByteArrayStatistics = TypedStatistics; +using FLBAStatistics = TypedStatistics; + +/// \brief Typed version of Statistics::Make +template +std::shared_ptr> MakeStatistics( + const ColumnDescriptor* descr, + ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) { + return std::static_pointer_cast>(Statistics::Make(descr, pool)); +} + +/// \brief Create Statistics initialized to a particular state +/// \param[in] min the minimum value +/// \param[in] max the minimum value +/// \param[in] num_values number of values +/// \param[in] null_count number of null values +/// \param[in] distinct_count number of distinct values +template +std::shared_ptr> MakeStatistics(const typename DType::c_type& min, + const typename DType::c_type& max, + int64_t num_values, + int64_t null_count, + int64_t distinct_count) { + return std::static_pointer_cast>(Statistics::Make( + DType::type_num, &min, &max, num_values, null_count, distinct_count)); +} + +/// \brief Typed version of Statistics::Make +template +std::shared_ptr> MakeStatistics( + const ColumnDescriptor* descr, const std::string& encoded_min, + const std::string& encoded_max, int64_t num_values, int64_t null_count, + int64_t distinct_count, bool has_min_max, bool has_null_count, + bool has_distinct_count, ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) { + return std::static_pointer_cast>(Statistics::Make( + descr, encoded_min, encoded_max, num_values, null_count, distinct_count, + has_min_max, has_null_count, has_distinct_count, pool)); +} + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/stream_reader.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/stream_reader.h new file mode 100644 index 0000000000000000000000000000000000000000..a7dadac92c89277a104e3acc4149a77258177c8c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/stream_reader.h @@ -0,0 +1,303 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include + +#include "parquet/column_reader.h" +#include "parquet/file_reader.h" +#include "parquet/stream_writer.h" + +namespace parquet { + +/// \brief A class for reading Parquet files using an output stream type API. +/// +/// The values given must be of the correct type i.e. the type must +/// match the file schema exactly otherwise a ParquetException will be +/// thrown. +/// +/// The user must explicitly advance to the next row using the +/// EndRow() function or EndRow input manipulator. +/// +/// Required and optional fields are supported: +/// - Required fields are read using operator>>(T) +/// - Optional fields are read with +/// operator>>(std::optional) +/// +/// Note that operator>>(std::optional) can be used to read +/// required fields. +/// +/// Similarly operator>>(T) can be used to read optional fields. +/// However, if the value is not present then a ParquetException will +/// be raised. +/// +/// Currently there is no support for repeated fields. +/// +class PARQUET_EXPORT StreamReader { + public: + template + using optional = ::std::optional; + + // N.B. Default constructed objects are not usable. This + // constructor is provided so that the object may be move + // assigned afterwards. + StreamReader() = default; + + explicit StreamReader(std::unique_ptr reader); + + ~StreamReader() = default; + + bool eof() const { return eof_; } + + int current_column() const { return column_index_; } + + int64_t current_row() const { return current_row_; } + + int num_columns() const; + + int64_t num_rows() const; + + // Moving is possible. + StreamReader(StreamReader&&) = default; + StreamReader& operator=(StreamReader&&) = default; + + // Copying is not allowed. + StreamReader(const StreamReader&) = delete; + StreamReader& operator=(const StreamReader&) = delete; + + StreamReader& operator>>(bool& v); + + StreamReader& operator>>(int8_t& v); + + StreamReader& operator>>(uint8_t& v); + + StreamReader& operator>>(int16_t& v); + + StreamReader& operator>>(uint16_t& v); + + StreamReader& operator>>(int32_t& v); + + StreamReader& operator>>(uint32_t& v); + + StreamReader& operator>>(int64_t& v); + + StreamReader& operator>>(uint64_t& v); + + StreamReader& operator>>(std::chrono::milliseconds& v); + + StreamReader& operator>>(std::chrono::microseconds& v); + + StreamReader& operator>>(float& v); + + StreamReader& operator>>(double& v); + + StreamReader& operator>>(char& v); + + template + StreamReader& operator>>(char (&v)[N]) { + ReadFixedLength(v, N); + return *this; + } + + template + StreamReader& operator>>(std::array& v) { + ReadFixedLength(v.data(), static_cast(N)); + return *this; + } + + // N.B. Cannot allow for reading to a arbitrary char pointer as the + // length cannot be verified. Also it would overshadow the + // char[N] input operator. + // StreamReader& operator>>(char * v); + + StreamReader& operator>>(std::string& v); + + StreamReader& operator>>(::arrow::Decimal128& v); + + // Input operators for optional fields. + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional& v); + + StreamReader& operator>>(optional<::arrow::Decimal128>& v); + + template + StreamReader& operator>>(optional>& v) { + CheckColumn(Type::FIXED_LEN_BYTE_ARRAY, ConvertedType::NONE, N); + FixedLenByteArray flba; + if (ReadOptional(&flba)) { + v = std::array{}; + std::memcpy(v->data(), flba.ptr, N); + } else { + v.reset(); + } + return *this; + } + + /// \brief Terminate current row and advance to next one. + /// \throws ParquetException if all columns in the row were not + /// read or skipped. + void EndRow(); + + /// \brief Skip the data in the next columns. + /// If the number of columns exceeds the columns remaining on the + /// current row then skipping is terminated - it does _not_ continue + /// skipping columns on the next row. + /// Skipping of columns still requires the use 'EndRow' even if all + /// remaining columns were skipped. + /// \return Number of columns actually skipped. + int64_t SkipColumns(int64_t num_columns_to_skip); + + /// \brief Skip the data in the next rows. + /// Skipping of rows is not allowed if reading of data for the + /// current row is not finished. + /// Skipping of rows will be terminated if the end of file is + /// reached. + /// \return Number of rows actually skipped. + int64_t SkipRows(int64_t num_rows_to_skip); + + protected: + [[noreturn]] void ThrowReadFailedException( + const std::shared_ptr& node); + + template + void Read(T* v) { + const auto& node = nodes_[column_index_]; + auto reader = static_cast(column_readers_[column_index_++].get()); + int16_t def_level; + int16_t rep_level; + int64_t values_read; + + reader->ReadBatch(kBatchSizeOne, &def_level, &rep_level, v, &values_read); + + if (values_read != 1) { + ThrowReadFailedException(node); + } + } + + template + void Read(T* v) { + const auto& node = nodes_[column_index_]; + auto reader = static_cast(column_readers_[column_index_++].get()); + int16_t def_level; + int16_t rep_level; + ReadType tmp; + int64_t values_read; + + reader->ReadBatch(kBatchSizeOne, &def_level, &rep_level, &tmp, &values_read); + + if (values_read == 1) { + *v = tmp; + } else { + ThrowReadFailedException(node); + } + } + + template + void ReadOptional(optional* v) { + const auto& node = nodes_[column_index_]; + auto reader = static_cast(column_readers_[column_index_++].get()); + int16_t def_level; + int16_t rep_level; + ReadType tmp; + int64_t values_read; + + reader->ReadBatch(kBatchSizeOne, &def_level, &rep_level, &tmp, &values_read); + + if (values_read == 1) { + *v = T(tmp); + } else if ((values_read == 0) && (def_level == 0)) { + v->reset(); + } else { + ThrowReadFailedException(node); + } + } + + void ReadFixedLength(char* ptr, int len); + + void Read(ByteArray* v); + + void Read(FixedLenByteArray* v); + + bool ReadOptional(ByteArray* v); + + bool ReadOptional(FixedLenByteArray* v); + + void NextRowGroup(); + + void CheckColumn(Type::type physical_type, ConvertedType::type converted_type, + int length = 0); + + void SkipRowsInColumn(ColumnReader* reader, int64_t num_rows_to_skip); + + void SetEof(); + + private: + std::unique_ptr file_reader_; + std::shared_ptr file_metadata_; + std::shared_ptr row_group_reader_; + std::vector> column_readers_; + std::vector> nodes_; + + bool eof_{true}; + int row_group_index_{0}; + int column_index_{0}; + int64_t current_row_{0}; + int64_t row_group_row_offset_{0}; + + static constexpr int64_t kBatchSizeOne = 1; +}; // namespace parquet + +PARQUET_EXPORT +StreamReader& operator>>(StreamReader&, EndRowType); + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/stream_writer.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/stream_writer.h new file mode 100644 index 0000000000000000000000000000000000000000..7637cf7da245c4d61ad7bedf5512b6903189a5b4 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/stream_writer.h @@ -0,0 +1,243 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include + +#include "parquet/column_writer.h" +#include "parquet/file_writer.h" + +namespace parquet { + +/// \brief A class for writing Parquet files using an output stream type API. +/// +/// The values given must be of the correct type i.e. the type must +/// match the file schema exactly otherwise a ParquetException will be +/// thrown. +/// +/// The user must explicitly indicate the end of the row using the +/// EndRow() function or EndRow output manipulator. +/// +/// A maximum row group size can be configured, the default size is +/// 512MB. Alternatively the row group size can be set to zero and the +/// user can create new row groups by calling the EndRowGroup() +/// function or using the EndRowGroup output manipulator. +/// +/// Required and optional fields are supported: +/// - Required fields are written using operator<<(T) +/// - Optional fields are written using +/// operator<<(std::optional). +/// +/// Note that operator<<(T) can be used to write optional fields. +/// +/// Similarly, operator<<(std::optional) can be used to +/// write required fields. However if the optional parameter does not +/// have a value (i.e. it is nullopt) then a ParquetException will be +/// raised. +/// +/// Currently there is no support for repeated fields. +/// +class PARQUET_EXPORT StreamWriter { + public: + template + using optional = ::std::optional; + + // N.B. Default constructed objects are not usable. This + // constructor is provided so that the object may be move + // assigned afterwards. + StreamWriter() = default; + + explicit StreamWriter(std::unique_ptr writer); + + ~StreamWriter() = default; + + static void SetDefaultMaxRowGroupSize(int64_t max_size); + + void SetMaxRowGroupSize(int64_t max_size); + + int current_column() const { return column_index_; } + + int64_t current_row() const { return current_row_; } + + int num_columns() const; + + // Moving is possible. + StreamWriter(StreamWriter&&) = default; + StreamWriter& operator=(StreamWriter&&) = default; + + // Copying is not allowed. + StreamWriter(const StreamWriter&) = delete; + StreamWriter& operator=(const StreamWriter&) = delete; + + /// \brief Output operators for required fields. + /// These can also be used for optional fields when a value must be set. + StreamWriter& operator<<(bool v); + + StreamWriter& operator<<(int8_t v); + + StreamWriter& operator<<(uint8_t v); + + StreamWriter& operator<<(int16_t v); + + StreamWriter& operator<<(uint16_t v); + + StreamWriter& operator<<(int32_t v); + + StreamWriter& operator<<(uint32_t v); + + StreamWriter& operator<<(int64_t v); + + StreamWriter& operator<<(uint64_t v); + + StreamWriter& operator<<(const std::chrono::milliseconds& v); + + StreamWriter& operator<<(const std::chrono::microseconds& v); + + StreamWriter& operator<<(float v); + + StreamWriter& operator<<(double v); + + StreamWriter& operator<<(char v); + + /// \brief Helper class to write fixed length strings. + /// This is useful as the standard string view (such as + /// std::string_view) is for variable length data. + struct PARQUET_EXPORT FixedStringView { + FixedStringView() = default; + + explicit FixedStringView(const char* data_ptr); + + FixedStringView(const char* data_ptr, std::size_t data_len); + + const char* data{NULLPTR}; + std::size_t size{0}; + }; + + /// \brief Output operators for fixed length strings. + template + StreamWriter& operator<<(const char (&v)[N]) { + return WriteFixedLength(v, N); + } + template + StreamWriter& operator<<(const std::array& v) { + return WriteFixedLength(v.data(), N); + } + StreamWriter& operator<<(FixedStringView v); + + /// \brief Output operators for variable length strings. + StreamWriter& operator<<(const char* v); + StreamWriter& operator<<(const std::string& v); + StreamWriter& operator<<(::std::string_view v); + + /// \brief Output operator for optional fields. + template + StreamWriter& operator<<(const optional& v) { + if (v) { + return operator<<(*v); + } + SkipOptionalColumn(); + return *this; + } + + /// \brief Skip the next N columns of optional data. If there are + /// less than N columns remaining then the excess columns are + /// ignored. + /// \throws ParquetException if there is an attempt to skip any + /// required column. + /// \return Number of columns actually skipped. + int64_t SkipColumns(int num_columns_to_skip); + + /// \brief Terminate the current row and advance to next one. + /// \throws ParquetException if all columns in the row were not + /// written or skipped. + void EndRow(); + + /// \brief Terminate the current row group and create new one. + void EndRowGroup(); + + protected: + template + StreamWriter& Write(const T v) { + auto writer = static_cast(row_group_writer_->column(column_index_++)); + + writer->WriteBatch(kBatchSizeOne, &kDefLevelOne, &kRepLevelZero, &v); + + if (max_row_group_size_ > 0) { + row_group_size_ += writer->estimated_buffered_value_bytes(); + } + return *this; + } + + StreamWriter& WriteVariableLength(const char* data_ptr, std::size_t data_len); + + StreamWriter& WriteFixedLength(const char* data_ptr, std::size_t data_len); + + void CheckColumn(Type::type physical_type, ConvertedType::type converted_type, + int length = -1); + + /// \brief Skip the next column which must be optional. + /// \throws ParquetException if the next column does not exist or is + /// not optional. + void SkipOptionalColumn(); + + void WriteNullValue(ColumnWriter* writer); + + private: + using node_ptr_type = std::shared_ptr; + + struct null_deleter { + void operator()(void*) {} + }; + + int32_t column_index_{0}; + int64_t current_row_{0}; + int64_t row_group_size_{0}; + int64_t max_row_group_size_{default_row_group_size_}; + + std::unique_ptr file_writer_; + std::unique_ptr row_group_writer_; + std::vector nodes_; + + static constexpr int16_t kDefLevelZero = 0; + static constexpr int16_t kDefLevelOne = 1; + static constexpr int16_t kRepLevelZero = 0; + static constexpr int64_t kBatchSizeOne = 1; + + static int64_t default_row_group_size_; +}; + +struct PARQUET_EXPORT EndRowType {}; +constexpr EndRowType EndRow = {}; + +struct PARQUET_EXPORT EndRowGroupType {}; +constexpr EndRowGroupType EndRowGroup = {}; + +PARQUET_EXPORT +StreamWriter& operator<<(StreamWriter&, EndRowType); + +PARQUET_EXPORT +StreamWriter& operator<<(StreamWriter&, EndRowGroupType); + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/test_util.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/test_util.h new file mode 100644 index 0000000000000000000000000000000000000000..59728cf53f699f0767bdc1d5d792b266378d55f1 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/test_util.h @@ -0,0 +1,834 @@ +// 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 +#include +#include +#include +#include +#include +#include + +#include + +#include "arrow/io/memory.h" +#include "arrow/testing/util.h" +#include "arrow/util/float16.h" + +#include "parquet/column_page.h" +#include "parquet/column_reader.h" +#include "parquet/column_writer.h" +#include "parquet/encoding.h" +#include "parquet/platform.h" + +// https://github.com/google/googletest/pull/2904 might not be available +// in our version of gtest/gmock +#define EXPECT_THROW_THAT(callable, ex_type, property) \ + EXPECT_THROW( \ + try { (callable)(); } catch (const ex_type& err) { \ + EXPECT_THAT(err, (property)); \ + throw; \ + }, \ + ex_type) + +namespace parquet { + +static constexpr int FLBA_LENGTH = 12; + +inline bool operator==(const FixedLenByteArray& a, const FixedLenByteArray& b) { + return 0 == memcmp(a.ptr, b.ptr, FLBA_LENGTH); +} + +namespace test { + +typedef ::testing::Types + ParquetTypes; + +class ParquetTestException : public parquet::ParquetException { + using ParquetException::ParquetException; +}; + +const char* get_data_dir(); +std::string get_bad_data_dir(); + +std::string get_data_file(const std::string& filename, bool is_good = true); + +template +static inline void assert_vector_equal(const std::vector& left, + const std::vector& right) { + ASSERT_EQ(left.size(), right.size()); + + for (size_t i = 0; i < left.size(); ++i) { + ASSERT_EQ(left[i], right[i]) << i; + } +} + +template +static inline bool vector_equal(const std::vector& left, const std::vector& right) { + if (left.size() != right.size()) { + return false; + } + + for (size_t i = 0; i < left.size(); ++i) { + if (left[i] != right[i]) { + std::cerr << "index " << i << " left was " << left[i] << " right was " << right[i] + << std::endl; + return false; + } + } + + return true; +} + +template +static std::vector slice(const std::vector& values, int start, int end) { + if (end < start) { + return std::vector(0); + } + + std::vector out(end - start); + for (int i = start; i < end; ++i) { + out[i - start] = values[i]; + } + return out; +} + +void random_bytes(int n, uint32_t seed, std::vector* out); +void random_bools(int n, double p, uint32_t seed, bool* out); + +template +inline void random_numbers(int n, uint32_t seed, T min_value, T max_value, T* out) { + std::default_random_engine gen(seed); + std::uniform_int_distribution d(min_value, max_value); + for (int i = 0; i < n; ++i) { + out[i] = d(gen); + } +} + +template <> +inline void random_numbers(int n, uint32_t seed, float min_value, float max_value, + float* out) { + std::default_random_engine gen(seed); + std::uniform_real_distribution d(min_value, max_value); + for (int i = 0; i < n; ++i) { + out[i] = d(gen); + } +} + +template <> +inline void random_numbers(int n, uint32_t seed, double min_value, double max_value, + double* out) { + std::default_random_engine gen(seed); + std::uniform_real_distribution d(min_value, max_value); + for (int i = 0; i < n; ++i) { + out[i] = d(gen); + } +} + +void random_Int96_numbers(int n, uint32_t seed, int32_t min_value, int32_t max_value, + Int96* out); + +void random_float16_numbers(int n, uint32_t seed, ::arrow::util::Float16 min_value, + ::arrow::util::Float16 max_value, uint16_t* out); + +void random_fixed_byte_array(int n, uint32_t seed, uint8_t* buf, int len, FLBA* out); + +void random_byte_array(int n, uint32_t seed, uint8_t* buf, ByteArray* out, int min_size, + int max_size); + +void random_byte_array(int n, uint32_t seed, uint8_t* buf, ByteArray* out, int max_size); + +void prefixed_random_byte_array(int n, uint32_t seed, uint8_t* buf, ByteArray* out, + int min_size, int max_size, double prefixed_probability); + +void prefixed_random_byte_array(int n, uint32_t seed, uint8_t* buf, int len, FLBA* out, + double prefixed_probability); + +template +std::shared_ptr EncodeValues(Encoding::type encoding, bool use_dictionary, + const Sequence& values, int length, + const ColumnDescriptor* descr) { + auto encoder = MakeTypedEncoder(encoding, use_dictionary, descr); + encoder->Put(values, length); + return encoder->FlushValues(); +} + +template +static void InitValues(int num_values, uint32_t seed, std::vector& values, + std::vector& buffer) { + random_numbers(num_values, seed, std::numeric_limits::min(), + std::numeric_limits::max(), values.data()); +} + +template +static void InitValues(int num_values, std::vector& values, + std::vector& buffer) { + InitValues(num_values, 0, values, buffer); +} + +template +static void InitDictValues(int num_values, int num_dicts, std::vector& values, + std::vector& buffer) { + int repeat_factor = num_values / num_dicts; + InitValues(num_dicts, values, buffer); + // add some repeated values + for (int j = 1; j < repeat_factor; ++j) { + for (int i = 0; i < num_dicts; ++i) { + std::memcpy(&values[num_dicts * j + i], &values[i], sizeof(T)); + } + } + // computed only dict_per_page * repeat_factor - 1 values < num_values + // compute remaining + for (int i = num_dicts * repeat_factor; i < num_values; ++i) { + std::memcpy(&values[i], &values[i - num_dicts * repeat_factor], sizeof(T)); + } +} + +template <> +inline void InitDictValues(int num_values, int num_dicts, std::vector& values, + std::vector& buffer) { + // No op for bool +} + +class MockPageReader : public PageReader { + public: + explicit MockPageReader(const std::vector>& pages) + : pages_(pages), page_index_(0) {} + + std::shared_ptr NextPage() override { + if (page_index_ == static_cast(pages_.size())) { + // EOS to consumer + return std::shared_ptr(nullptr); + } + return pages_[page_index_++]; + } + + // No-op + void set_max_page_header_size(uint32_t size) override {} + + private: + std::vector> pages_; + int page_index_; +}; + +// TODO(wesm): this is only used for testing for now. Refactor to form part of +// primary file write path +template +class DataPageBuilder { + public: + using c_type = typename Type::c_type; + + // This class writes data and metadata to the passed inputs + explicit DataPageBuilder(ArrowOutputStream* sink) + : sink_(sink), + num_values_(0), + encoding_(Encoding::PLAIN), + definition_level_encoding_(Encoding::RLE), + repetition_level_encoding_(Encoding::RLE), + have_def_levels_(false), + have_rep_levels_(false), + have_values_(false) {} + + void AppendDefLevels(const std::vector& levels, int16_t max_level, + Encoding::type encoding = Encoding::RLE) { + AppendLevels(levels, max_level, encoding); + + num_values_ = std::max(static_cast(levels.size()), num_values_); + definition_level_encoding_ = encoding; + have_def_levels_ = true; + } + + void AppendRepLevels(const std::vector& levels, int16_t max_level, + Encoding::type encoding = Encoding::RLE) { + AppendLevels(levels, max_level, encoding); + + num_values_ = std::max(static_cast(levels.size()), num_values_); + repetition_level_encoding_ = encoding; + have_rep_levels_ = true; + } + + void AppendValues(const ColumnDescriptor* d, const std::vector& values, + Encoding::type encoding = Encoding::PLAIN) { + std::shared_ptr values_sink = EncodeValues( + encoding, false, values.data(), static_cast(values.size()), d); + PARQUET_THROW_NOT_OK(sink_->Write(values_sink->data(), values_sink->size())); + + num_values_ = std::max(static_cast(values.size()), num_values_); + encoding_ = encoding; + have_values_ = true; + } + + int32_t num_values() const { return num_values_; } + + Encoding::type encoding() const { return encoding_; } + + Encoding::type rep_level_encoding() const { return repetition_level_encoding_; } + + Encoding::type def_level_encoding() const { return definition_level_encoding_; } + + private: + ArrowOutputStream* sink_; + + int32_t num_values_; + Encoding::type encoding_; + Encoding::type definition_level_encoding_; + Encoding::type repetition_level_encoding_; + + bool have_def_levels_; + bool have_rep_levels_; + bool have_values_; + + // Used internally for both repetition and definition levels + void AppendLevels(const std::vector& levels, int16_t max_level, + Encoding::type encoding) { + if (encoding != Encoding::RLE) { + ParquetException::NYI("only rle encoding currently implemented"); + } + + std::vector encode_buffer(LevelEncoder::MaxBufferSize( + Encoding::RLE, max_level, static_cast(levels.size()))); + + // We encode into separate memory from the output stream because the + // RLE-encoded bytes have to be preceded in the stream by their absolute + // size. + LevelEncoder encoder; + encoder.Init(encoding, max_level, static_cast(levels.size()), + encode_buffer.data(), static_cast(encode_buffer.size())); + + encoder.Encode(static_cast(levels.size()), levels.data()); + + int32_t rle_bytes = encoder.len(); + PARQUET_THROW_NOT_OK( + sink_->Write(reinterpret_cast(&rle_bytes), sizeof(int32_t))); + PARQUET_THROW_NOT_OK(sink_->Write(encode_buffer.data(), rle_bytes)); + } +}; + +template <> +inline void DataPageBuilder::AppendValues(const ColumnDescriptor* d, + const std::vector& values, + Encoding::type encoding) { + if (encoding != Encoding::PLAIN) { + ParquetException::NYI("only plain encoding currently implemented"); + } + + auto encoder = MakeTypedEncoder(Encoding::PLAIN, false, d); + dynamic_cast(encoder.get()) + ->Put(values, static_cast(values.size())); + std::shared_ptr buffer = encoder->FlushValues(); + PARQUET_THROW_NOT_OK(sink_->Write(buffer->data(), buffer->size())); + + num_values_ = std::max(static_cast(values.size()), num_values_); + encoding_ = encoding; + have_values_ = true; +} + +template +static std::shared_ptr MakeDataPage( + const ColumnDescriptor* d, const std::vector& values, + int num_vals, Encoding::type encoding, const uint8_t* indices, int indices_size, + const std::vector& def_levels, int16_t max_def_level, + const std::vector& rep_levels, int16_t max_rep_level) { + int num_values = 0; + + auto page_stream = CreateOutputStream(); + test::DataPageBuilder page_builder(page_stream.get()); + + if (!rep_levels.empty()) { + page_builder.AppendRepLevels(rep_levels, max_rep_level); + } + if (!def_levels.empty()) { + page_builder.AppendDefLevels(def_levels, max_def_level); + } + + if (encoding == Encoding::PLAIN) { + page_builder.AppendValues(d, values, encoding); + num_values = std::max(page_builder.num_values(), num_vals); + } else { // DICTIONARY PAGES + PARQUET_THROW_NOT_OK(page_stream->Write(indices, indices_size)); + num_values = std::max(page_builder.num_values(), num_vals); + } + + PARQUET_ASSIGN_OR_THROW(auto buffer, page_stream->Finish()); + + return std::make_shared(buffer, num_values, encoding, + page_builder.def_level_encoding(), + page_builder.rep_level_encoding(), buffer->size()); +} + +template +class DictionaryPageBuilder { + public: + typedef typename TYPE::c_type TC; + static constexpr int TN = TYPE::type_num; + using SpecializedEncoder = typename EncodingTraits::Encoder; + + // This class writes data and metadata to the passed inputs + explicit DictionaryPageBuilder(const ColumnDescriptor* d) + : num_dict_values_(0), have_values_(false) { + auto encoder = MakeTypedEncoder(Encoding::PLAIN, true, d); + dict_traits_ = dynamic_cast*>(encoder.get()); + encoder_.reset(dynamic_cast(encoder.release())); + } + + ~DictionaryPageBuilder() {} + + std::shared_ptr AppendValues(const std::vector& values) { + int num_values = static_cast(values.size()); + // Dictionary encoding + encoder_->Put(values.data(), num_values); + num_dict_values_ = dict_traits_->num_entries(); + have_values_ = true; + return encoder_->FlushValues(); + } + + std::shared_ptr WriteDict() { + std::shared_ptr dict_buffer = + AllocateBuffer(::arrow::default_memory_pool(), dict_traits_->dict_encoded_size()); + dict_traits_->WriteDict(dict_buffer->mutable_data()); + return dict_buffer; + } + + int32_t num_values() const { return num_dict_values_; } + + private: + DictEncoder* dict_traits_; + std::unique_ptr encoder_; + int32_t num_dict_values_; + bool have_values_; +}; + +template <> +inline DictionaryPageBuilder::DictionaryPageBuilder( + const ColumnDescriptor* d) { + ParquetException::NYI("only plain encoding currently implemented for boolean"); +} + +template <> +inline std::shared_ptr DictionaryPageBuilder::WriteDict() { + ParquetException::NYI("only plain encoding currently implemented for boolean"); + return nullptr; +} + +template <> +inline std::shared_ptr DictionaryPageBuilder::AppendValues( + const std::vector& values) { + ParquetException::NYI("only plain encoding currently implemented for boolean"); + return nullptr; +} + +template +inline static std::shared_ptr MakeDictPage( + const ColumnDescriptor* d, const std::vector& values, + const std::vector& values_per_page, Encoding::type encoding, + std::vector>& rle_indices) { + test::DictionaryPageBuilder page_builder(d); + int num_pages = static_cast(values_per_page.size()); + int value_start = 0; + + for (int i = 0; i < num_pages; i++) { + rle_indices.push_back(page_builder.AppendValues( + slice(values, value_start, value_start + values_per_page[i]))); + value_start += values_per_page[i]; + } + + auto buffer = page_builder.WriteDict(); + + return std::make_shared(buffer, page_builder.num_values(), + Encoding::PLAIN); +} + +// Given def/rep levels and values create multiple dict pages +template +inline static void PaginateDict(const ColumnDescriptor* d, + const std::vector& values, + const std::vector& def_levels, + int16_t max_def_level, + const std::vector& rep_levels, + int16_t max_rep_level, int num_levels_per_page, + const std::vector& values_per_page, + std::vector>& pages, + Encoding::type encoding = Encoding::RLE_DICTIONARY) { + int num_pages = static_cast(values_per_page.size()); + std::vector> rle_indices; + std::shared_ptr dict_page = + MakeDictPage(d, values, values_per_page, encoding, rle_indices); + pages.push_back(dict_page); + int def_level_start = 0; + int def_level_end = 0; + int rep_level_start = 0; + int rep_level_end = 0; + for (int i = 0; i < num_pages; i++) { + if (max_def_level > 0) { + def_level_start = i * num_levels_per_page; + def_level_end = (i + 1) * num_levels_per_page; + } + if (max_rep_level > 0) { + rep_level_start = i * num_levels_per_page; + rep_level_end = (i + 1) * num_levels_per_page; + } + std::shared_ptr data_page = MakeDataPage( + d, {}, values_per_page[i], encoding, rle_indices[i]->data(), + static_cast(rle_indices[i]->size()), + slice(def_levels, def_level_start, def_level_end), max_def_level, + slice(rep_levels, rep_level_start, rep_level_end), max_rep_level); + pages.push_back(data_page); + } +} + +// Given def/rep levels and values create multiple plain pages +template +static inline void PaginatePlain(const ColumnDescriptor* d, + const std::vector& values, + const std::vector& def_levels, + int16_t max_def_level, + const std::vector& rep_levels, + int16_t max_rep_level, int num_levels_per_page, + const std::vector& values_per_page, + std::vector>& pages, + Encoding::type encoding = Encoding::PLAIN) { + int num_pages = static_cast(values_per_page.size()); + int def_level_start = 0; + int def_level_end = 0; + int rep_level_start = 0; + int rep_level_end = 0; + int value_start = 0; + for (int i = 0; i < num_pages; i++) { + if (max_def_level > 0) { + def_level_start = i * num_levels_per_page; + def_level_end = (i + 1) * num_levels_per_page; + } + if (max_rep_level > 0) { + rep_level_start = i * num_levels_per_page; + rep_level_end = (i + 1) * num_levels_per_page; + } + std::shared_ptr page = MakeDataPage( + d, slice(values, value_start, value_start + values_per_page[i]), + values_per_page[i], encoding, nullptr, 0, + slice(def_levels, def_level_start, def_level_end), max_def_level, + slice(rep_levels, rep_level_start, rep_level_end), max_rep_level); + pages.push_back(page); + value_start += values_per_page[i]; + } +} + +// Generates pages from randomly generated data +template +static inline int MakePages(const ColumnDescriptor* d, int num_pages, int levels_per_page, + std::vector& def_levels, + std::vector& rep_levels, + std::vector& values, + std::vector& buffer, + std::vector>& pages, + Encoding::type encoding = Encoding::PLAIN, + uint32_t seed = 0) { + int num_levels = levels_per_page * num_pages; + int num_values = 0; + int16_t zero = 0; + int16_t max_def_level = d->max_definition_level(); + int16_t max_rep_level = d->max_repetition_level(); + std::vector values_per_page(num_pages, levels_per_page); + // Create definition levels + if (max_def_level > 0 && num_levels != 0) { + def_levels.resize(num_levels); + random_numbers(num_levels, seed, zero, max_def_level, def_levels.data()); + for (int p = 0; p < num_pages; p++) { + int num_values_per_page = 0; + for (int i = 0; i < levels_per_page; i++) { + if (def_levels[i + p * levels_per_page] == max_def_level) { + num_values_per_page++; + num_values++; + } + } + values_per_page[p] = num_values_per_page; + } + } else { + num_values = num_levels; + } + // Create repetition levels + if (max_rep_level > 0 && num_levels != 0) { + rep_levels.resize(num_levels); + // Using a different seed so that def_levels and rep_levels are different. + random_numbers(num_levels, seed + 789, zero, max_rep_level, rep_levels.data()); + // The generated levels are random. Force the very first page to start with a new + // record. + rep_levels[0] = 0; + // For a null value, rep_levels and def_levels are both 0. + // If we have a repeated value right after this, it needs to start with + // rep_level = 0 to indicate a new record. + for (int i = 0; i < num_levels - 1; ++i) { + if (rep_levels[i] == 0 && def_levels[i] == 0) { + rep_levels[i + 1] = 0; + } + } + } + // Create values + values.resize(num_values); + if (encoding == Encoding::PLAIN) { + InitValues(num_values, values, buffer); + PaginatePlain(d, values, def_levels, max_def_level, rep_levels, max_rep_level, + levels_per_page, values_per_page, pages); + } else if (encoding == Encoding::RLE_DICTIONARY || + encoding == Encoding::PLAIN_DICTIONARY) { + // Calls InitValues and repeats the data + InitDictValues(num_values, levels_per_page, values, buffer); + PaginateDict(d, values, def_levels, max_def_level, rep_levels, max_rep_level, + levels_per_page, values_per_page, pages); + } + + return num_values; +} + +// ---------------------------------------------------------------------- +// Test data generation + +template <> +void inline InitValues(int num_values, uint32_t seed, std::vector& values, + std::vector& buffer) { + values = {}; + if (seed == 0) { + seed = static_cast(::arrow::random_seed()); + } + ::arrow::random_is_valid(num_values, 0.5, &values, static_cast(seed)); +} + +template <> +inline void InitValues(int num_values, uint32_t seed, + std::vector& values, + std::vector& buffer) { + int max_byte_array_len = 12; + int num_bytes = static_cast(max_byte_array_len + sizeof(uint32_t)); + size_t nbytes = num_values * num_bytes; + buffer.resize(nbytes); + random_byte_array(num_values, seed, buffer.data(), values.data(), max_byte_array_len); +} + +inline void InitWideByteArrayValues(int num_values, std::vector& values, + std::vector& buffer, int min_len, + int max_len) { + int num_bytes = static_cast(max_len + sizeof(uint32_t)); + size_t nbytes = num_values * num_bytes; + buffer.resize(nbytes); + random_byte_array(num_values, 0, buffer.data(), values.data(), min_len, max_len); +} + +template <> +inline void InitValues(int num_values, uint32_t seed, std::vector& values, + std::vector& buffer) { + size_t nbytes = num_values * FLBA_LENGTH; + buffer.resize(nbytes); + random_fixed_byte_array(num_values, seed, buffer.data(), FLBA_LENGTH, values.data()); +} + +template <> +inline void InitValues(int num_values, uint32_t seed, std::vector& values, + std::vector& buffer) { + random_Int96_numbers(num_values, seed, std::numeric_limits::min(), + std::numeric_limits::max(), values.data()); +} + +inline std::string TestColumnName(int i) { + std::stringstream col_name; + col_name << "column_" << i; + return col_name.str(); +} + +// This class lives here because of its dependency on the InitValues specializations. +template +class PrimitiveTypedTest : public ::testing::Test { + public: + using c_type = typename TestType::c_type; + + void SetUpSchema(Repetition::type repetition, int num_columns = 1) { + std::vector fields; + + for (int i = 0; i < num_columns; ++i) { + std::string name = TestColumnName(i); + fields.push_back(schema::PrimitiveNode::Make(name, repetition, TestType::type_num, + ConvertedType::NONE, FLBA_LENGTH)); + } + node_ = schema::GroupNode::Make("schema", Repetition::REQUIRED, fields); + schema_.Init(node_); + } + + void GenerateData(int64_t num_values, uint32_t seed = 0); + void SetupValuesOut(int64_t num_values); + void SyncValuesOut(); + + protected: + schema::NodePtr node_; + SchemaDescriptor schema_; + + // Input buffers + std::vector values_; + + std::vector def_levels_; + + std::vector buffer_; + // Pointer to the values, needed as we cannot use std::vector::data() + c_type* values_ptr_; + std::vector bool_buffer_; + + // Output buffers + std::vector values_out_; + std::vector bool_buffer_out_; + c_type* values_out_ptr_; +}; + +template +inline void PrimitiveTypedTest::SyncValuesOut() {} + +template <> +inline void PrimitiveTypedTest::SyncValuesOut() { + std::vector::const_iterator source_iterator = bool_buffer_out_.begin(); + std::vector::iterator destination_iterator = values_out_.begin(); + while (source_iterator != bool_buffer_out_.end()) { + *destination_iterator++ = *source_iterator++ != 0; + } +} + +template +inline void PrimitiveTypedTest::SetupValuesOut(int64_t num_values) { + values_out_.clear(); + values_out_.resize(num_values); + values_out_ptr_ = values_out_.data(); +} + +template <> +inline void PrimitiveTypedTest::SetupValuesOut(int64_t num_values) { + values_out_.clear(); + values_out_.resize(num_values); + + bool_buffer_out_.clear(); + bool_buffer_out_.resize(num_values); + // Write once to all values so we can copy it without getting Valgrind errors + // about uninitialised values. + std::fill(bool_buffer_out_.begin(), bool_buffer_out_.end(), true); + values_out_ptr_ = reinterpret_cast(bool_buffer_out_.data()); +} + +template +inline void PrimitiveTypedTest::GenerateData(int64_t num_values, + uint32_t seed) { + def_levels_.resize(num_values); + values_.resize(num_values); + + InitValues(static_cast(num_values), seed, values_, buffer_); + values_ptr_ = values_.data(); + + std::fill(def_levels_.begin(), def_levels_.end(), 1); +} + +template <> +inline void PrimitiveTypedTest::GenerateData(int64_t num_values, + uint32_t seed) { + def_levels_.resize(num_values); + values_.resize(num_values); + + InitValues(static_cast(num_values), seed, values_, buffer_); + bool_buffer_.resize(num_values); + std::copy(values_.begin(), values_.end(), bool_buffer_.begin()); + values_ptr_ = reinterpret_cast(bool_buffer_.data()); + + std::fill(def_levels_.begin(), def_levels_.end(), 1); +} + +// ---------------------------------------------------------------------- +// test data generation + +template +inline void GenerateData(int num_values, T* out, std::vector* heap) { + // seed the prng so failure is deterministic + random_numbers(num_values, 0, std::numeric_limits::min(), + std::numeric_limits::max(), out); +} + +template +inline void GenerateBoundData(int num_values, T* out, T min, T max, + std::vector* heap) { + // seed the prng so failure is deterministic + random_numbers(num_values, 0, min, max, out); +} + +template <> +inline void GenerateData(int num_values, bool* out, std::vector* heap) { + // seed the prng so failure is deterministic + random_bools(num_values, 0.5, 0, out); +} + +template <> +inline void GenerateData(int num_values, Int96* out, std::vector* heap) { + // seed the prng so failure is deterministic + random_Int96_numbers(num_values, 0, std::numeric_limits::min(), + std::numeric_limits::max(), out); +} + +template <> +inline void GenerateData(int num_values, ByteArray* out, + std::vector* heap) { + int max_byte_array_len = 12; + heap->resize(num_values * max_byte_array_len); + // seed the prng so failure is deterministic + random_byte_array(num_values, 0, heap->data(), out, 2, max_byte_array_len); +} + +// Generate ByteArray or FLBA data where there is a given probability +// for each value to share a common prefix with its predecessor. +// This is useful to exercise prefix-based encodings such as DELTA_BYTE_ARRAY. +template +inline void GeneratePrefixedData(int num_values, T* out, std::vector* heap, + double prefixed_probability); + +template <> +inline void GeneratePrefixedData(int num_values, ByteArray* out, + std::vector* heap, + double prefixed_probability) { + int max_byte_array_len = 12; + heap->resize(num_values * max_byte_array_len); + // seed the prng so failure is deterministic + prefixed_random_byte_array(num_values, /*seed=*/0, heap->data(), out, /*min_size=*/2, + /*max_size=*/max_byte_array_len, prefixed_probability); +} + +static constexpr int kGenerateDataFLBALength = 8; + +template <> +inline void GeneratePrefixedData(int num_values, FLBA* out, + std::vector* heap, + double prefixed_probability) { + heap->resize(num_values * kGenerateDataFLBALength); + // seed the prng so failure is deterministic + prefixed_random_byte_array(num_values, /*seed=*/0, heap->data(), + kGenerateDataFLBALength, out, prefixed_probability); +} + +template <> +inline void GenerateData(int num_values, FLBA* out, std::vector* heap) { + heap->resize(num_values * kGenerateDataFLBALength); + // seed the prng so failure is deterministic + random_fixed_byte_array(num_values, 0, heap->data(), kGenerateDataFLBALength, out); +} + +} // namespace test +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/type_fwd.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/type_fwd.h new file mode 100644 index 0000000000000000000000000000000000000000..da0d0f7bdee96c944410ed19d7f9c28fb48bea50 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/type_fwd.h @@ -0,0 +1,91 @@ +// 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 + +namespace parquet { + +/// \brief Feature selection when writing Parquet files +/// +/// `ParquetVersion::type` governs which data types are allowed and how they +/// are represented. For example, uint32_t data will be written differently +/// depending on this value (as INT64 for PARQUET_1_0, as UINT32 for other +/// versions). +/// +/// However, some features - such as compression algorithms, encryption, +/// or the improved "v2" data page format - must be enabled separately in +/// ArrowWriterProperties. +struct ParquetVersion { + enum type : int { + /// Enable only pre-2.2 Parquet format features when writing + /// + /// This setting is useful for maximum compatibility with legacy readers. + /// Note that logical types may still be emitted, as long they have a + /// corresponding converted type. + PARQUET_1_0, + + /// DEPRECATED: Enable Parquet format 2.6 features + /// + /// This misleadingly named enum value is roughly similar to PARQUET_2_6. + PARQUET_2_0 ARROW_DEPRECATED_ENUM_VALUE("use PARQUET_2_4 or PARQUET_2_6 " + "for fine-grained feature selection"), + + /// Enable Parquet format 2.4 and earlier features when writing + /// + /// This enables UINT32 as well as logical types which don't have + /// a corresponding converted type. + /// + /// Note: Parquet format 2.4.0 was released in October 2017. + PARQUET_2_4, + + /// Enable Parquet format 2.6 and earlier features when writing + /// + /// This enables the NANOS time unit in addition to the PARQUET_2_4 + /// features. + /// + /// Note: Parquet format 2.6.0 was released in September 2018. + PARQUET_2_6, + + /// Enable latest Parquet format 2.x features + /// + /// This value is equal to the greatest 2.x version supported by + /// this library. + PARQUET_2_LATEST = PARQUET_2_6 + }; +}; + +class FileMetaData; +class RowGroupMetaData; + +class ColumnDescriptor; +class SchemaDescriptor; + +class ReaderProperties; +class ArrowReaderProperties; + +class WriterProperties; +class WriterPropertiesBuilder; +class ArrowWriterProperties; +class ArrowWriterPropertiesBuilder; + +namespace arrow { + +class FileWriter; +class FileReader; + +} // namespace arrow +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/types.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/types.h new file mode 100644 index 0000000000000000000000000000000000000000..70a1c4b73ec45ed248755450b2e3e5fd80c2b3f5 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/types.h @@ -0,0 +1,820 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include + +#include "parquet/platform.h" +#include "parquet/type_fwd.h" +#include "parquet/windows_fixup.h" // for OPTIONAL + +namespace arrow::util { + +class Codec; + +} // namespace arrow::util + +namespace parquet { + +// ---------------------------------------------------------------------- +// Metadata enums to match Thrift metadata +// +// The reason we maintain our own enums is to avoid transitive dependency on +// the compiled Thrift headers (and thus thrift/Thrift.h) for users of the +// public API. After building parquet-cpp, you should not need to include +// Thrift headers in your application. This means some boilerplate to convert +// between our types and Parquet's Thrift types. +// +// We can also add special values like NONE to distinguish between metadata +// values being set and not set. As an example consider ConvertedType and +// CompressionCodec + +// Mirrors parquet::Type +struct Type { + enum type { + BOOLEAN = 0, + INT32 = 1, + INT64 = 2, + INT96 = 3, + FLOAT = 4, + DOUBLE = 5, + BYTE_ARRAY = 6, + FIXED_LEN_BYTE_ARRAY = 7, + // Should always be last element. + UNDEFINED = 8 + }; +}; + +// Mirrors parquet::ConvertedType +struct ConvertedType { + enum type { + NONE, // Not a real converted type, but means no converted type is specified + UTF8, + MAP, + MAP_KEY_VALUE, + LIST, + ENUM, + DECIMAL, + DATE, + TIME_MILLIS, + TIME_MICROS, + TIMESTAMP_MILLIS, + TIMESTAMP_MICROS, + UINT_8, + UINT_16, + UINT_32, + UINT_64, + INT_8, + INT_16, + INT_32, + INT_64, + JSON, + BSON, + INTERVAL, + // DEPRECATED INVALID ConvertedType for all-null data. + // Only useful for reading legacy files written out by interim Parquet C++ releases. + // For writing, always emit LogicalType::Null instead. + // See PARQUET-1990. + NA = 25, + UNDEFINED = 26 // Not a real converted type; should always be last element + }; +}; + +// forward declaration +namespace format { + +class LogicalType; + +} + +// Mirrors parquet::FieldRepetitionType +struct Repetition { + enum type { REQUIRED = 0, OPTIONAL = 1, REPEATED = 2, /*Always last*/ UNDEFINED = 3 }; +}; + +// Reference: +// parquet-mr/parquet-hadoop/src/main/java/org/apache/parquet/ +// format/converter/ParquetMetadataConverter.java +// Sort order for page and column statistics. Types are associated with sort +// orders (e.g., UTF8 columns should use UNSIGNED) and column stats are +// aggregated using a sort order. As of parquet-format version 2.3.1, the +// order used to aggregate stats is always SIGNED and is not stored in the +// Parquet file. These stats are discarded for types that need unsigned. +// See PARQUET-686. +struct SortOrder { + enum type { SIGNED, UNSIGNED, UNKNOWN }; +}; + +namespace schema { + +struct DecimalMetadata { + bool isset; + int32_t scale; + int32_t precision; +}; + +} // namespace schema + +/// \brief Implementation of parquet.thrift LogicalType types. +class PARQUET_EXPORT LogicalType { + public: + struct Type { + enum type { + UNDEFINED = 0, // Not a real logical type + STRING = 1, + MAP, + LIST, + ENUM, + DECIMAL, + DATE, + TIME, + TIMESTAMP, + INTERVAL, + INT, + NIL, // Thrift NullType: annotates data that is always null + JSON, + BSON, + UUID, + FLOAT16, + NONE // Not a real logical type; should always be last element + }; + }; + + struct TimeUnit { + enum unit { UNKNOWN = 0, MILLIS = 1, MICROS, NANOS }; + }; + + /// \brief If possible, return a logical type equivalent to the given legacy + /// converted type (and decimal metadata if applicable). + static std::shared_ptr FromConvertedType( + const parquet::ConvertedType::type converted_type, + const parquet::schema::DecimalMetadata converted_decimal_metadata = {false, -1, + -1}); + + /// \brief Return the logical type represented by the Thrift intermediary object. + static std::shared_ptr FromThrift( + const parquet::format::LogicalType& thrift_logical_type); + + /// \brief Return the explicitly requested logical type. + static std::shared_ptr String(); + static std::shared_ptr Map(); + static std::shared_ptr List(); + static std::shared_ptr Enum(); + static std::shared_ptr Decimal(int32_t precision, int32_t scale = 0); + static std::shared_ptr Date(); + static std::shared_ptr Time(bool is_adjusted_to_utc, + LogicalType::TimeUnit::unit time_unit); + + /// \brief Create a Timestamp logical type + /// \param[in] is_adjusted_to_utc set true if the data is UTC-normalized + /// \param[in] time_unit the resolution of the timestamp + /// \param[in] is_from_converted_type if true, the timestamp was generated + /// by translating a legacy converted type of TIMESTAMP_MILLIS or + /// TIMESTAMP_MICROS. Default is false. + /// \param[in] force_set_converted_type if true, always set the + /// legacy ConvertedType TIMESTAMP_MICROS and TIMESTAMP_MILLIS + /// metadata. Default is false + static std::shared_ptr Timestamp( + bool is_adjusted_to_utc, LogicalType::TimeUnit::unit time_unit, + bool is_from_converted_type = false, bool force_set_converted_type = false); + + static std::shared_ptr Interval(); + static std::shared_ptr Int(int bit_width, bool is_signed); + + /// \brief Create a logical type for data that's always null + /// + /// Any physical type can be annotated with this logical type. + static std::shared_ptr Null(); + + static std::shared_ptr JSON(); + static std::shared_ptr BSON(); + static std::shared_ptr UUID(); + static std::shared_ptr Float16(); + + /// \brief Create a placeholder for when no logical type is specified + static std::shared_ptr None(); + + /// \brief Return true if this logical type is consistent with the given underlying + /// physical type. + bool is_applicable(parquet::Type::type primitive_type, + int32_t primitive_length = -1) const; + + /// \brief Return true if this logical type is equivalent to the given legacy converted + /// type (and decimal metadata if applicable). + bool is_compatible(parquet::ConvertedType::type converted_type, + parquet::schema::DecimalMetadata converted_decimal_metadata = { + false, -1, -1}) const; + + /// \brief If possible, return the legacy converted type (and decimal metadata if + /// applicable) equivalent to this logical type. + parquet::ConvertedType::type ToConvertedType( + parquet::schema::DecimalMetadata* out_decimal_metadata) const; + + /// \brief Return a printable representation of this logical type. + std::string ToString() const; + + /// \brief Return a JSON representation of this logical type. + std::string ToJSON() const; + + /// \brief Return a serializable Thrift object for this logical type. + parquet::format::LogicalType ToThrift() const; + + /// \brief Return true if the given logical type is equivalent to this logical type. + bool Equals(const LogicalType& other) const; + + /// \brief Return the enumerated type of this logical type. + LogicalType::Type::type type() const; + + /// \brief Return the appropriate sort order for this logical type. + SortOrder::type sort_order() const; + + // Type checks ... + bool is_string() const; + bool is_map() const; + bool is_list() const; + bool is_enum() const; + bool is_decimal() const; + bool is_date() const; + bool is_time() const; + bool is_timestamp() const; + bool is_interval() const; + bool is_int() const; + bool is_null() const; + bool is_JSON() const; + bool is_BSON() const; + bool is_UUID() const; + bool is_float16() const; + bool is_none() const; + /// \brief Return true if this logical type is of a known type. + bool is_valid() const; + bool is_invalid() const; + /// \brief Return true if this logical type is suitable for a schema GroupNode. + bool is_nested() const; + bool is_nonnested() const; + /// \brief Return true if this logical type is included in the Thrift output for its + /// node. + bool is_serialized() const; + + LogicalType(const LogicalType&) = delete; + LogicalType& operator=(const LogicalType&) = delete; + virtual ~LogicalType() noexcept; + + protected: + LogicalType(); + + class Impl; + std::unique_ptr impl_; +}; + +/// \brief Allowed for physical type BYTE_ARRAY, must be encoded as UTF-8. +class PARQUET_EXPORT StringLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + StringLogicalType() = default; +}; + +/// \brief Allowed for group nodes only. +class PARQUET_EXPORT MapLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + MapLogicalType() = default; +}; + +/// \brief Allowed for group nodes only. +class PARQUET_EXPORT ListLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + ListLogicalType() = default; +}; + +/// \brief Allowed for physical type BYTE_ARRAY, must be encoded as UTF-8. +class PARQUET_EXPORT EnumLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + EnumLogicalType() = default; +}; + +/// \brief Allowed for physical type INT32, INT64, FIXED_LEN_BYTE_ARRAY, or BYTE_ARRAY, +/// depending on the precision. +class PARQUET_EXPORT DecimalLogicalType : public LogicalType { + public: + static std::shared_ptr Make(int32_t precision, int32_t scale = 0); + int32_t precision() const; + int32_t scale() const; + + private: + DecimalLogicalType() = default; +}; + +/// \brief Allowed for physical type INT32. +class PARQUET_EXPORT DateLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + DateLogicalType() = default; +}; + +/// \brief Allowed for physical type INT32 (for MILLIS) or INT64 (for MICROS and NANOS). +class PARQUET_EXPORT TimeLogicalType : public LogicalType { + public: + static std::shared_ptr Make(bool is_adjusted_to_utc, + LogicalType::TimeUnit::unit time_unit); + bool is_adjusted_to_utc() const; + LogicalType::TimeUnit::unit time_unit() const; + + private: + TimeLogicalType() = default; +}; + +/// \brief Allowed for physical type INT64. +class PARQUET_EXPORT TimestampLogicalType : public LogicalType { + public: + static std::shared_ptr Make(bool is_adjusted_to_utc, + LogicalType::TimeUnit::unit time_unit, + bool is_from_converted_type = false, + bool force_set_converted_type = false); + bool is_adjusted_to_utc() const; + LogicalType::TimeUnit::unit time_unit() const; + + /// \brief If true, will not set LogicalType in Thrift metadata + bool is_from_converted_type() const; + + /// \brief If true, will set ConvertedType for micros and millis + /// resolution in legacy ConvertedType Thrift metadata + bool force_set_converted_type() const; + + private: + TimestampLogicalType() = default; +}; + +/// \brief Allowed for physical type FIXED_LEN_BYTE_ARRAY with length 12 +class PARQUET_EXPORT IntervalLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + IntervalLogicalType() = default; +}; + +/// \brief Allowed for physical type INT32 (for bit widths 8, 16, and 32) and INT64 +/// (for bit width 64). +class PARQUET_EXPORT IntLogicalType : public LogicalType { + public: + static std::shared_ptr Make(int bit_width, bool is_signed); + int bit_width() const; + bool is_signed() const; + + private: + IntLogicalType() = default; +}; + +/// \brief Allowed for any physical type. +class PARQUET_EXPORT NullLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + NullLogicalType() = default; +}; + +/// \brief Allowed for physical type BYTE_ARRAY. +class PARQUET_EXPORT JSONLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + JSONLogicalType() = default; +}; + +/// \brief Allowed for physical type BYTE_ARRAY. +class PARQUET_EXPORT BSONLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + BSONLogicalType() = default; +}; + +/// \brief Allowed for physical type FIXED_LEN_BYTE_ARRAY with length 16, +/// must encode raw UUID bytes. +class PARQUET_EXPORT UUIDLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + UUIDLogicalType() = default; +}; + +/// \brief Allowed for physical type FIXED_LEN_BYTE_ARRAY with length 2, +/// must encode raw FLOAT16 bytes. +class PARQUET_EXPORT Float16LogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + Float16LogicalType() = default; +}; + +/// \brief Allowed for any physical type. +class PARQUET_EXPORT NoLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + NoLogicalType() = default; +}; + +// Internal API, for unrecognized logical types +class PARQUET_EXPORT UndefinedLogicalType : public LogicalType { + public: + static std::shared_ptr Make(); + + private: + UndefinedLogicalType() = default; +}; + +// Data encodings. Mirrors parquet::Encoding +struct Encoding { + enum type { + PLAIN = 0, + PLAIN_DICTIONARY = 2, + RLE = 3, + BIT_PACKED = 4, + DELTA_BINARY_PACKED = 5, + DELTA_LENGTH_BYTE_ARRAY = 6, + DELTA_BYTE_ARRAY = 7, + RLE_DICTIONARY = 8, + BYTE_STREAM_SPLIT = 9, + // Should always be last element (except UNKNOWN) + UNDEFINED = 10, + UNKNOWN = 999 + }; +}; + +// Exposed data encodings. It is the encoding of the data read from the file, +// rather than the encoding of the data in the file. E.g., the data encoded as +// RLE_DICTIONARY in the file can be read as dictionary indices by RLE +// decoding, in which case the data read from the file is DICTIONARY encoded. +enum class ExposedEncoding { + NO_ENCODING = 0, // data is not encoded, i.e. already decoded during reading + DICTIONARY = 1 +}; + +/// \brief Return true if Parquet supports indicated compression type +PARQUET_EXPORT +bool IsCodecSupported(Compression::type codec); + +PARQUET_EXPORT +std::unique_ptr GetCodec(Compression::type codec); + +PARQUET_EXPORT +std::unique_ptr GetCodec(Compression::type codec, + const CodecOptions& codec_options); + +PARQUET_EXPORT +std::unique_ptr GetCodec(Compression::type codec, int compression_level); + +struct ParquetCipher { + enum type { AES_GCM_V1 = 0, AES_GCM_CTR_V1 = 1 }; +}; + +struct AadMetadata { + std::string aad_prefix; + std::string aad_file_unique; + bool supply_aad_prefix; +}; + +struct EncryptionAlgorithm { + ParquetCipher::type algorithm; + AadMetadata aad; +}; + +// parquet::PageType +struct PageType { + enum type { + DATA_PAGE, + INDEX_PAGE, + DICTIONARY_PAGE, + DATA_PAGE_V2, + // Should always be last element + UNDEFINED + }; +}; + +bool PageCanUseChecksum(PageType::type pageType); + +class ColumnOrder { + public: + enum type { UNDEFINED, TYPE_DEFINED_ORDER }; + explicit ColumnOrder(ColumnOrder::type column_order) : column_order_(column_order) {} + // Default to Type Defined Order + ColumnOrder() : column_order_(type::TYPE_DEFINED_ORDER) {} + ColumnOrder::type get_order() { return column_order_; } + + static ColumnOrder undefined_; + static ColumnOrder type_defined_; + + private: + ColumnOrder::type column_order_; +}; + +/// \brief BoundaryOrder is a proxy around format::BoundaryOrder. +struct BoundaryOrder { + enum type { + Unordered = 0, + Ascending = 1, + Descending = 2, + // Should always be last element + UNDEFINED = 3 + }; +}; + +/// \brief SortingColumn is a proxy around format::SortingColumn. +struct PARQUET_EXPORT SortingColumn { + // The column index (in this row group) + int32_t column_idx; + + // If true, indicates this column is sorted in descending order. + bool descending; + + // If true, nulls will come before non-null values, otherwise, nulls go at the end. + bool nulls_first; +}; + +inline bool operator==(const SortingColumn& left, const SortingColumn& right) { + return left.nulls_first == right.nulls_first && left.descending == right.descending && + left.column_idx == right.column_idx; +} + +inline bool operator!=(const SortingColumn& left, const SortingColumn& right) { + return !(left == right); +} + +// ---------------------------------------------------------------------- + +struct ByteArray { + ByteArray() : len(0), ptr(NULLPTR) {} + ByteArray(uint32_t len, const uint8_t* ptr) : len(len), ptr(ptr) {} + + ByteArray(::std::string_view view) // NOLINT implicit conversion + : ByteArray(static_cast(view.size()), + reinterpret_cast(view.data())) {} + + explicit operator std::string_view() const { + return std::string_view{reinterpret_cast(ptr), len}; + } + + uint32_t len; + const uint8_t* ptr; +}; + +inline bool operator==(const ByteArray& left, const ByteArray& right) { + return left.len == right.len && + (left.len == 0 || std::memcmp(left.ptr, right.ptr, left.len) == 0); +} + +inline bool operator!=(const ByteArray& left, const ByteArray& right) { + return !(left == right); +} + +struct FixedLenByteArray { + FixedLenByteArray() : ptr(NULLPTR) {} + explicit FixedLenByteArray(const uint8_t* ptr) : ptr(ptr) {} + const uint8_t* ptr; +}; + +using FLBA = FixedLenByteArray; + +// Julian day at unix epoch. +// +// The Julian Day Number (JDN) is the integer assigned to a whole solar day in +// the Julian day count starting from noon Universal time, with Julian day +// number 0 assigned to the day starting at noon on Monday, January 1, 4713 BC, +// proleptic Julian calendar (November 24, 4714 BC, in the proleptic Gregorian +// calendar), +constexpr int64_t kJulianToUnixEpochDays = INT64_C(2440588); +constexpr int64_t kSecondsPerDay = INT64_C(60 * 60 * 24); +constexpr int64_t kMillisecondsPerDay = kSecondsPerDay * INT64_C(1000); +constexpr int64_t kMicrosecondsPerDay = kMillisecondsPerDay * INT64_C(1000); +constexpr int64_t kNanosecondsPerDay = kMicrosecondsPerDay * INT64_C(1000); + +MANUALLY_ALIGNED_STRUCT(1) Int96 { uint32_t value[3]; }; +STRUCT_END(Int96, 12); + +inline bool operator==(const Int96& left, const Int96& right) { + return std::equal(left.value, left.value + 3, right.value); +} + +inline bool operator!=(const Int96& left, const Int96& right) { return !(left == right); } + +static inline std::string ByteArrayToString(const ByteArray& a) { + return std::string(reinterpret_cast(a.ptr), a.len); +} + +static inline void Int96SetNanoSeconds(parquet::Int96& i96, int64_t nanoseconds) { + std::memcpy(&i96.value, &nanoseconds, sizeof(nanoseconds)); +} + +struct DecodedInt96 { + uint64_t days_since_epoch; + uint64_t nanoseconds; +}; + +static inline DecodedInt96 DecodeInt96Timestamp(const parquet::Int96& i96) { + // We do the computations in the unsigned domain to avoid unsigned behaviour + // on overflow. + DecodedInt96 result; + result.days_since_epoch = i96.value[2] - static_cast(kJulianToUnixEpochDays); + result.nanoseconds = 0; + + memcpy(&result.nanoseconds, &i96.value, sizeof(uint64_t)); + return result; +} + +static inline int64_t Int96GetNanoSeconds(const parquet::Int96& i96) { + const auto decoded = DecodeInt96Timestamp(i96); + return static_cast(decoded.days_since_epoch * kNanosecondsPerDay + + decoded.nanoseconds); +} + +static inline int64_t Int96GetMicroSeconds(const parquet::Int96& i96) { + const auto decoded = DecodeInt96Timestamp(i96); + uint64_t microseconds = decoded.nanoseconds / static_cast(1000); + return static_cast(decoded.days_since_epoch * kMicrosecondsPerDay + + microseconds); +} + +static inline int64_t Int96GetMilliSeconds(const parquet::Int96& i96) { + const auto decoded = DecodeInt96Timestamp(i96); + uint64_t milliseconds = decoded.nanoseconds / static_cast(1000000); + return static_cast(decoded.days_since_epoch * kMillisecondsPerDay + + milliseconds); +} + +static inline int64_t Int96GetSeconds(const parquet::Int96& i96) { + const auto decoded = DecodeInt96Timestamp(i96); + uint64_t seconds = decoded.nanoseconds / static_cast(1000000000); + return static_cast(decoded.days_since_epoch * kSecondsPerDay + seconds); +} + +static inline std::string Int96ToString(const Int96& a) { + std::ostringstream result; + std::copy(a.value, a.value + 3, std::ostream_iterator(result, " ")); + return result.str(); +} + +static inline std::string FixedLenByteArrayToString(const FixedLenByteArray& a, int len) { + std::ostringstream result; + std::copy(a.ptr, a.ptr + len, std::ostream_iterator(result, " ")); + return result.str(); +} + +template +struct type_traits {}; + +template <> +struct type_traits { + using value_type = bool; + + static constexpr int value_byte_size = 1; + static constexpr const char* printf_code = "d"; +}; + +template <> +struct type_traits { + using value_type = int32_t; + + static constexpr int value_byte_size = 4; + static constexpr const char* printf_code = "d"; +}; + +template <> +struct type_traits { + using value_type = int64_t; + + static constexpr int value_byte_size = 8; + static constexpr const char* printf_code = + (sizeof(long) == 64) ? "ld" : "lld"; // NOLINT: runtime/int +}; + +template <> +struct type_traits { + using value_type = Int96; + + static constexpr int value_byte_size = 12; + static constexpr const char* printf_code = "s"; +}; + +template <> +struct type_traits { + using value_type = float; + + static constexpr int value_byte_size = 4; + static constexpr const char* printf_code = "f"; +}; + +template <> +struct type_traits { + using value_type = double; + + static constexpr int value_byte_size = 8; + static constexpr const char* printf_code = "lf"; +}; + +template <> +struct type_traits { + using value_type = ByteArray; + + static constexpr int value_byte_size = sizeof(ByteArray); + static constexpr const char* printf_code = "s"; +}; + +template <> +struct type_traits { + using value_type = FixedLenByteArray; + + static constexpr int value_byte_size = sizeof(FixedLenByteArray); + static constexpr const char* printf_code = "s"; +}; + +template +struct PhysicalType { + using c_type = typename type_traits::value_type; + static constexpr Type::type type_num = TYPE; +}; + +using BooleanType = PhysicalType; +using Int32Type = PhysicalType; +using Int64Type = PhysicalType; +using Int96Type = PhysicalType; +using FloatType = PhysicalType; +using DoubleType = PhysicalType; +using ByteArrayType = PhysicalType; +using FLBAType = PhysicalType; + +template +inline std::string format_fwf(int width) { + std::stringstream ss; + ss << "%-" << width << type_traits::printf_code; + return ss.str(); +} + +PARQUET_EXPORT std::string EncodingToString(Encoding::type t); + +PARQUET_EXPORT std::string ConvertedTypeToString(ConvertedType::type t); + +PARQUET_EXPORT std::string TypeToString(Type::type t); + +PARQUET_EXPORT std::string TypeToString(Type::type t, int type_length); + +PARQUET_EXPORT std::string FormatStatValue(Type::type parquet_type, + ::std::string_view val); + +PARQUET_EXPORT int GetTypeByteSize(Type::type t); + +PARQUET_EXPORT SortOrder::type DefaultSortOrder(Type::type primitive); + +PARQUET_EXPORT SortOrder::type GetSortOrder(ConvertedType::type converted, + Type::type primitive); + +PARQUET_EXPORT SortOrder::type GetSortOrder( + const std::shared_ptr& logical_type, Type::type primitive); + +// PLAIN_DICTIONARY is deprecated but used to be used as a dictionary index +// encoding. +constexpr bool IsDictionaryIndexEncoding(Encoding::type e) { + return e == Encoding::RLE_DICTIONARY || e == Encoding::PLAIN_DICTIONARY; +} + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/windows_compatibility.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/windows_compatibility.h new file mode 100644 index 0000000000000000000000000000000000000000..fe84d8c6ce06e12b2b50563997b40337f691ee53 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/windows_compatibility.h @@ -0,0 +1,21 @@ +// 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/windows_compatibility.h" +#include "parquet/windows_fixup.h" diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/windows_fixup.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/windows_fixup.h new file mode 100644 index 0000000000000000000000000000000000000000..ce44480c5732e760841c2c29b0bede4159b6e33e --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/windows_fixup.h @@ -0,0 +1,29 @@ +// 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 header needs to be included multiple times. + +#include "arrow/util/windows_fixup.h" + +#ifdef _WIN32 + +// parquet.thrift's OPTIONAL RepetitionType conflicts with a Windows #define +#ifdef OPTIONAL +#undef OPTIONAL +#endif + +#endif // _WIN32 diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/xxhasher.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/xxhasher.h new file mode 100644 index 0000000000000000000000000000000000000000..a54f287883e006e9cd6d9aeeb2efeb1d6f9db2df --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/xxhasher.h @@ -0,0 +1,50 @@ +// 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 + +#include "parquet/hasher.h" +#include "parquet/platform.h" +#include "parquet/types.h" + +namespace parquet { + +class PARQUET_EXPORT XxHasher : public Hasher { + public: + uint64_t Hash(int32_t value) const override; + uint64_t Hash(int64_t value) const override; + uint64_t Hash(float value) const override; + uint64_t Hash(double value) const override; + uint64_t Hash(const Int96* value) const override; + uint64_t Hash(const ByteArray* value) const override; + uint64_t Hash(const FLBA* val, uint32_t len) const override; + + void Hashes(const int32_t* values, int num_values, uint64_t* hashes) const override; + void Hashes(const int64_t* values, int num_values, uint64_t* hashes) const override; + void Hashes(const float* values, int num_values, uint64_t* hashes) const override; + void Hashes(const double* values, int num_values, uint64_t* hashes) const override; + void Hashes(const Int96* values, int num_values, uint64_t* hashes) const override; + void Hashes(const ByteArray* values, int num_values, uint64_t* hashes) const override; + void Hashes(const FLBA* values, uint32_t type_len, int num_values, + uint64_t* hashes) const override; + + static constexpr int kParquetBloomXxHashSeed = 0; +}; + +} // namespace parquet