diff --git a/.gitattributes b/.gitattributes index 3d66e39f45f80328c02a3323bb1aeb3a8ca7e1ca..89224bad11940f098ba1fec14c03b110689f6c75 100644 --- a/.gitattributes +++ b/.gitattributes @@ -105,3 +105,4 @@ parrot/lib/python3.10/site-packages/google/protobuf/__pycache__/descriptor_pb2.c parrot/lib/libtinfo.so.6 filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/aiohttp/_websocket.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text parrot/lib/libreadline.so.8.2 filter=lfs diff=lfs merge=lfs -text +parrot/lib/libreadline.so.8 filter=lfs diff=lfs merge=lfs -text diff --git a/parrot/lib/libreadline.so.8 b/parrot/lib/libreadline.so.8 new file mode 100644 index 0000000000000000000000000000000000000000..3d1ca162d3248c9d4e76c84be87174ab49829fe1 --- /dev/null +++ b/parrot/lib/libreadline.so.8 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b6a9d66a73115c872272bb479c8f29df1bf7d9b16e5913e083d64b7753ce1c6 +size 411464 diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/benchmark.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/benchmark.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb0bc7f0c4739be0a6f94321bbe207a68825f66a Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/benchmark.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/compute.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/compute.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1932e5dd5b8bfe87bf62d1e5c0834a1b3422c635 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/compute.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/csv.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/csv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e24c5e2d0d4b91dc4903913544a7c27b7d1721e3 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/csv.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/dataset.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e6f967b8ca2bccf91fbd5704a3667bde949c217 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/dataset.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/feather.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/feather.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de2413e91e8928c7c536a831555db93c3f4dc830 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/feather.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/flight.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/flight.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd18f35a06d060e2142cf1350e0ceee25416d1a9 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/flight.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/fs.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/fs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cb7e01ab44e1bad7cd332a4f5ae947e21010e43 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/fs.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/orc.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/orc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bf74393e3d270aeb1299ccc04b7c3c7cc64bf51 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/orc.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/types.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75db28b7eaf2e2508d06a874bc7e7dae4a93e89d Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/__pycache__/types.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/metadata.h b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..9fc30df58e0d38c3e97fcf750c6c98abbf2772aa --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/include/parquet/metadata.h @@ -0,0 +1,568 @@ +// 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/encryption/type_fwd.h" +#include "parquet/platform.h" +#include "parquet/properties.h" +#include "parquet/schema.h" +#include "parquet/types.h" + +namespace parquet { + +class ColumnDescriptor; +class EncodedStatistics; +class FileCryptoMetaData; +class Statistics; +class SchemaDescriptor; + +namespace schema { + +class ColumnPath; + +} // namespace schema + +using KeyValueMetadata = ::arrow::KeyValueMetadata; + +class PARQUET_EXPORT ApplicationVersion { + public: + // Known Versions with Issues + static const ApplicationVersion& PARQUET_251_FIXED_VERSION(); + static const ApplicationVersion& PARQUET_816_FIXED_VERSION(); + static const ApplicationVersion& PARQUET_CPP_FIXED_STATS_VERSION(); + static const ApplicationVersion& PARQUET_MR_FIXED_STATS_VERSION(); + static const ApplicationVersion& PARQUET_CPP_10353_FIXED_VERSION(); + + // Application that wrote the file. e.g. "IMPALA" + std::string application_; + // Build name + std::string build_; + + // Version of the application that wrote the file, expressed as + // (..). Unmatched parts default to 0. + // "1.2.3" => {1, 2, 3} + // "1.2" => {1, 2, 0} + // "1.2-cdh5" => {1, 2, 0} + struct { + int major; + int minor; + int patch; + std::string unknown; + std::string pre_release; + std::string build_info; + } version; + + ApplicationVersion() = default; + explicit ApplicationVersion(const std::string& created_by); + ApplicationVersion(std::string application, int major, int minor, int patch); + + // Returns true if version is strictly less than other_version + bool VersionLt(const ApplicationVersion& other_version) const; + + // Returns true if version is strictly equal with other_version + bool VersionEq(const ApplicationVersion& other_version) const; + + // Checks if the Version has the correct statistics for a given column + bool HasCorrectStatistics(Type::type primitive, EncodedStatistics& statistics, + SortOrder::type sort_order = SortOrder::SIGNED) const; +}; + +class PARQUET_EXPORT ColumnCryptoMetaData { + public: + static std::unique_ptr Make(const uint8_t* metadata); + ~ColumnCryptoMetaData(); + + bool Equals(const ColumnCryptoMetaData& other) const; + + std::shared_ptr path_in_schema() const; + bool encrypted_with_footer_key() const; + const std::string& key_metadata() const; + + private: + explicit ColumnCryptoMetaData(const uint8_t* metadata); + + class ColumnCryptoMetaDataImpl; + std::unique_ptr impl_; +}; + +/// \brief Public struct for Thrift PageEncodingStats in ColumnChunkMetaData +struct PageEncodingStats { + PageType::type page_type; + Encoding::type encoding; + int32_t count; +}; + +/// \brief Public struct for location to page index in ColumnChunkMetaData. +struct IndexLocation { + /// File offset of the given index, in bytes + int64_t offset; + /// Length of the given index, in bytes + int32_t length; +}; + +/// \brief ColumnChunkMetaData is a proxy around format::ColumnChunkMetaData. +class PARQUET_EXPORT ColumnChunkMetaData { + public: + // API convenience to get a MetaData accessor + + ARROW_DEPRECATED("Use the ReaderProperties-taking overload") + static std::unique_ptr Make( + const void* metadata, const ColumnDescriptor* descr, + const ApplicationVersion* writer_version, int16_t row_group_ordinal = -1, + int16_t column_ordinal = -1, + std::shared_ptr file_decryptor = NULLPTR); + + static std::unique_ptr Make( + const void* metadata, const ColumnDescriptor* descr, + const ReaderProperties& properties = default_reader_properties(), + const ApplicationVersion* writer_version = NULLPTR, int16_t row_group_ordinal = -1, + int16_t column_ordinal = -1, + std::shared_ptr file_decryptor = NULLPTR); + + ~ColumnChunkMetaData(); + + bool Equals(const ColumnChunkMetaData& other) const; + + // column chunk + int64_t file_offset() const; + + // parameter is only used when a dataset is spread across multiple files + const std::string& file_path() const; + + // column metadata + bool is_metadata_set() const; + Type::type type() const; + int64_t num_values() const; + std::shared_ptr path_in_schema() const; + bool is_stats_set() const; + std::shared_ptr statistics() const; + + Compression::type compression() const; + // Indicate if the ColumnChunk compression is supported by the current + // compiled parquet library. + bool can_decompress() const; + + const std::vector& encodings() const; + const std::vector& encoding_stats() const; + std::optional bloom_filter_offset() const; + std::optional bloom_filter_length() const; + bool has_dictionary_page() const; + int64_t dictionary_page_offset() const; + int64_t data_page_offset() const; + bool has_index_page() const; + int64_t index_page_offset() const; + int64_t total_compressed_size() const; + int64_t total_uncompressed_size() const; + std::unique_ptr crypto_metadata() const; + std::optional GetColumnIndexLocation() const; + std::optional GetOffsetIndexLocation() const; + + private: + explicit ColumnChunkMetaData( + const void* metadata, const ColumnDescriptor* descr, int16_t row_group_ordinal, + int16_t column_ordinal, const ReaderProperties& properties, + const ApplicationVersion* writer_version = NULLPTR, + std::shared_ptr file_decryptor = NULLPTR); + // PIMPL Idiom + class ColumnChunkMetaDataImpl; + std::unique_ptr impl_; +}; + +/// \brief RowGroupMetaData is a proxy around format::RowGroupMetaData. +class PARQUET_EXPORT RowGroupMetaData { + public: + ARROW_DEPRECATED("Use the ReaderProperties-taking overload") + static std::unique_ptr Make( + const void* metadata, const SchemaDescriptor* schema, + const ApplicationVersion* writer_version, + std::shared_ptr file_decryptor = NULLPTR); + + /// \brief Create a RowGroupMetaData from a serialized thrift message. + static std::unique_ptr Make( + const void* metadata, const SchemaDescriptor* schema, + const ReaderProperties& properties = default_reader_properties(), + const ApplicationVersion* writer_version = NULLPTR, + std::shared_ptr file_decryptor = NULLPTR); + + ~RowGroupMetaData(); + + bool Equals(const RowGroupMetaData& other) const; + + /// \brief The number of columns in this row group. The order must match the + /// parent's column ordering. + int num_columns() const; + + /// \brief Return the ColumnChunkMetaData of the corresponding column ordinal. + /// + /// WARNING, the returned object references memory location in it's parent + /// (RowGroupMetaData) object. Hence, the parent must outlive the returned + /// object. + /// + /// \param[in] index of the ColumnChunkMetaData to retrieve. + /// + /// \throws ParquetException if the index is out of bound. + std::unique_ptr ColumnChunk(int index) const; + + /// \brief Number of rows in this row group. + int64_t num_rows() const; + + /// \brief Total byte size of all the uncompressed column data in this row group. + int64_t total_byte_size() const; + + /// \brief Total byte size of all the compressed (and potentially encrypted) + /// column data in this row group. + /// + /// This information is optional and may be 0 if omitted. + int64_t total_compressed_size() const; + + /// \brief Byte offset from beginning of file to first page (data or + /// dictionary) in this row group + /// + /// The file_offset field that this method exposes is optional. This method + /// will return 0 if that field is not set to a meaningful value. + int64_t file_offset() const; + // Return const-pointer to make it clear that this object is not to be copied + const SchemaDescriptor* schema() const; + // Indicate if all of the RowGroup's ColumnChunks can be decompressed. + bool can_decompress() const; + // Sorting columns of the row group if any. + std::vector sorting_columns() const; + + private: + explicit RowGroupMetaData( + const void* metadata, const SchemaDescriptor* schema, + const ReaderProperties& properties, + const ApplicationVersion* writer_version = NULLPTR, + std::shared_ptr file_decryptor = NULLPTR); + // PIMPL Idiom + class RowGroupMetaDataImpl; + std::unique_ptr impl_; +}; + +class FileMetaDataBuilder; + +/// \brief FileMetaData is a proxy around format::FileMetaData. +class PARQUET_EXPORT FileMetaData { + public: + ARROW_DEPRECATED("Use the ReaderProperties-taking overload") + static std::shared_ptr Make( + const void* serialized_metadata, uint32_t* inout_metadata_len, + std::shared_ptr file_decryptor); + + /// \brief Create a FileMetaData from a serialized thrift message. + static std::shared_ptr Make( + const void* serialized_metadata, uint32_t* inout_metadata_len, + const ReaderProperties& properties = default_reader_properties(), + std::shared_ptr file_decryptor = NULLPTR); + + ~FileMetaData(); + + bool Equals(const FileMetaData& other) const; + + /// \brief The number of parquet "leaf" columns. + /// + /// Parquet thrift definition requires that nested schema elements are + /// flattened. This method returns the number of columns in the flattened + /// version. + /// For instance, if the schema looks like this : + /// 0 foo.bar + /// foo.bar.baz 0 + /// foo.bar.baz2 1 + /// foo.qux 2 + /// 1 foo2 3 + /// 2 foo3 4 + /// This method will return 5, because there are 5 "leaf" fields (so 5 + /// flattened fields) + int num_columns() const; + + /// \brief The number of flattened schema elements. + /// + /// Parquet thrift definition requires that nested schema elements are + /// flattened. This method returns the total number of elements in the + /// flattened list. + int num_schema_elements() const; + + /// \brief The total number of rows. + /// + /// If the FileMetaData was obtained by calling `SubSet()`, this is the total + /// number of rows in the selected row groups. + int64_t num_rows() const; + + /// \brief The number of row groups in the file. + /// + /// If the FileMetaData was obtained by calling `SubSet()`, this is the number + /// of selected row groups. + int num_row_groups() const; + + /// \brief Return the RowGroupMetaData of the corresponding row group ordinal. + /// + /// WARNING, the returned object references memory location in it's parent + /// (FileMetaData) object. Hence, the parent must outlive the returned object. + /// + /// \param[in] index of the RowGroup to retrieve. + /// + /// \throws ParquetException if the index is out of bound. + std::unique_ptr RowGroup(int index) const; + + /// \brief Return the "version" of the file + /// + /// WARNING: The value returned by this method is unreliable as 1) the Parquet + /// file metadata stores the version as a single integer and 2) some producers + /// are known to always write a hardcoded value. Therefore, you cannot use + /// this value to know which features are used in the file. + ParquetVersion::type version() const; + + /// \brief Return the application's user-agent string of the writer. + const std::string& created_by() const; + + /// \brief Return the application's version of the writer. + const ApplicationVersion& writer_version() const; + + /// \brief Size of the original thrift encoded metadata footer. + uint32_t size() const; + + /// \brief Indicate if all of the FileMetaData's RowGroups can be decompressed. + /// + /// This will return false if any of the RowGroup's page is compressed with a + /// compression format which is not compiled in the current parquet library. + bool can_decompress() const; + + bool is_encryption_algorithm_set() const; + EncryptionAlgorithm encryption_algorithm() const; + const std::string& footer_signing_key_metadata() const; + + /// \brief Verify signature of FileMetaData when file is encrypted but footer + /// is not encrypted (plaintext footer). + bool VerifySignature(const void* signature); + + void WriteTo(::arrow::io::OutputStream* dst, + const std::shared_ptr& encryptor = NULLPTR) const; + + /// \brief Return Thrift-serialized representation of the metadata as a + /// string + std::string SerializeToString() const; + + // Return const-pointer to make it clear that this object is not to be copied + const SchemaDescriptor* schema() const; + + const std::shared_ptr& key_value_metadata() const; + + /// \brief Set a path to all ColumnChunk for all RowGroups. + /// + /// Commonly used by systems (Dask, Spark) who generates an metadata-only + /// parquet file. The path is usually relative to said index file. + /// + /// \param[in] path to set. + void set_file_path(const std::string& path); + + /// \brief Merge row groups from another metadata file into this one. + /// + /// The schema of the input FileMetaData must be equal to the + /// schema of this object. + /// + /// This is used by systems who creates an aggregate metadata-only file by + /// concatenating the row groups of multiple files. This newly created + /// metadata file acts as an index of all available row groups. + /// + /// \param[in] other FileMetaData to merge the row groups from. + /// + /// \throws ParquetException if schemas are not equal. + void AppendRowGroups(const FileMetaData& other); + + /// \brief Return a FileMetaData containing a subset of the row groups in this + /// FileMetaData. + std::shared_ptr Subset(const std::vector& row_groups) const; + + private: + friend FileMetaDataBuilder; + friend class SerializedFile; + friend class SerializedRowGroup; + + explicit FileMetaData(const void* serialized_metadata, uint32_t* metadata_len, + const ReaderProperties& properties, + std::shared_ptr file_decryptor = NULLPTR); + + void set_file_decryptor(std::shared_ptr file_decryptor); + const std::shared_ptr& file_decryptor() const; + + // PIMPL Idiom + FileMetaData(); + class FileMetaDataImpl; + std::unique_ptr impl_; +}; + +class PARQUET_EXPORT FileCryptoMetaData { + public: + // API convenience to get a MetaData accessor + static std::shared_ptr Make( + const uint8_t* serialized_metadata, uint32_t* metadata_len, + const ReaderProperties& properties = default_reader_properties()); + ~FileCryptoMetaData(); + + EncryptionAlgorithm encryption_algorithm() const; + const std::string& key_metadata() const; + + void WriteTo(::arrow::io::OutputStream* dst) const; + + private: + friend FileMetaDataBuilder; + FileCryptoMetaData(const uint8_t* serialized_metadata, uint32_t* metadata_len, + const ReaderProperties& properties); + + // PIMPL Idiom + FileCryptoMetaData(); + class FileCryptoMetaDataImpl; + std::unique_ptr impl_; +}; + +// Builder API +class PARQUET_EXPORT ColumnChunkMetaDataBuilder { + public: + // API convenience to get a MetaData reader + static std::unique_ptr Make( + std::shared_ptr props, const ColumnDescriptor* column); + + static std::unique_ptr Make( + std::shared_ptr props, const ColumnDescriptor* column, + void* contents); + + ~ColumnChunkMetaDataBuilder(); + + // column chunk + // Used when a dataset is spread across multiple files + void set_file_path(const std::string& path); + // column metadata + void SetStatistics(const EncodedStatistics& stats); + // get the column descriptor + const ColumnDescriptor* descr() const; + + int64_t total_compressed_size() const; + // commit the metadata + + void Finish(int64_t num_values, int64_t dictionary_page_offset, + int64_t index_page_offset, int64_t data_page_offset, + int64_t compressed_size, int64_t uncompressed_size, bool has_dictionary, + bool dictionary_fallback, + const std::map& dict_encoding_stats_, + const std::map& data_encoding_stats_, + const std::shared_ptr& encryptor = NULLPTR); + + // The metadata contents, suitable for passing to ColumnChunkMetaData::Make + const void* contents() const; + + // For writing metadata at end of column chunk + void WriteTo(::arrow::io::OutputStream* sink); + + private: + explicit ColumnChunkMetaDataBuilder(std::shared_ptr props, + const ColumnDescriptor* column); + explicit ColumnChunkMetaDataBuilder(std::shared_ptr props, + const ColumnDescriptor* column, void* contents); + // PIMPL Idiom + class ColumnChunkMetaDataBuilderImpl; + std::unique_ptr impl_; +}; + +class PARQUET_EXPORT RowGroupMetaDataBuilder { + public: + // API convenience to get a MetaData reader + static std::unique_ptr Make( + std::shared_ptr props, const SchemaDescriptor* schema_, + void* contents); + + ~RowGroupMetaDataBuilder(); + + ColumnChunkMetaDataBuilder* NextColumnChunk(); + int num_columns(); + int64_t num_rows(); + int current_column() const; + + void set_num_rows(int64_t num_rows); + + // commit the metadata + void Finish(int64_t total_bytes_written, int16_t row_group_ordinal = -1); + + private: + explicit RowGroupMetaDataBuilder(std::shared_ptr props, + const SchemaDescriptor* schema_, void* contents); + // PIMPL Idiom + class RowGroupMetaDataBuilderImpl; + std::unique_ptr impl_; +}; + +/// \brief Public struct for location to all page indexes in a parquet file. +struct PageIndexLocation { + /// Alias type of page index location of a row group. The index location + /// is located by column ordinal. If the column does not have the page index, + /// its value is set to std::nullopt. + using RowGroupIndexLocation = std::vector>; + /// Alias type of page index location of a parquet file. The index location + /// is located by the row group ordinal. + using FileIndexLocation = std::map; + /// Row group column index locations which uses row group ordinal as the key. + FileIndexLocation column_index_location; + /// Row group offset index locations which uses row group ordinal as the key. + FileIndexLocation offset_index_location; +}; + +class PARQUET_EXPORT FileMetaDataBuilder { + public: + ARROW_DEPRECATED("Deprecated in 12.0.0. Use overload without KeyValueMetadata instead.") + static std::unique_ptr Make( + const SchemaDescriptor* schema, std::shared_ptr props, + std::shared_ptr key_value_metadata); + + // API convenience to get a MetaData builder + static std::unique_ptr Make( + const SchemaDescriptor* schema, std::shared_ptr props); + + ~FileMetaDataBuilder(); + + // The prior RowGroupMetaDataBuilder (if any) is destroyed + RowGroupMetaDataBuilder* AppendRowGroup(); + + // Update location to all page indexes in the parquet file + void SetPageIndexLocation(const PageIndexLocation& location); + + // Complete the Thrift structure + std::unique_ptr Finish( + const std::shared_ptr& key_value_metadata = NULLPTR); + + // crypto metadata + std::unique_ptr GetCryptoMetaData(); + + private: + explicit FileMetaDataBuilder( + const SchemaDescriptor* schema, std::shared_ptr props, + std::shared_ptr key_value_metadata = NULLPTR); + // PIMPL Idiom + class FileMetaDataBuilderImpl; + std::unique_ptr impl_; +}; + +PARQUET_EXPORT std::string ParquetVersionToString(ParquetVersion::type ver); + +} // namespace parquet diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69af7da526781e456180923a99b6c3a64307a465 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/arrow_16597.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/arrow_16597.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c706bcfd1f72e85a39a48ce822d9f2c6ee2a85f Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/arrow_16597.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/arrow_7980.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/arrow_7980.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a20198e17a7ed9b8a784ee12dc4dc6e05bbcbdc Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/arrow_7980.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/conftest.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/conftest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97c7d8e6bb8b7054ec27b9f466962e2c23a3ed83 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/conftest.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/pandas_examples.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/pandas_examples.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33653f819c73fa81b4ab841400d3413372f145b4 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/pandas_examples.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/pandas_threaded_import.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/pandas_threaded_import.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..796788b0447e4307e1410a8b5a10d5ab064eaf61 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/pandas_threaded_import.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/read_record_batch.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/read_record_batch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67df12262a43f5be7fa0bb6c7dc3a20fa7eb9854 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/read_record_batch.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/strategies.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/strategies.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06062a0bd16e8218a0642459fd80113027bcae46 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/strategies.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_acero.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_acero.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..300dc98302d841c782917de8b053f002d0af106b Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_acero.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_adhoc_memory_leak.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_adhoc_memory_leak.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb0f54887a271e82786366fb43d9f3eb2dc8fe38 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_adhoc_memory_leak.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_builder.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c7a221b19fcf71dce1d372480cce5c4607ef12f Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_builder.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cffi.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cffi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48a417c83330b22dae77518d029599ee542c2eed Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cffi.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_convert_builtin.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_convert_builtin.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a06811a25489dc6b52a139a91e500fd97e0f08be Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_convert_builtin.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cpp_internals.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cpp_internals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d51073a682e1f948b278ece6e4512dabd20f746a Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cpp_internals.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_csv.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_csv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b0cc253bc3a7abeb680b107926b4bd2f7852b19 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_csv.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cuda.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cuda.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93470df5b342c75b156a03ee8f30709b6edb51a3 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cuda.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cuda_numba_interop.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cuda_numba_interop.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2cda1f1998af291eae66902199618982bbaff8c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_cuda_numba_interop.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_dataset_encryption.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_dataset_encryption.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f46b7518260657e582aadbf8434eedd75206115d Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_dataset_encryption.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_deprecations.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_deprecations.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdd559bb8623bca829f570fdd77cab75eaf53e7b Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_deprecations.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_device.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_device.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..198be9490a135d3486e892e9c3363aa6ec9f386e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_device.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_dlpack.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_dlpack.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a75736669e6510a517b6c9acac977b68da66ea70 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_dlpack.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_exec_plan.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_exec_plan.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..948bf2f7cd3abb979630bafd83dbe6711d0f3760 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_exec_plan.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_extension_type.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_extension_type.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84ea3acf62c27e00b9cc61e16b0ac4ab3d78da47 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_extension_type.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_feather.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_feather.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32742a7bf1b5c498ce28a300d07fb75ba1b1e0fb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_feather.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_flight.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_flight.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29e7af5f0c8cab7a82ace4e317147f390148034b Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_flight.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_flight_async.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_flight_async.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a79f58a3383d991e4345c9517da195b3d16e569 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_flight_async.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_fs.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_fs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86f2cc33d638ddff91792d97fd4c2a229c5d0c8e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_fs.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_gandiva.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_gandiva.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30a53f5cbc4cc9761c948ee9b13ebdfa2624a5cc Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_gandiva.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_gdb.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_gdb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebc394b89c300488677b3606bff73793c55cc19a Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_gdb.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_io.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_io.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3f37f67b12d0c7f79e6052a452415c149629230 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_io.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_ipc.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_ipc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e264da62e1d5c6e822ff8e0705867cae851bf97 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_ipc.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_json.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_json.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e73a2ac68dbcbdbecc9df7b53f643c43f05eddda Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_json.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_jvm.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_jvm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f86e187117c482d24fe854ed25f69ebf1f607fb7 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_jvm.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_memory.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_memory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6d8440690a4a8069f8a7ae5d7e7f92aeafcf70a Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_memory.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_misc.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_misc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27cd18048acde0311886e693cff0f5962bbd734c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_misc.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_orc.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_orc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d97c64a6a4c708d98ad4d6da3799d02973a630c5 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_orc.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_scalars.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_scalars.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3f7393aa3d48ff5c3db038472271425267b1b70 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_scalars.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_schema.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_schema.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7d3e959c2201aba7eb2eedcd4047d4caabbeadb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_schema.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_sparse_tensor.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_sparse_tensor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..217cea7cff6b9ae5ae4dcfe6cbfda33254c702d8 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_sparse_tensor.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_strategies.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_strategies.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d66e276c7331d1df2af69d06588ec089ae95fb3 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_strategies.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_substrait.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_substrait.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aad27d1d7f58f6709d87890b4210766d58275f29 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_substrait.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_table.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_table.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cad45d80b1fff4a947edaff5f7ac63cf9c277953 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_table.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_tensor.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_tensor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb388ffc5926ed641488579f6d61d50241ffc5c6 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_tensor.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_types.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cabd2e9dd2a1a591ac8605d99bbd95d27c4a30ac Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_types.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_udf.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_udf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5496785c1982a5dd6980e9be20307dea2531b17d Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_udf.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_util.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa196c5fe5182275202bdbfa0ede7dde8b1f2301 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/test_util.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/util.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6bc4e4ff9ccb3a3cec3f69ccdd10af549991e7e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/__pycache__/util.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/data/feather/v0.17.0.version.2-compression.lz4.feather b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/feather/v0.17.0.version.2-compression.lz4.feather new file mode 100644 index 0000000000000000000000000000000000000000..562b0b2c53d8684fcb2b0417bad36877d92af53e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/feather/v0.17.0.version.2-compression.lz4.feather differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/README.md b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c548225155331252e380ef9317af43f105c509d0 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/README.md @@ -0,0 +1,22 @@ + + +The ORC and JSON files come from the `examples` directory in the Apache ORC +source tree: +https://github.com/apache/orc/tree/main/examples diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/TestOrcFile.emptyFile.orc b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/TestOrcFile.emptyFile.orc new file mode 100644 index 0000000000000000000000000000000000000000..ecdadcbff134615d7eefcb740d55fe710cee059b Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/TestOrcFile.emptyFile.orc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/TestOrcFile.test1.orc b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/TestOrcFile.test1.orc new file mode 100644 index 0000000000000000000000000000000000000000..4fb0beff868971efb653739fe6ae47a37e4a1c66 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/TestOrcFile.test1.orc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/TestOrcFile.testDate1900.orc b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/TestOrcFile.testDate1900.orc new file mode 100644 index 0000000000000000000000000000000000000000..f51ffdbd03a43fadbedce302ffa8e5967a30ad59 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/TestOrcFile.testDate1900.orc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/decimal.orc b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/decimal.orc new file mode 100644 index 0000000000000000000000000000000000000000..cb0f7b9d767a37159c5509da1a47877d1c8b411e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/data/orc/decimal.orc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..226786cbb78698fdccb8c69b78470eed8a5df553 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/__pycache__/common.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fb6823355d8b8912cadf086e54b411d7e325796 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/__pycache__/common.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/__pycache__/test_encryption.cpython-310.pyc b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/__pycache__/test_encryption.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0662a701d231550f8adea62fc0e96000256dfae Binary files /dev/null and b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/__pycache__/test_encryption.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/common.py b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/common.py new file mode 100644 index 0000000000000000000000000000000000000000..b4a57ba0b1556387403b428f43a0a3f9b7ec130b --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/common.py @@ -0,0 +1,166 @@ +# 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. + +import io + +import numpy as np + +import pyarrow as pa +from pyarrow.tests import util + + +def _write_table(table, path, **kwargs): + # So we see the ImportError somewhere + import pyarrow.parquet as pq + from pyarrow.pandas_compat import _pandas_api + + if _pandas_api.is_data_frame(table): + table = pa.Table.from_pandas(table) + + pq.write_table(table, path, **kwargs) + return table + + +def _read_table(*args, **kwargs): + import pyarrow.parquet as pq + + table = pq.read_table(*args, **kwargs) + table.validate(full=True) + return table + + +def _roundtrip_table(table, read_table_kwargs=None, + write_table_kwargs=None): + read_table_kwargs = read_table_kwargs or {} + write_table_kwargs = write_table_kwargs or {} + + writer = pa.BufferOutputStream() + _write_table(table, writer, **write_table_kwargs) + reader = pa.BufferReader(writer.getvalue()) + return _read_table(reader, **read_table_kwargs) + + +def _check_roundtrip(table, expected=None, read_table_kwargs=None, + **write_table_kwargs): + if expected is None: + expected = table + + read_table_kwargs = read_table_kwargs or {} + + # intentionally check twice + result = _roundtrip_table(table, read_table_kwargs=read_table_kwargs, + write_table_kwargs=write_table_kwargs) + assert result.equals(expected) + result = _roundtrip_table(result, read_table_kwargs=read_table_kwargs, + write_table_kwargs=write_table_kwargs) + assert result.equals(expected) + + +def _roundtrip_pandas_dataframe(df, write_kwargs): + table = pa.Table.from_pandas(df) + result = _roundtrip_table( + table, write_table_kwargs=write_kwargs) + return result.to_pandas() + + +def _random_integers(size, dtype): + # We do not generate integers outside the int64 range + platform_int_info = np.iinfo('int_') + iinfo = np.iinfo(dtype) + return np.random.randint(max(iinfo.min, platform_int_info.min), + min(iinfo.max, platform_int_info.max), + size=size, dtype=dtype) + + +def _range_integers(size, dtype): + return pa.array(np.arange(size, dtype=dtype)) + + +def _test_dataframe(size=10000, seed=0): + import pandas as pd + + np.random.seed(seed) + df = pd.DataFrame({ + 'uint8': _random_integers(size, np.uint8), + 'uint16': _random_integers(size, np.uint16), + 'uint32': _random_integers(size, np.uint32), + 'uint64': _random_integers(size, np.uint64), + 'int8': _random_integers(size, np.int8), + 'int16': _random_integers(size, np.int16), + 'int32': _random_integers(size, np.int32), + 'int64': _random_integers(size, np.int64), + 'float32': np.random.randn(size).astype(np.float32), + 'float64': np.arange(size, dtype=np.float64), + 'bool': np.random.randn(size) > 0, + 'strings': [util.rands(10) for i in range(size)], + 'all_none': [None] * size, + 'all_none_category': [None] * size + }) + + # TODO(PARQUET-1015) + # df['all_none_category'] = df['all_none_category'].astype('category') + return df + + +def make_sample_file(table_or_df): + import pyarrow.parquet as pq + + if isinstance(table_or_df, pa.Table): + a_table = table_or_df + else: + a_table = pa.Table.from_pandas(table_or_df) + + buf = io.BytesIO() + _write_table(a_table, buf, compression='SNAPPY', version='2.6') + + buf.seek(0) + return pq.ParquetFile(buf) + + +def alltypes_sample(size=10000, seed=0, categorical=False): + import pandas as pd + + np.random.seed(seed) + arrays = { + 'uint8': np.arange(size, dtype=np.uint8), + 'uint16': np.arange(size, dtype=np.uint16), + 'uint32': np.arange(size, dtype=np.uint32), + 'uint64': np.arange(size, dtype=np.uint64), + 'int8': np.arange(size, dtype=np.int16), + 'int16': np.arange(size, dtype=np.int16), + 'int32': np.arange(size, dtype=np.int32), + 'int64': np.arange(size, dtype=np.int64), + 'float16': np.arange(size, dtype=np.float16), + 'float32': np.arange(size, dtype=np.float32), + 'float64': np.arange(size, dtype=np.float64), + 'bool': np.random.randn(size) > 0, + 'datetime_ms': np.arange("2016-01-01T00:00:00.001", size, + dtype='datetime64[ms]'), + 'datetime_us': np.arange("2016-01-01T00:00:00.000001", size, + dtype='datetime64[us]'), + 'datetime_ns': np.arange("2016-01-01T00:00:00.000000001", size, + dtype='datetime64[ns]'), + 'timedelta': np.arange(0, size, dtype="timedelta64[s]"), + 'str': pd.Series([str(x) for x in range(size)]), + 'empty_str': [''] * size, + 'str_with_nulls': [None] + [str(x) for x in range(size - 2)] + [None], + 'null': [None] * size, + 'null_list': [None] * 2 + [[None] * (x % 4) for x in range(size - 2)], + } + if categorical: + arrays['str_category'] = arrays['str'].astype('category') + return pd.DataFrame(arrays) diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/conftest.py b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..767e7f6b69d0745780a28624da0639e6b7a55c08 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/conftest.py @@ -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. + +import pytest + +from pyarrow.util import guid + + +@pytest.fixture(scope='module') +def datadir(base_datadir): + return base_datadir / 'parquet' + + +@pytest.fixture +def s3_bucket(s3_server): + boto3 = pytest.importorskip('boto3') + botocore = pytest.importorskip('botocore') + s3_bucket_name = 'test-s3fs' + + host, port, access_key, secret_key = s3_server['connection'] + s3_client = boto3.client( + 's3', + endpoint_url='http://{}:{}'.format(host, port), + aws_access_key_id=access_key, + aws_secret_access_key=secret_key, + config=botocore.client.Config(signature_version='s3v4'), + region_name='us-east-1' + ) + + try: + s3_client.create_bucket(Bucket=s3_bucket_name) + except Exception: + pass # we get BucketAlreadyOwnedByYou error with fsspec handler + finally: + s3_client.close() + + return s3_bucket_name + + +@pytest.fixture +def s3_example_s3fs(s3_server, s3_bucket): + s3fs = pytest.importorskip('s3fs') + + host, port, access_key, secret_key = s3_server['connection'] + fs = s3fs.S3FileSystem( + key=access_key, + secret=secret_key, + client_kwargs={ + 'endpoint_url': 'http://{}:{}'.format(host, port) + } + ) + + test_path = '{}/{}'.format(s3_bucket, guid()) + + fs.mkdir(test_path) + yield fs, test_path + try: + fs.rm(test_path, recursive=True) + except FileNotFoundError: + pass + + +@pytest.fixture +def s3_example_fs(s3_server): + from pyarrow.fs import FileSystem + + host, port, access_key, secret_key = s3_server['connection'] + uri = ( + "s3://{}:{}@mybucket/data.parquet?scheme=http&endpoint_override={}:{}" + "&allow_bucket_creation=True" + .format(access_key, secret_key, host, port) + ) + fs, path = FileSystem.from_uri(uri) + + fs.create_dir("mybucket") + + yield fs, uri, path diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/encryption.py b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/encryption.py new file mode 100644 index 0000000000000000000000000000000000000000..d07f8ae2735207f5f6c4e6463e123ff04c539e47 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/encryption.py @@ -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. +import base64 + +import pyarrow.parquet.encryption as pe + + +class InMemoryKmsClient(pe.KmsClient): + """This is a mock class implementation of KmsClient, built for testing + only. + """ + + def __init__(self, config): + """Create an InMemoryKmsClient instance.""" + pe.KmsClient.__init__(self) + self.master_keys_map = config.custom_kms_conf + + def wrap_key(self, key_bytes, master_key_identifier): + """Not a secure cipher - the wrapped key + is just the master key concatenated with key bytes""" + master_key_bytes = self.master_keys_map[master_key_identifier].encode( + 'utf-8') + wrapped_key = b"".join([master_key_bytes, key_bytes]) + result = base64.b64encode(wrapped_key) + return result + + def unwrap_key(self, wrapped_key, master_key_identifier): + """Not a secure cipher - just extract the key from + the wrapped key""" + expected_master_key = self.master_keys_map[master_key_identifier] + decoded_wrapped_key = base64.b64decode(wrapped_key) + master_key_bytes = decoded_wrapped_key[:16] + decrypted_key = decoded_wrapped_key[16:] + if (expected_master_key == master_key_bytes.decode('utf-8')): + return decrypted_key + raise ValueError("Incorrect master key used", + master_key_bytes, decrypted_key) + + +def verify_file_encrypted(path): + """Verify that the file is encrypted by looking at its first 4 bytes. + If it's the magic string PARE + then this is a parquet with encrypted footer.""" + with open(path, "rb") as file: + magic_str = file.read(4) + # Verify magic string for parquet with encrypted footer is PARE + assert magic_str == b'PARE' diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_basic.py b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..194af7415e863415adddcd2bee33e500b6713c9e --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_basic.py @@ -0,0 +1,989 @@ +# 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. + +import os +from collections import OrderedDict +import io +import warnings +from shutil import copytree +from decimal import Decimal + +import numpy as np +import pytest + +import pyarrow as pa +from pyarrow import fs +from pyarrow.tests import util +from pyarrow.tests.parquet.common import (_check_roundtrip, _roundtrip_table, + _test_dataframe) + +try: + import pyarrow.parquet as pq + from pyarrow.tests.parquet.common import _read_table, _write_table +except ImportError: + pq = None + + +try: + import pandas as pd + import pandas.testing as tm + + from pyarrow.tests.pandas_examples import dataframe_with_lists + from pyarrow.tests.parquet.common import alltypes_sample +except ImportError: + pd = tm = None + + +# Marks all of the tests in this module +# Ignore these with pytest ... -m 'not parquet' +pytestmark = pytest.mark.parquet + + +def test_parquet_invalid_version(tempdir): + table = pa.table({'a': [1, 2, 3]}) + with pytest.raises(ValueError, match="Unsupported Parquet format version"): + _write_table(table, tempdir / 'test_version.parquet', version="2.2") + with pytest.raises(ValueError, match="Unsupported Parquet data page " + + "version"): + _write_table(table, tempdir / 'test_version.parquet', + data_page_version="2.2") + + +def test_set_data_page_size(): + arr = pa.array([1, 2, 3] * 100000) + t = pa.Table.from_arrays([arr], names=['f0']) + + # 128K, 512K + page_sizes = [2 << 16, 2 << 18] + for target_page_size in page_sizes: + _check_roundtrip(t, data_page_size=target_page_size) + + +@pytest.mark.pandas +def test_set_write_batch_size(): + df = _test_dataframe(100) + table = pa.Table.from_pandas(df, preserve_index=False) + + _check_roundtrip( + table, data_page_size=10, write_batch_size=1, version='2.4' + ) + + +@pytest.mark.pandas +def test_set_dictionary_pagesize_limit(): + df = _test_dataframe(100) + table = pa.Table.from_pandas(df, preserve_index=False) + + _check_roundtrip(table, dictionary_pagesize_limit=1, + data_page_size=10, version='2.4') + + with pytest.raises(TypeError): + _check_roundtrip(table, dictionary_pagesize_limit="a", + data_page_size=10, version='2.4') + + +@pytest.mark.pandas +def test_chunked_table_write(): + # ARROW-232 + tables = [] + batch = pa.RecordBatch.from_pandas(alltypes_sample(size=10)) + tables.append(pa.Table.from_batches([batch] * 3)) + df, _ = dataframe_with_lists() + batch = pa.RecordBatch.from_pandas(df) + tables.append(pa.Table.from_batches([batch] * 3)) + + for data_page_version in ['1.0', '2.0']: + for use_dictionary in [True, False]: + for table in tables: + _check_roundtrip( + table, version='2.6', + data_page_version=data_page_version, + use_dictionary=use_dictionary) + + +@pytest.mark.pandas +def test_memory_map(tempdir): + df = alltypes_sample(size=10) + + table = pa.Table.from_pandas(df) + _check_roundtrip(table, read_table_kwargs={'memory_map': True}, + version='2.6') + + filename = str(tempdir / 'tmp_file') + with open(filename, 'wb') as f: + _write_table(table, f, version='2.6') + table_read = pq.read_pandas(filename, memory_map=True) + assert table_read.equals(table) + + +@pytest.mark.pandas +def test_enable_buffered_stream(tempdir): + df = alltypes_sample(size=10) + + table = pa.Table.from_pandas(df) + _check_roundtrip(table, read_table_kwargs={'buffer_size': 1025}, + version='2.6') + + filename = str(tempdir / 'tmp_file') + with open(filename, 'wb') as f: + _write_table(table, f, version='2.6') + table_read = pq.read_pandas(filename, buffer_size=4096) + assert table_read.equals(table) + + +def test_special_chars_filename(tempdir): + table = pa.Table.from_arrays([pa.array([42])], ["ints"]) + filename = "foo # bar" + path = tempdir / filename + assert not path.exists() + _write_table(table, str(path)) + assert path.exists() + table_read = _read_table(str(path)) + assert table_read.equals(table) + + +def test_invalid_source(): + # Test that we provide an helpful error message pointing out + # that None wasn't expected when trying to open a Parquet None file. + with pytest.raises(TypeError, match="None"): + pq.read_table(None) + + with pytest.raises(TypeError, match="None"): + pq.ParquetFile(None) + + +@pytest.mark.slow +def test_file_with_over_int16_max_row_groups(): + # PARQUET-1857: Parquet encryption support introduced a INT16_MAX upper + # limit on the number of row groups, but this limit only impacts files with + # encrypted row group metadata because of the int16 row group ordinal used + # in the Parquet Thrift metadata. Unencrypted files are not impacted, so + # this test checks that it works (even if it isn't a good idea) + t = pa.table([list(range(40000))], names=['f0']) + _check_roundtrip(t, row_group_size=1) + + +@pytest.mark.pandas +def test_empty_table_roundtrip(): + df = alltypes_sample(size=10) + + # Create a non-empty table to infer the types correctly, then slice to 0 + table = pa.Table.from_pandas(df) + table = pa.Table.from_arrays( + [col.chunk(0)[:0] for col in table.itercolumns()], + names=table.schema.names) + + assert table.schema.field('null').type == pa.null() + assert table.schema.field('null_list').type == pa.list_(pa.null()) + _check_roundtrip( + table, version='2.6') + + +@pytest.mark.pandas +def test_empty_table_no_columns(): + df = pd.DataFrame() + empty = pa.Table.from_pandas(df, preserve_index=False) + _check_roundtrip(empty) + + +def test_write_nested_zero_length_array_chunk_failure(): + # Bug report in ARROW-3792 + cols = OrderedDict( + int32=pa.int32(), + list_string=pa.list_(pa.string()) + ) + data = [[], [OrderedDict(int32=1, list_string=('G',)), ]] + + # This produces a table with a column like + # )> + # [ + # [], + # [ + # [ + # "G" + # ] + # ] + # ] + # + # Each column is a ChunkedArray with 2 elements + my_arrays = [pa.array(batch, type=pa.struct(cols)).flatten() + for batch in data] + my_batches = [pa.RecordBatch.from_arrays(batch, schema=pa.schema(cols)) + for batch in my_arrays] + tbl = pa.Table.from_batches(my_batches, pa.schema(cols)) + _check_roundtrip(tbl) + + +@pytest.mark.pandas +def test_multiple_path_types(tempdir): + # Test compatibility with PEP 519 path-like objects + path = tempdir / 'zzz.parquet' + df = pd.DataFrame({'x': np.arange(10, dtype=np.int64)}) + _write_table(df, path) + table_read = _read_table(path) + df_read = table_read.to_pandas() + tm.assert_frame_equal(df, df_read) + + # Test compatibility with plain string paths + path = str(tempdir) + 'zzz.parquet' + df = pd.DataFrame({'x': np.arange(10, dtype=np.int64)}) + _write_table(df, path) + table_read = _read_table(path) + df_read = table_read.to_pandas() + tm.assert_frame_equal(df, df_read) + + +def test_fspath(tempdir): + # ARROW-12472 support __fspath__ objects without using str() + path = tempdir / "test.parquet" + table = pa.table({"a": [1, 2, 3]}) + _write_table(table, path) + + fs_protocol_obj = util.FSProtocolClass(path) + + result = _read_table(fs_protocol_obj) + assert result.equals(table) + + # combined with non-local filesystem raises + with pytest.raises(TypeError): + _read_table(fs_protocol_obj, filesystem=fs.FileSystem()) + + +@pytest.mark.parametrize("filesystem", [ + None, fs.LocalFileSystem() +]) +@pytest.mark.parametrize("name", ("data.parquet", "例.parquet")) +def test_relative_paths(tempdir, filesystem, name): + # reading and writing from relative paths + table = pa.table({"a": [1, 2, 3]}) + path = tempdir / name + + # reading + pq.write_table(table, str(path)) + with util.change_cwd(tempdir): + result = pq.read_table(name, filesystem=filesystem) + assert result.equals(table) + + path.unlink() + assert not path.exists() + + # writing + with util.change_cwd(tempdir): + pq.write_table(table, name, filesystem=filesystem) + result = pq.read_table(path) + assert result.equals(table) + + +def test_read_non_existing_file(): + # ensure we have a proper error message + with pytest.raises(FileNotFoundError): + pq.read_table('i-am-not-existing.parquet') + + +def test_file_error_python_exception(): + class BogusFile(io.BytesIO): + def read(self, *args): + raise ZeroDivisionError("zorglub") + + def seek(self, *args): + raise ZeroDivisionError("zorglub") + + # ensure the Python exception is restored + with pytest.raises(ZeroDivisionError, match="zorglub"): + pq.read_table(BogusFile(b"")) + + +def test_parquet_read_from_buffer(tempdir): + # reading from a buffer from python's open() + table = pa.table({"a": [1, 2, 3]}) + pq.write_table(table, str(tempdir / "data.parquet")) + + with open(str(tempdir / "data.parquet"), "rb") as f: + result = pq.read_table(f) + assert result.equals(table) + + with open(str(tempdir / "data.parquet"), "rb") as f: + result = pq.read_table(pa.PythonFile(f)) + assert result.equals(table) + + +def test_byte_stream_split(): + # This is only a smoke test. + arr_float = pa.array(list(map(float, range(100)))) + arr_int = pa.array(list(map(int, range(100)))) + arr_bool = pa.array([True, False] * 50) + data_float = [arr_float, arr_float] + table = pa.Table.from_arrays(data_float, names=['a', 'b']) + + # Check with byte_stream_split for both columns. + _check_roundtrip(table, expected=table, compression="gzip", + use_dictionary=False, use_byte_stream_split=True) + + # Check with byte_stream_split for column 'b' and dictionary + # for column 'a'. + _check_roundtrip(table, expected=table, compression="gzip", + use_dictionary=['a'], + use_byte_stream_split=['b']) + + # Check with a collision for both columns. + _check_roundtrip(table, expected=table, compression="gzip", + use_dictionary=['a', 'b'], + use_byte_stream_split=['a', 'b']) + + # Check with mixed column types. + mixed_table = pa.Table.from_arrays([arr_float, arr_float, arr_int, arr_int], + names=['a', 'b', 'c', 'd']) + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=['b', 'd'], + use_byte_stream_split=['a', 'c']) + + # Try to use the wrong data type with the byte_stream_split encoding. + # This should throw an exception. + table = pa.Table.from_arrays([arr_bool], names=['tmp']) + with pytest.raises(IOError, match='BYTE_STREAM_SPLIT only supports'): + _check_roundtrip(table, expected=table, use_byte_stream_split=True, + use_dictionary=False) + + +def test_store_decimal_as_integer(tempdir): + arr_decimal_1_9 = pa.array(list(map(Decimal, range(100))), + type=pa.decimal128(5, 2)) + arr_decimal_10_18 = pa.array(list(map(Decimal, range(100))), + type=pa.decimal128(16, 9)) + arr_decimal_gt18 = pa.array(list(map(Decimal, range(100))), + type=pa.decimal128(22, 2)) + arr_bool = pa.array([True, False] * 50) + data_decimal = [arr_decimal_1_9, arr_decimal_10_18, arr_decimal_gt18] + table = pa.Table.from_arrays(data_decimal, names=['a', 'b', 'c']) + + # Check with store_decimal_as_integer. + _check_roundtrip(table, + expected=table, + compression="gzip", + use_dictionary=False, + store_decimal_as_integer=True) + + # Check physical type in parquet schema + pqtestfile_path = os.path.join(tempdir, 'test.parquet') + pq.write_table(table, pqtestfile_path, + compression="gzip", + use_dictionary=False, + store_decimal_as_integer=True) + + pqtestfile = pq.ParquetFile(pqtestfile_path) + pqcol_decimal_1_9 = pqtestfile.schema.column(0) + pqcol_decimal_10_18 = pqtestfile.schema.column(1) + + assert pqcol_decimal_1_9.physical_type == 'INT32' + assert pqcol_decimal_10_18.physical_type == 'INT64' + + # Check with store_decimal_as_integer and delta-int encoding. + # DELTA_BINARY_PACKED requires parquet physical type to be INT64 or INT32 + _check_roundtrip(table, + expected=table, + compression="gzip", + use_dictionary=False, + store_decimal_as_integer=True, + column_encoding={ + 'a': 'DELTA_BINARY_PACKED', + 'b': 'DELTA_BINARY_PACKED' + }) + + # Check with mixed column types. + mixed_table = pa.Table.from_arrays( + [arr_decimal_1_9, arr_decimal_10_18, arr_decimal_gt18, arr_bool], + names=['a', 'b', 'c', 'd']) + _check_roundtrip(mixed_table, + expected=mixed_table, + use_dictionary=False, + store_decimal_as_integer=True) + + +def test_column_encoding(): + arr_float = pa.array(list(map(float, range(100)))) + arr_int = pa.array(list(map(int, range(100)))) + arr_bin = pa.array([str(x) for x in range(100)], type=pa.binary()) + arr_flba = pa.array( + [str(x).zfill(10) for x in range(100)], type=pa.binary(10)) + arr_bool = pa.array([False, True, False, False] * 25) + mixed_table = pa.Table.from_arrays( + [arr_float, arr_int, arr_bin, arr_flba, arr_bool], + names=['a', 'b', 'c', 'd', 'e']) + + # Check "BYTE_STREAM_SPLIT" for columns 'a', 'b', 'd' + # and "PLAIN" column_encoding for column 'c'. + _check_roundtrip(mixed_table, expected=mixed_table, use_dictionary=False, + column_encoding={'a': "BYTE_STREAM_SPLIT", + 'b': "BYTE_STREAM_SPLIT", + 'c': "PLAIN", + 'd': "BYTE_STREAM_SPLIT"}) + + # Check "PLAIN" for all columns. + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + column_encoding="PLAIN") + + # Check "DELTA_BINARY_PACKED" for integer columns. + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + column_encoding={'a': "PLAIN", + 'b': "DELTA_BINARY_PACKED", + 'c': "PLAIN"}) + + # Check "DELTA_LENGTH_BYTE_ARRAY" for byte columns. + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + column_encoding={'a': "PLAIN", + 'b': "DELTA_BINARY_PACKED", + 'c': "DELTA_LENGTH_BYTE_ARRAY"}) + + # Check "DELTA_BYTE_ARRAY" for byte columns. + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + column_encoding={'a': "PLAIN", + 'b': "DELTA_BINARY_PACKED", + 'c': "DELTA_BYTE_ARRAY", + 'd': "DELTA_BYTE_ARRAY"}) + + # Check "RLE" for boolean columns. + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + column_encoding={'e': "RLE"}) + + # Try to pass "BYTE_STREAM_SPLIT" column encoding for boolean column 'e'. + # This should throw an error as it is does not support BOOLEAN. + with pytest.raises(IOError, + match="BYTE_STREAM_SPLIT only supports"): + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + column_encoding={'a': "PLAIN", + 'c': "PLAIN", + 'e': "BYTE_STREAM_SPLIT"}) + + # Try to pass use "DELTA_BINARY_PACKED" encoding on float column. + # This should throw an error as only integers are supported. + with pytest.raises(OSError, + match="DELTA_BINARY_PACKED encoder only supports"): + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + column_encoding={'a': "DELTA_BINARY_PACKED", + 'b': "PLAIN", + 'c': "PLAIN"}) + + # Try to pass "RLE_DICTIONARY". + # This should throw an error as dictionary encoding is already used by + # default and not supported to be specified as "fallback" encoding + with pytest.raises(ValueError, + match="'RLE_DICTIONARY' is already used by default"): + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + column_encoding="RLE_DICTIONARY") + + # Try to pass unsupported encoding. + with pytest.raises(ValueError, + match="Unsupported column encoding: 'MADE_UP_ENCODING'"): + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + column_encoding={'a': "MADE_UP_ENCODING"}) + + # Try to pass column_encoding and use_dictionary. + # This should throw an error. + with pytest.raises(ValueError): + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=['b'], + column_encoding={'b': "PLAIN"}) + + # Try to pass column_encoding and use_dictionary=True (default value). + # This should throw an error. + with pytest.raises(ValueError): + _check_roundtrip(mixed_table, expected=mixed_table, + column_encoding={'b': "PLAIN"}) + + # Try to pass column_encoding and use_byte_stream_split on same column. + # This should throw an error. + with pytest.raises(ValueError): + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + use_byte_stream_split=['a'], + column_encoding={'a': "RLE", + 'b': "BYTE_STREAM_SPLIT", + 'c': "PLAIN"}) + + # Try to pass column_encoding and use_byte_stream_split=True. + # This should throw an error. + with pytest.raises(ValueError): + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + use_byte_stream_split=True, + column_encoding={'a': "RLE", + 'b': "BYTE_STREAM_SPLIT", + 'c': "PLAIN"}) + + # Try to pass column_encoding=True. + # This should throw an error. + with pytest.raises(TypeError): + _check_roundtrip(mixed_table, expected=mixed_table, + use_dictionary=False, + column_encoding=True) + + +def test_compression_level(): + arr = pa.array(list(map(int, range(1000)))) + data = [arr, arr] + table = pa.Table.from_arrays(data, names=['a', 'b']) + + # Check one compression level. + _check_roundtrip(table, expected=table, compression="gzip", + compression_level=1) + + # Check another one to make sure that compression_level=1 does not + # coincide with the default one in Arrow. + _check_roundtrip(table, expected=table, compression="gzip", + compression_level=5) + + # Check that the user can provide a compression per column + _check_roundtrip(table, expected=table, + compression={'a': "gzip", 'b': "snappy"}) + + # Check that the user can provide a compression level per column + _check_roundtrip(table, expected=table, compression="gzip", + compression_level={'a': 2, 'b': 3}) + + # Check if both LZ4 compressors are working + # (level < 3 -> fast, level >= 3 -> HC) + _check_roundtrip(table, expected=table, compression="lz4", + compression_level=1) + + _check_roundtrip(table, expected=table, compression="lz4", + compression_level=9) + + # Check that specifying a compression level for a codec which does allow + # specifying one, results into an error. + # Uncompressed, snappy and lzo do not support specifying a compression + # level. + # GZIP (zlib) allows for specifying a compression level but as of up + # to version 1.2.11 the valid range is [-1, 9]. + invalid_combinations = [("snappy", 4), ("gzip", -1337), + ("None", 444), ("lzo", 14)] + buf = io.BytesIO() + for (codec, level) in invalid_combinations: + with pytest.raises((ValueError, OSError)): + _write_table(table, buf, compression=codec, + compression_level=level) + + +def test_sanitized_spark_field_names(): + a0 = pa.array([0, 1, 2, 3, 4]) + name = 'prohib; ,\t{}' + table = pa.Table.from_arrays([a0], [name]) + + result = _roundtrip_table(table, write_table_kwargs={'flavor': 'spark'}) + + expected_name = 'prohib______' + assert result.schema[0].name == expected_name + + +@pytest.mark.pandas +def test_multithreaded_read(): + df = alltypes_sample(size=10000) + + table = pa.Table.from_pandas(df) + + buf = io.BytesIO() + _write_table(table, buf, compression='SNAPPY', version='2.6') + + buf.seek(0) + table1 = _read_table(buf, use_threads=True) + + buf.seek(0) + table2 = _read_table(buf, use_threads=False) + + assert table1.equals(table2) + + +@pytest.mark.pandas +def test_min_chunksize(): + data = pd.DataFrame([np.arange(4)], columns=['A', 'B', 'C', 'D']) + table = pa.Table.from_pandas(data.reset_index()) + + buf = io.BytesIO() + _write_table(table, buf, chunk_size=-1) + + buf.seek(0) + result = _read_table(buf) + + assert result.equals(table) + + with pytest.raises(ValueError): + _write_table(table, buf, chunk_size=0) + + +@pytest.mark.pandas +def test_write_error_deletes_incomplete_file(tempdir): + # ARROW-1285 + df = pd.DataFrame({'a': list('abc'), + 'b': list(range(1, 4)), + 'c': np.arange(3, 6).astype('u1'), + 'd': np.arange(4.0, 7.0, dtype='float64'), + 'e': [True, False, True], + 'f': pd.Categorical(list('abc')), + 'g': pd.date_range('20130101', periods=3), + 'h': pd.date_range('20130101', periods=3, + tz='US/Eastern'), + 'i': pd.date_range('20130101', periods=3, freq='ns')}) + + pdf = pa.Table.from_pandas(df) + + filename = tempdir / 'tmp_file' + try: + # Test relies on writing nanoseconds to raise an error + # true for Parquet 2.4 + _write_table(pdf, filename, version="2.4") + except pa.ArrowException: + pass + + assert not filename.exists() + + +def test_read_non_existent_file(tempdir): + path = 'nonexistent-file.parquet' + try: + pq.read_table(path) + except Exception as e: + assert path in e.args[0] + + +def test_read_table_doesnt_warn(datadir): + with warnings.catch_warnings(): + warnings.simplefilter(action="error") + pq.read_table(datadir / 'v0.7.1.parquet') + + +@pytest.mark.pandas +def test_zlib_compression_bug(): + # ARROW-3514: "zlib deflate failed, output buffer too small" + table = pa.Table.from_arrays([pa.array(['abc', 'def'])], ['some_col']) + f = io.BytesIO() + pq.write_table(table, f, compression='gzip') + + f.seek(0) + roundtrip = pq.read_table(f) + tm.assert_frame_equal(roundtrip.to_pandas(), table.to_pandas()) + + +def test_parquet_file_too_small(tempdir): + path = str(tempdir / "test.parquet") + # TODO(dataset) with datasets API it raises OSError instead + with pytest.raises((pa.ArrowInvalid, OSError), + match='size is 0 bytes'): + with open(path, 'wb') as f: + pass + pq.read_table(path) + + with pytest.raises((pa.ArrowInvalid, OSError), + match='size is 4 bytes'): + with open(path, 'wb') as f: + f.write(b'ffff') + pq.read_table(path) + + +@pytest.mark.pandas +@pytest.mark.fastparquet +@pytest.mark.filterwarnings("ignore:RangeIndex:FutureWarning") +@pytest.mark.filterwarnings("ignore:tostring:DeprecationWarning:fastparquet") +def test_fastparquet_cross_compatibility(tempdir): + fp = pytest.importorskip('fastparquet') + + df = pd.DataFrame( + { + "a": list("abc"), + "b": list(range(1, 4)), + "c": np.arange(4.0, 7.0, dtype="float64"), + "d": [True, False, True], + "e": pd.date_range("20130101", periods=3), + "f": pd.Categorical(["a", "b", "a"]), + # fastparquet writes list as BYTE_ARRAY JSON, so no roundtrip + # "g": [[1, 2], None, [1, 2, 3]], + } + ) + table = pa.table(df) + + # Arrow -> fastparquet + file_arrow = str(tempdir / "cross_compat_arrow.parquet") + pq.write_table(table, file_arrow, compression=None) + + fp_file = fp.ParquetFile(file_arrow) + df_fp = fp_file.to_pandas() + tm.assert_frame_equal(df, df_fp) + + # Fastparquet -> arrow + file_fastparquet = str(tempdir / "cross_compat_fastparquet.parquet") + fp.write(file_fastparquet, df) + + table_fp = pq.read_pandas(file_fastparquet) + # for fastparquet written file, categoricals comes back as strings + # (no arrow schema in parquet metadata) + df['f'] = df['f'].astype(object) + tm.assert_frame_equal(table_fp.to_pandas(), df) + + +@pytest.mark.parametrize('array_factory', [ + lambda: pa.array([0, None] * 10), + lambda: pa.array([0, None] * 10).dictionary_encode(), + lambda: pa.array(["", None] * 10), + lambda: pa.array(["", None] * 10).dictionary_encode(), +]) +@pytest.mark.parametrize('read_dictionary', [False, True]) +def test_buffer_contents( + array_factory, read_dictionary +): + # Test that null values are deterministically initialized to zero + # after a roundtrip through Parquet. + # See ARROW-8006 and ARROW-8011. + orig_table = pa.Table.from_pydict({"col": array_factory()}) + bio = io.BytesIO() + pq.write_table(orig_table, bio, use_dictionary=True) + bio.seek(0) + read_dictionary = ['col'] if read_dictionary else None + table = pq.read_table(bio, use_threads=False, + read_dictionary=read_dictionary) + + for col in table.columns: + [chunk] = col.chunks + buf = chunk.buffers()[1] + assert buf.to_pybytes() == buf.size * b"\0" + + +def test_parquet_compression_roundtrip(tempdir): + # ARROW-10480: ensure even with nonstandard Parquet file naming + # conventions, writing and then reading a file works. In + # particular, ensure that we don't automatically double-compress + # the stream due to auto-detecting the extension in the filename + table = pa.table([pa.array(range(4))], names=["ints"]) + path = tempdir / "arrow-10480.pyarrow.gz" + pq.write_table(table, path, compression="GZIP") + result = pq.read_table(path) + assert result.equals(table) + + +def test_empty_row_groups(tempdir): + # ARROW-3020 + table = pa.Table.from_arrays([pa.array([], type='int32')], ['f0']) + + path = tempdir / 'empty_row_groups.parquet' + + num_groups = 3 + with pq.ParquetWriter(path, table.schema) as writer: + for i in range(num_groups): + writer.write_table(table) + + reader = pq.ParquetFile(path) + assert reader.metadata.num_row_groups == num_groups + + for i in range(num_groups): + assert reader.read_row_group(i).equals(table) + + +def test_reads_over_batch(tempdir): + data = [None] * (1 << 20) + data.append([1]) + # Large list with mostly nones and one final + # value. This should force batched reads when + # reading back. + table = pa.Table.from_arrays([data], ['column']) + + path = tempdir / 'arrow-11607.parquet' + pq.write_table(table, path) + table2 = pq.read_table(path) + assert table == table2 + + +def test_permutation_of_column_order(tempdir): + # ARROW-2366 + case = tempdir / "dataset_column_order_permutation" + case.mkdir(exist_ok=True) + + data1 = pa.table([[1, 2, 3], [.1, .2, .3]], names=['a', 'b']) + pq.write_table(data1, case / "data1.parquet") + + data2 = pa.table([[.4, .5, .6], [4, 5, 6]], names=['b', 'a']) + pq.write_table(data2, case / "data2.parquet") + + table = pq.read_table(str(case)) + table2 = pa.table([[1, 2, 3, 4, 5, 6], + [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]], + names=['a', 'b']) + + assert table == table2 + + +def test_thrift_size_limits(tempdir): + path = tempdir / 'largethrift.parquet' + + array = pa.array(list(range(10))) + num_cols = 1000 + table = pa.table( + [array] * num_cols, + names=[f'some_long_column_name_{i}' for i in range(num_cols)]) + pq.write_table(table, path) + + with pytest.raises( + OSError, + match="Couldn't deserialize thrift:.*Exceeded size limit"): + pq.read_table(path, thrift_string_size_limit=50 * num_cols) + with pytest.raises( + OSError, + match="Couldn't deserialize thrift:.*Exceeded size limit"): + pq.read_table(path, thrift_container_size_limit=num_cols) + + got = pq.read_table(path, thrift_string_size_limit=100 * num_cols) + assert got == table + got = pq.read_table(path, thrift_container_size_limit=2 * num_cols) + assert got == table + got = pq.read_table(path) + assert got == table + + +def test_page_checksum_verification_write_table(tempdir): + """Check that checksum verification works for datasets created with + pq.write_table()""" + + # Write some sample data into a parquet file with page checksum enabled + original_path = tempdir / 'correct.parquet' + table_orig = pa.table({'a': [1, 2, 3, 4]}) + pq.write_table(table_orig, original_path, write_page_checksum=True) + + # Read file and verify that the data is correct + table_check = pq.read_table(original_path, page_checksum_verification=True) + assert table_orig == table_check + + # Read the original file as binary and swap the 31-th and 36-th bytes. This + # should be equivalent to storing the following data: + # pa.table({'a': [1, 3, 2, 4]}) + bin_data = bytearray(original_path.read_bytes()) + + # Swap two bytes to emulate corruption. Also, check that the two bytes are + # different, otherwise no corruption occurs + assert bin_data[31] != bin_data[36] + bin_data[31], bin_data[36] = bin_data[36], bin_data[31] + + # Write the corrupted data to another parquet file + corrupted_path = tempdir / 'corrupted.parquet' + corrupted_path.write_bytes(bin_data) + + # Case 1: Reading the corrupted file with read_table() and without page + # checksum verification succeeds but yields corrupted data + table_corrupt = pq.read_table(corrupted_path, + page_checksum_verification=False) + # The read should complete without error, but the table has different + # content than the original file! + assert table_corrupt != table_orig + assert table_corrupt == pa.table({'a': [1, 3, 2, 4]}) + + # Case 2: Reading the corrupted file with read_table() and with page + # checksum verification enabled raises an exception + with pytest.raises(OSError, match="CRC checksum verification"): + _ = pq.read_table(corrupted_path, page_checksum_verification=True) + + # Case 3: Reading the corrupted file with ParquetFile.read() and without + # page checksum verification succeeds but yields corrupted data + corrupted_pq_file = pq.ParquetFile(corrupted_path, + page_checksum_verification=False) + table_corrupt2 = corrupted_pq_file.read() + assert table_corrupt2 != table_orig + assert table_corrupt2 == pa.table({'a': [1, 3, 2, 4]}) + + # Case 4: Reading the corrupted file with ParquetFile.read() and with page + # checksum verification enabled raises an exception + corrupted_pq_file = pq.ParquetFile(corrupted_path, + page_checksum_verification=True) + # Accessing the data should result in an error + with pytest.raises(OSError, match="CRC checksum verification"): + _ = corrupted_pq_file.read() + + +@pytest.mark.dataset +def test_checksum_write_to_dataset(tempdir): + """Check that checksum verification works for datasets created with + pq.write_to_dataset""" + + table_orig = pa.table({'a': [1, 2, 3, 4]}) + + # Write a sample dataset with page checksum enabled + original_dir_path = tempdir / 'correct_dir' + pq.write_to_dataset(table_orig, + original_dir_path, + write_page_checksum=True) + + # Read file and verify that the data is correct + original_file_path_list = list(original_dir_path.iterdir()) + assert len(original_file_path_list) == 1 + original_path = original_file_path_list[0] + table_check = pq.read_table(original_path, page_checksum_verification=True) + assert table_orig == table_check + + # Read the original file as binary and swap the 31-th and 36-th bytes. This + # should be equivalent to storing the following data: + # pa.table({'a': [1, 3, 2, 4]}) + bin_data = bytearray(original_path.read_bytes()) + + # Swap two bytes to emulate corruption. Also, check that the two bytes are + # different, otherwise no corruption occurs + assert bin_data[31] != bin_data[36] + bin_data[31], bin_data[36] = bin_data[36], bin_data[31] + + # Write the corrupted data to another parquet dataset + # Copy dataset dir (which should be just one file) + corrupted_dir_path = tempdir / 'corrupted_dir' + copytree(original_dir_path, corrupted_dir_path) + # Corrupt just the one file with the dataset + corrupted_file_path = corrupted_dir_path / original_path.name + corrupted_file_path.write_bytes(bin_data) + + # Case 1: Reading the corrupted file with read_table() and without page + # checksum verification succeeds but yields corrupted data + table_corrupt = pq.read_table(corrupted_file_path, + page_checksum_verification=False) + # The read should complete without error, but the table has different + # content than the original file! + assert table_corrupt != table_orig + assert table_corrupt == pa.table({'a': [1, 3, 2, 4]}) + + # Case 2: Reading the corrupted file with read_table() and with page + # checksum verification enabled raises an exception + with pytest.raises(OSError, match="CRC checksum verification"): + _ = pq.read_table(corrupted_file_path, page_checksum_verification=True) + + +@pytest.mark.dataset +def test_deprecated_use_legacy_dataset(tempdir): + # Test that specifying use_legacy_dataset in ParquetDataset, write_to_dataset + # and read_table doesn't raise an error but gives a warning. + table = pa.table({"a": [1, 2, 3]}) + path = tempdir / "deprecate_legacy" + + msg = "Passing 'use_legacy_dataset'" + with pytest.warns(FutureWarning, match=msg): + pq.write_to_dataset(table, path, use_legacy_dataset=False) + + pq.write_to_dataset(table, path) + + with pytest.warns(FutureWarning, match=msg): + pq.read_table(path, use_legacy_dataset=False) + + with pytest.warns(FutureWarning, match=msg): + pq.ParquetDataset(path, use_legacy_dataset=False) diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_compliant_nested_type.py b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_compliant_nested_type.py new file mode 100644 index 0000000000000000000000000000000000000000..2345855a3321b6af48acfc0fcba0732e4af2c92c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_compliant_nested_type.py @@ -0,0 +1,109 @@ +# 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. + +import pytest + +import pyarrow as pa + +try: + import pyarrow.parquet as pq + from pyarrow.tests.parquet.common import (_read_table, + _check_roundtrip) +except ImportError: + pq = None + +try: + import pandas as pd + import pandas.testing as tm + + from pyarrow.tests.parquet.common import _roundtrip_pandas_dataframe +except ImportError: + pd = tm = None + + +# Marks all of the tests in this module +# Ignore these with pytest ... -m 'not parquet' +pytestmark = pytest.mark.parquet + + +# Tests for ARROW-11497 +_test_data_simple = [ + {'items': [1, 2]}, + {'items': [0]}, +] + +_test_data_complex = [ + {'items': [{'name': 'elem1', 'value': '1'}, + {'name': 'elem2', 'value': '2'}]}, + {'items': [{'name': 'elem1', 'value': '0'}]}, +] + +parametrize_test_data = pytest.mark.parametrize( + "test_data", [_test_data_simple, _test_data_complex]) + + +@pytest.mark.pandas +@parametrize_test_data +def test_write_compliant_nested_type_enable(tempdir, test_data): + # prepare dataframe for testing + df = pd.DataFrame(data=test_data) + # verify that we can read/write pandas df with new flag (default behaviour) + _roundtrip_pandas_dataframe(df, + write_kwargs={}) + + # Write to a parquet file with compliant nested type + table = pa.Table.from_pandas(df, preserve_index=False) + path = str(tempdir / 'data.parquet') + with pq.ParquetWriter(path, table.schema, + version='2.6') as writer: + writer.write_table(table) + # Read back as a table + new_table = _read_table(path) + # Validate that "items" columns compliant to Parquet nested format + # Should be like this: list> + assert isinstance(new_table.schema.types[0], pa.ListType) + assert new_table.schema.types[0].value_field.name == 'element' + + # Verify that the new table can be read/written correctly + _check_roundtrip(new_table) + + +@pytest.mark.pandas +@parametrize_test_data +def test_write_compliant_nested_type_disable(tempdir, test_data): + # prepare dataframe for testing + df = pd.DataFrame(data=test_data) + # verify that we can read/write with new flag disabled + _roundtrip_pandas_dataframe(df, write_kwargs={ + 'use_compliant_nested_type': False}) + + # Write to a parquet file while disabling compliant nested type + table = pa.Table.from_pandas(df, preserve_index=False) + path = str(tempdir / 'data.parquet') + with pq.ParquetWriter(path, table.schema, version='2.6', + use_compliant_nested_type=False) as writer: + writer.write_table(table) + new_table = _read_table(path) + + # Validate that "items" columns is not compliant to Parquet nested format + # Should be like this: list> + assert isinstance(new_table.schema.types[0], pa.ListType) + assert new_table.schema.types[0].value_field.name == 'item' + + # Verify that the new table can be read/written correctly + _check_roundtrip(new_table, + use_compliant_nested_type=False) diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_dataset.py b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..47e608a1404ff6d88bd8af4ec6d6ac504d7b5487 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_dataset.py @@ -0,0 +1,1331 @@ +# 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. + +import datetime +import inspect +import os +import pathlib + +import numpy as np +import pytest +import unittest.mock as mock + +import pyarrow as pa +import pyarrow.compute as pc +from pyarrow.fs import (FileSelector, FileSystem, LocalFileSystem, + PyFileSystem, SubTreeFileSystem, FSSpecHandler) +from pyarrow.tests import util +from pyarrow.util import guid + +try: + import pyarrow.parquet as pq + from pyarrow.tests.parquet.common import ( + _read_table, _test_dataframe, _write_table) +except ImportError: + pq = None + + +try: + import pandas as pd + import pandas.testing as tm + +except ImportError: + pd = tm = None + + +# Marks all of the tests in this module +# Ignore these with pytest ... -m 'not parquet' +pytestmark = [pytest.mark.parquet, pytest.mark.dataset] + + +def test_filesystem_uri(tempdir): + table = pa.table({"a": [1, 2, 3]}) + + directory = tempdir / "data_dir" + directory.mkdir() + path = directory / "data.parquet" + pq.write_table(table, str(path)) + + # filesystem object + result = pq.read_table( + path, filesystem=LocalFileSystem()) + assert result.equals(table) + + # filesystem URI + result = pq.read_table( + "data_dir/data.parquet", filesystem=util._filesystem_uri(tempdir)) + assert result.equals(table) + + +@pytest.mark.pandas +def test_read_partitioned_directory(tempdir): + local = LocalFileSystem() + _partition_test_for_filesystem(local, tempdir) + + +@pytest.mark.pandas +def test_read_partitioned_columns_selection(tempdir): + # ARROW-3861 - do not include partition columns in resulting table when + # `columns` keyword was passed without those columns + local = LocalFileSystem() + base_path = tempdir + _partition_test_for_filesystem(local, base_path) + + dataset = pq.ParquetDataset(base_path) + result = dataset.read(columns=["values"]) + assert result.column_names == ["values"] + + +@pytest.mark.pandas +def test_filters_equivalency(tempdir): + local = LocalFileSystem() + base_path = tempdir + + integer_keys = [0, 1] + string_keys = ['a', 'b', 'c'] + boolean_keys = [True, False] + partition_spec = [ + ['integer', integer_keys], + ['string', string_keys], + ['boolean', boolean_keys] + ] + + df = pd.DataFrame({ + 'integer': np.array(integer_keys, dtype='i4').repeat(15), + 'string': np.tile(np.tile(np.array(string_keys, dtype=object), 5), 2), + 'boolean': np.tile(np.tile(np.array(boolean_keys, dtype='bool'), 5), 3), + 'values': np.arange(30), + }) + + _generate_partition_directories(local, base_path, partition_spec, df) + + # Old filters syntax: + # integer == 1 AND string != b AND boolean == True + dataset = pq.ParquetDataset( + base_path, filesystem=local, + filters=[('integer', '=', 1), ('string', '!=', 'b'), + ('boolean', '==', 'True')], + ) + table = dataset.read() + result_df = (table.to_pandas().reset_index(drop=True)) + + assert 0 not in result_df['integer'].values + assert 'b' not in result_df['string'].values + assert False not in result_df['boolean'].values + + # filters in disjunctive normal form: + # (integer == 1 AND string != b AND boolean == True) OR + # (integer == 2 AND boolean == False) + # TODO(ARROW-3388): boolean columns are reconstructed as string + filters = [ + [ + ('integer', '=', 1), + ('string', '!=', 'b'), + ('boolean', '==', 'True') + ], + [('integer', '=', 0), ('boolean', '==', 'False')] + ] + dataset = pq.ParquetDataset( + base_path, filesystem=local, filters=filters) + table = dataset.read() + result_df = table.to_pandas().reset_index(drop=True) + + # Check that all rows in the DF fulfill the filter + df_filter_1 = (result_df['integer'] == 1) \ + & (result_df['string'] != 'b') \ + & (result_df['boolean'] == 'True') + df_filter_2 = (np.array(result_df['integer']) == 0) \ + & (result_df['boolean'] == 'False') + assert df_filter_1.sum() > 0 + assert df_filter_2.sum() > 0 + assert result_df.shape[0] == (df_filter_1.sum() + df_filter_2.sum()) + + for filters in [[[('string', '==', b'1\0a')]], + [[('string', '==', '1\0a')]]]: + dataset = pq.ParquetDataset( + base_path, filesystem=local, filters=filters) + assert dataset.read().num_rows == 0 + + +@pytest.mark.pandas +def test_filters_cutoff_exclusive_integer(tempdir): + local = LocalFileSystem() + base_path = tempdir + + integer_keys = [0, 1, 2, 3, 4] + partition_spec = [ + ['integers', integer_keys], + ] + N = 5 + + df = pd.DataFrame({ + 'index': np.arange(N), + 'integers': np.array(integer_keys, dtype='i4'), + }, columns=['index', 'integers']) + + _generate_partition_directories(local, base_path, partition_spec, df) + + dataset = pq.ParquetDataset( + base_path, filesystem=local, + filters=[ + ('integers', '<', 4), + ('integers', '>', 1), + ], + ) + table = dataset.read() + result_df = (table.to_pandas() + .sort_values(by='index') + .reset_index(drop=True)) + + result_list = [x for x in map(int, result_df['integers'].values)] + assert result_list == [2, 3] + + +@pytest.mark.xfail( + # different error with use_legacy_datasets because result_df is no longer + # categorical + raises=(TypeError, AssertionError), + reason='Loss of type information in creation of categoricals.' +) +@pytest.mark.pandas +def test_filters_cutoff_exclusive_datetime(tempdir): + local = LocalFileSystem() + base_path = tempdir + + date_keys = [ + datetime.date(2018, 4, 9), + datetime.date(2018, 4, 10), + datetime.date(2018, 4, 11), + datetime.date(2018, 4, 12), + datetime.date(2018, 4, 13) + ] + partition_spec = [ + ['dates', date_keys] + ] + N = 5 + + df = pd.DataFrame({ + 'index': np.arange(N), + 'dates': np.array(date_keys, dtype='datetime64'), + }, columns=['index', 'dates']) + + _generate_partition_directories(local, base_path, partition_spec, df) + + dataset = pq.ParquetDataset( + base_path, filesystem=local, + filters=[ + ('dates', '<', "2018-04-12"), + ('dates', '>', "2018-04-10") + ], + ) + table = dataset.read() + result_df = (table.to_pandas() + .sort_values(by='index') + .reset_index(drop=True)) + + expected = pd.Categorical( + np.array([datetime.date(2018, 4, 11)], dtype='datetime64'), + categories=np.array(date_keys, dtype='datetime64')) + + assert result_df['dates'].values == expected + + +@pytest.mark.pandas +def test_filters_inclusive_datetime(tempdir): + # ARROW-11480 + path = tempdir / 'timestamps.parquet' + + pd.DataFrame({ + "dates": pd.date_range("2020-01-01", periods=10, freq="D"), + "id": range(10) + }).to_parquet(path, use_deprecated_int96_timestamps=True) + + table = pq.read_table(path, filters=[ + ("dates", "<=", datetime.datetime(2020, 1, 5)) + ]) + + assert table.column('id').to_pylist() == [0, 1, 2, 3, 4] + + +@pytest.mark.pandas +def test_filters_inclusive_integer(tempdir): + local = LocalFileSystem() + base_path = tempdir + + integer_keys = [0, 1, 2, 3, 4] + partition_spec = [ + ['integers', integer_keys], + ] + N = 5 + + df = pd.DataFrame({ + 'index': np.arange(N), + 'integers': np.array(integer_keys, dtype='i4'), + }, columns=['index', 'integers']) + + _generate_partition_directories(local, base_path, partition_spec, df) + + dataset = pq.ParquetDataset( + base_path, filesystem=local, + filters=[ + ('integers', '<=', 3), + ('integers', '>=', 2), + ], + ) + table = dataset.read() + result_df = (table.to_pandas() + .sort_values(by='index') + .reset_index(drop=True)) + + result_list = [int(x) for x in map(int, result_df['integers'].values)] + assert result_list == [2, 3] + + +@pytest.mark.pandas +def test_filters_inclusive_set(tempdir): + local = LocalFileSystem() + base_path = tempdir + + integer_keys = [0, 1] + string_keys = ['a', 'b', 'c'] + boolean_keys = [True, False] + partition_spec = [ + ['integer', integer_keys], + ['string', string_keys], + ['boolean', boolean_keys] + ] + + df = pd.DataFrame({ + 'integer': np.array(integer_keys, dtype='i4').repeat(15), + 'string': np.tile(np.tile(np.array(string_keys, dtype=object), 5), 2), + 'boolean': np.tile(np.tile(np.array(boolean_keys, dtype='bool'), 5), 3), + 'values': np.arange(30), + }) + + _generate_partition_directories(local, base_path, partition_spec, df) + + dataset = pq.ParquetDataset( + base_path, filesystem=local, + filters=[('string', 'in', 'ab')], + ) + table = dataset.read() + result_df = (table.to_pandas().reset_index(drop=True)) + + assert 'a' in result_df['string'].values + assert 'b' in result_df['string'].values + assert 'c' not in result_df['string'].values + + dataset = pq.ParquetDataset( + base_path, filesystem=local, + filters=[('integer', 'in', [1]), ('string', 'in', ('a', 'b')), + ('boolean', 'not in', {'False'})], + ) + table = dataset.read() + result_df = (table.to_pandas().reset_index(drop=True)) + + assert 0 not in result_df['integer'].values + assert 'c' not in result_df['string'].values + assert False not in result_df['boolean'].values + + +@pytest.mark.pandas +def test_filters_invalid_pred_op(tempdir): + local = LocalFileSystem() + base_path = tempdir + + integer_keys = [0, 1, 2, 3, 4] + partition_spec = [ + ['integers', integer_keys], + ] + N = 5 + + df = pd.DataFrame({ + 'index': np.arange(N), + 'integers': np.array(integer_keys, dtype='i4'), + }, columns=['index', 'integers']) + + _generate_partition_directories(local, base_path, partition_spec, df) + + with pytest.raises(TypeError): + pq.ParquetDataset(base_path, + filesystem=local, + filters=[('integers', 'in', 3), ]) + + with pytest.raises(ValueError): + pq.ParquetDataset(base_path, + filesystem=local, + filters=[('integers', '=<', 3), ]) + + # Dataset API returns empty table + dataset = pq.ParquetDataset(base_path, + filesystem=local, + filters=[('integers', 'in', set()), ]) + assert dataset.read().num_rows == 0 + + dataset = pq.ParquetDataset(base_path, + filesystem=local, + filters=[('integers', '!=', {3})]) + with pytest.raises(NotImplementedError): + assert dataset.read().num_rows == 0 + + +@pytest.mark.pandas +def test_filters_invalid_column(tempdir): + # ARROW-5572 - raise error on invalid name in filter specification + # works with new dataset + local = LocalFileSystem() + base_path = tempdir + + integer_keys = [0, 1, 2, 3, 4] + partition_spec = [['integers', integer_keys]] + N = 5 + + df = pd.DataFrame({ + 'index': np.arange(N), + 'integers': np.array(integer_keys, dtype='i4'), + }, columns=['index', 'integers']) + + _generate_partition_directories(local, base_path, partition_spec, df) + + msg = r"No match for FieldRef.Name\(non_existent_column\)" + with pytest.raises(ValueError, match=msg): + pq.ParquetDataset(base_path, filesystem=local, + filters=[('non_existent_column', '<', 3), ]).read() + + +@pytest.mark.pandas +@pytest.mark.parametrize("filters", + ([('integers', '<', 3)], + [[('integers', '<', 3)]], + pc.field('integers') < 3, + pc.field('nested', 'a') < 3, + pc.field('nested', 'b').cast(pa.int64()) < 3)) +@pytest.mark.parametrize("read_method", ("read_table", "read_pandas")) +def test_filters_read_table(tempdir, filters, read_method): + read = getattr(pq, read_method) + # test that filters keyword is passed through in read_table + local = LocalFileSystem() + base_path = tempdir + + integer_keys = [0, 1, 2, 3, 4] + partition_spec = [ + ['integers', integer_keys], + ] + N = len(integer_keys) + + df = pd.DataFrame({ + 'index': np.arange(N), + 'integers': np.array(integer_keys, dtype='i4'), + 'nested': np.array([{'a': i, 'b': str(i)} for i in range(N)]) + }) + + _generate_partition_directories(local, base_path, partition_spec, df) + + kwargs = dict(filesystem=local, filters=filters) + + table = read(base_path, **kwargs) + assert table.num_rows == 3 + + +@pytest.mark.pandas +def test_partition_keys_with_underscores(tempdir): + # ARROW-5666 - partition field values with underscores preserve underscores + local = LocalFileSystem() + base_path = tempdir + + string_keys = ["2019_2", "2019_3"] + partition_spec = [ + ['year_week', string_keys], + ] + N = 2 + + df = pd.DataFrame({ + 'index': np.arange(N), + 'year_week': np.array(string_keys, dtype='object'), + }, columns=['index', 'year_week']) + + _generate_partition_directories(local, base_path, partition_spec, df) + + dataset = pq.ParquetDataset(base_path) + result = dataset.read() + assert result.column("year_week").to_pylist() == string_keys + + +@pytest.mark.s3 +def test_read_s3fs(s3_example_s3fs, ): + fs, path = s3_example_s3fs + path = path + "/test.parquet" + table = pa.table({"a": [1, 2, 3]}) + _write_table(table, path, filesystem=fs) + + result = _read_table(path, filesystem=fs) + assert result.equals(table) + + +@pytest.mark.s3 +def test_read_directory_s3fs(s3_example_s3fs): + fs, directory = s3_example_s3fs + path = directory + "/test.parquet" + table = pa.table({"a": [1, 2, 3]}) + _write_table(table, path, filesystem=fs) + + result = _read_table(directory, filesystem=fs) + assert result.equals(table) + + +@pytest.mark.pandas +def test_read_single_file_list(tempdir): + data_path = str(tempdir / 'data.parquet') + + table = pa.table({"a": [1, 2, 3]}) + _write_table(table, data_path) + + result = pq.ParquetDataset([data_path]).read() + assert result.equals(table) + + +@pytest.mark.pandas +@pytest.mark.s3 +def test_read_partitioned_directory_s3fs(s3_example_s3fs): + fs, path = s3_example_s3fs + _partition_test_for_filesystem(fs, path) + + +def _partition_test_for_filesystem(fs, base_path): + foo_keys = [0, 1] + bar_keys = ['a', 'b', 'c'] + partition_spec = [ + ['foo', foo_keys], + ['bar', bar_keys] + ] + N = 30 + + df = pd.DataFrame({ + 'index': np.arange(N), + 'foo': np.array(foo_keys, dtype='i4').repeat(15), + 'bar': np.tile(np.tile(np.array(bar_keys, dtype=object), 5), 2), + 'values': np.random.randn(N) + }, columns=['index', 'foo', 'bar', 'values']) + + _generate_partition_directories(fs, base_path, partition_spec, df) + + dataset = pq.ParquetDataset(base_path, filesystem=fs) + table = dataset.read() + result_df = (table.to_pandas() + .sort_values(by='index') + .reset_index(drop=True)) + + expected_df = (df.sort_values(by='index') + .reset_index(drop=True) + .reindex(columns=result_df.columns)) + + # With pandas 2.0.0 Index can store all numeric dtypes (not just + # int64/uint64/float64). Using astype() to create a categorical + # column preserves original dtype (int32) + expected_df['foo'] = expected_df['foo'].astype("category") + expected_df['bar'] = expected_df['bar'].astype("category") + + assert (result_df.columns == ['index', 'values', 'foo', 'bar']).all() + + tm.assert_frame_equal(result_df, expected_df) + + +def _generate_partition_directories(fs, base_dir, partition_spec, df): + # partition_spec : list of lists, e.g. [['foo', [0, 1, 2], + # ['bar', ['a', 'b', 'c']] + # part_table : a pyarrow.Table to write to each partition + if not isinstance(fs, FileSystem): + fs = PyFileSystem(FSSpecHandler(fs)) + + DEPTH = len(partition_spec) + + pathsep = getattr(fs, "pathsep", getattr(fs, "sep", "/")) + + def _visit_level(base_dir, level, part_keys): + name, values = partition_spec[level] + for value in values: + this_part_keys = part_keys + [(name, value)] + + level_dir = pathsep.join([ + str(base_dir), + '{}={}'.format(name, value) + ]) + fs.create_dir(level_dir) + + if level == DEPTH - 1: + # Generate example data + from pyarrow.fs import FileType + + file_path = pathsep.join([level_dir, guid()]) + filtered_df = _filter_partition(df, this_part_keys) + part_table = pa.Table.from_pandas(filtered_df) + with fs.open_output_stream(file_path) as f: + _write_table(part_table, f) + assert fs.get_file_info(file_path).type != FileType.NotFound + assert fs.get_file_info(file_path).type == FileType.File + + file_success = pathsep.join([level_dir, '_SUCCESS']) + with fs.open_output_stream(file_success) as f: + pass + else: + _visit_level(level_dir, level + 1, this_part_keys) + file_success = pathsep.join([level_dir, '_SUCCESS']) + with fs.open_output_stream(file_success) as f: + pass + + _visit_level(base_dir, 0, []) + + +def _filter_partition(df, part_keys): + predicate = np.ones(len(df), dtype=bool) + + to_drop = [] + for name, value in part_keys: + to_drop.append(name) + + # to avoid pandas warning + if isinstance(value, (datetime.date, datetime.datetime)): + value = pd.Timestamp(value) + + predicate &= df[name] == value + + return df[predicate].drop(to_drop, axis=1) + + +@pytest.mark.pandas +def test_filter_before_validate_schema(tempdir): + # ARROW-4076 apply filter before schema validation + # to avoid checking unneeded schemas + + # create partitioned dataset with mismatching schemas which would + # otherwise raise if first validation all schemas + dir1 = tempdir / 'A=0' + dir1.mkdir() + table1 = pa.Table.from_pandas(pd.DataFrame({'B': [1, 2, 3]})) + pq.write_table(table1, dir1 / 'data.parquet') + + dir2 = tempdir / 'A=1' + dir2.mkdir() + table2 = pa.Table.from_pandas(pd.DataFrame({'B': ['a', 'b', 'c']})) + pq.write_table(table2, dir2 / 'data.parquet') + + # read single file using filter + table = pq.read_table(tempdir, filters=[[('A', '==', 0)]]) + assert table.column('B').equals(pa.chunked_array([[1, 2, 3]])) + + +@pytest.mark.pandas +def test_read_multiple_files(tempdir): + nfiles = 10 + size = 5 + + dirpath = tempdir / guid() + dirpath.mkdir() + + test_data = [] + paths = [] + for i in range(nfiles): + df = _test_dataframe(size, seed=i) + + # Hack so that we don't have a dtype cast in v1 files + df['uint32'] = df['uint32'].astype(np.int64) + + path = dirpath / '{}.parquet'.format(i) + + table = pa.Table.from_pandas(df) + _write_table(table, path) + + test_data.append(table) + paths.append(path) + + # Write a _SUCCESS.crc file + (dirpath / '_SUCCESS.crc').touch() + + def read_multiple_files(paths, columns=None, use_threads=True, **kwargs): + dataset = pq.ParquetDataset(paths, **kwargs) + return dataset.read(columns=columns, use_threads=use_threads) + + result = read_multiple_files(paths) + expected = pa.concat_tables(test_data) + + assert result.equals(expected) + + # Read column subset + to_read = [0, 2, 6, result.num_columns - 1] + + col_names = [result.field(i).name for i in to_read] + out = pq.read_table(dirpath, columns=col_names) + expected = pa.Table.from_arrays([result.column(i) for i in to_read], + names=col_names, + metadata=result.schema.metadata) + assert out.equals(expected) + + # Read with multiple threads + pq.read_table(dirpath, use_threads=True) + + # Test failure modes with non-uniform metadata + bad_apple = _test_dataframe(size, seed=i).iloc[:, :4] + bad_apple_path = tempdir / '{}.parquet'.format(guid()) + + t = pa.Table.from_pandas(bad_apple) + _write_table(t, bad_apple_path) + + # TODO(dataset) Dataset API skips bad files + + # bad_meta = pq.read_metadata(bad_apple_path) + + # with pytest.raises(ValueError): + # read_multiple_files(paths + [bad_apple_path]) + + # with pytest.raises(ValueError): + # read_multiple_files(paths, metadata=bad_meta) + + # mixed_paths = [bad_apple_path, paths[0]] + + # with pytest.raises(ValueError): + # read_multiple_files(mixed_paths) + + +@pytest.mark.pandas +def test_dataset_read_pandas(tempdir): + nfiles = 5 + size = 5 + + dirpath = tempdir / guid() + dirpath.mkdir() + + test_data = [] + frames = [] + paths = [] + for i in range(nfiles): + df = _test_dataframe(size, seed=i) + df.index = np.arange(i * size, (i + 1) * size) + df.index.name = 'index' + + path = dirpath / '{}.parquet'.format(i) + + table = pa.Table.from_pandas(df) + _write_table(table, path) + test_data.append(table) + frames.append(df) + paths.append(path) + + dataset = pq.ParquetDataset(dirpath) + columns = ['uint8', 'strings'] + result = dataset.read_pandas(columns=columns).to_pandas() + expected = pd.concat([x[columns] for x in frames]) + + tm.assert_frame_equal(result, expected) + + # also be able to pass the columns as a set (ARROW-12314) + result = dataset.read_pandas(columns=set(columns)).to_pandas() + assert result.shape == expected.shape + # column order can be different because of using a set + tm.assert_frame_equal(result.reindex(columns=expected.columns), expected) + + +@pytest.mark.pandas +def test_dataset_memory_map(tempdir): + # ARROW-2627: Check that we can use ParquetDataset with memory-mapping + dirpath = tempdir / guid() + dirpath.mkdir() + + df = _test_dataframe(10, seed=0) + path = dirpath / '{}.parquet'.format(0) + table = pa.Table.from_pandas(df) + _write_table(table, path, version='2.6') + + dataset = pq.ParquetDataset( + dirpath, memory_map=True) + assert dataset.read().equals(table) + + +@pytest.mark.pandas +def test_dataset_enable_buffered_stream(tempdir): + dirpath = tempdir / guid() + dirpath.mkdir() + + df = _test_dataframe(10, seed=0) + path = dirpath / '{}.parquet'.format(0) + table = pa.Table.from_pandas(df) + _write_table(table, path, version='2.6') + + with pytest.raises(ValueError): + pq.ParquetDataset( + dirpath, buffer_size=-64) + + for buffer_size in [128, 1024]: + dataset = pq.ParquetDataset( + dirpath, buffer_size=buffer_size) + assert dataset.read().equals(table) + + +@pytest.mark.pandas +def test_dataset_enable_pre_buffer(tempdir): + dirpath = tempdir / guid() + dirpath.mkdir() + + df = _test_dataframe(10, seed=0) + path = dirpath / '{}.parquet'.format(0) + table = pa.Table.from_pandas(df) + _write_table(table, path, version='2.6') + + for pre_buffer in (True, False): + dataset = pq.ParquetDataset( + dirpath, pre_buffer=pre_buffer) + assert dataset.read().equals(table) + actual = pq.read_table(dirpath, pre_buffer=pre_buffer) + assert actual.equals(table) + + +def _make_example_multifile_dataset(base_path, nfiles=10, file_nrows=5): + test_data = [] + paths = [] + for i in range(nfiles): + df = _test_dataframe(file_nrows, seed=i) + path = base_path / '{}.parquet'.format(i) + + test_data.append(_write_table(df, path)) + paths.append(path) + return paths + + +def _assert_dataset_paths(dataset, paths): + paths = [str(path.as_posix()) for path in paths] + assert set(paths) == set(dataset.files) + + +@pytest.mark.pandas +@pytest.mark.parametrize('dir_prefix', ['_', '.']) +def test_ignore_private_directories(tempdir, dir_prefix): + dirpath = tempdir / guid() + dirpath.mkdir() + + paths = _make_example_multifile_dataset(dirpath, nfiles=10, + file_nrows=5) + + # private directory + (dirpath / '{}staging'.format(dir_prefix)).mkdir() + + dataset = pq.ParquetDataset(dirpath) + + _assert_dataset_paths(dataset, paths) + + +@pytest.mark.pandas +def test_ignore_hidden_files_dot(tempdir): + dirpath = tempdir / guid() + dirpath.mkdir() + + paths = _make_example_multifile_dataset(dirpath, nfiles=10, + file_nrows=5) + + with (dirpath / '.DS_Store').open('wb') as f: + f.write(b'gibberish') + + with (dirpath / '.private').open('wb') as f: + f.write(b'gibberish') + + dataset = pq.ParquetDataset(dirpath) + + _assert_dataset_paths(dataset, paths) + + +@pytest.mark.pandas +def test_ignore_hidden_files_underscore(tempdir): + dirpath = tempdir / guid() + dirpath.mkdir() + + paths = _make_example_multifile_dataset(dirpath, nfiles=10, + file_nrows=5) + + with (dirpath / '_committed_123').open('wb') as f: + f.write(b'abcd') + + with (dirpath / '_started_321').open('wb') as f: + f.write(b'abcd') + + dataset = pq.ParquetDataset(dirpath) + + _assert_dataset_paths(dataset, paths) + + +@pytest.mark.pandas +@pytest.mark.parametrize('dir_prefix', ['_', '.']) +def test_ignore_no_private_directories_in_base_path(tempdir, dir_prefix): + # ARROW-8427 - don't ignore explicitly listed files if parent directory + # is a private directory + dirpath = tempdir / "{0}data".format(dir_prefix) / guid() + dirpath.mkdir(parents=True) + + paths = _make_example_multifile_dataset(dirpath, nfiles=10, + file_nrows=5) + + dataset = pq.ParquetDataset(paths) + _assert_dataset_paths(dataset, paths) + + # ARROW-9644 - don't ignore full directory with underscore in base path + dataset = pq.ParquetDataset(dirpath) + _assert_dataset_paths(dataset, paths) + + +def test_ignore_custom_prefixes(tempdir): + # ARROW-9573 - allow override of default ignore_prefixes + part = ["xxx"] * 3 + ["yyy"] * 3 + table = pa.table([ + pa.array(range(len(part))), + pa.array(part).dictionary_encode(), + ], names=['index', '_part']) + + pq.write_to_dataset(table, str(tempdir), partition_cols=['_part']) + + private_duplicate = tempdir / '_private_duplicate' + private_duplicate.mkdir() + pq.write_to_dataset(table, str(private_duplicate), + partition_cols=['_part']) + + read = pq.read_table( + tempdir, ignore_prefixes=['_private']) + + assert read.equals(table) + + +def test_empty_directory(tempdir): + # ARROW-5310 + empty_dir = tempdir / 'dataset' + empty_dir.mkdir() + + dataset = pq.ParquetDataset(empty_dir) + result = dataset.read() + assert result.num_rows == 0 + assert result.num_columns == 0 + + +def _test_write_to_dataset_with_partitions(base_path, + filesystem=None, + schema=None, + index_name=None): + import pandas as pd + import pandas.testing as tm + + import pyarrow.parquet as pq + + # ARROW-1400 + output_df = pd.DataFrame({ + 'group1': list('aaabbbbccc'), + 'group2': list('eefeffgeee'), + 'num': list(range(10)), + 'nan': [np.nan] * 10, + 'date': np.arange('2017-01-01', '2017-01-11', dtype='datetime64[D]').astype( + 'datetime64[ns]') + }) + cols = output_df.columns.tolist() + partition_by = ['group1', 'group2'] + output_table = pa.Table.from_pandas(output_df, schema=schema, safe=False, + preserve_index=False) + pq.write_to_dataset(output_table, base_path, partition_by, + filesystem=filesystem) + + metadata_path = os.path.join(str(base_path), '_common_metadata') + + if filesystem is not None: + with filesystem.open(metadata_path, 'wb') as f: + pq.write_metadata(output_table.schema, f) + else: + pq.write_metadata(output_table.schema, metadata_path) + + dataset = pq.ParquetDataset(base_path, + filesystem=filesystem) + # ARROW-2209: Ensure the dataset schema also includes the partition columns + # NB schema property is an arrow and not parquet schema + dataset_cols = set(dataset.schema.names) + + assert dataset_cols == set(output_table.schema.names) + + input_table = dataset.read() + input_df = input_table.to_pandas() + + # Read data back in and compare with original DataFrame + # Partitioned columns added to the end of the DataFrame when read + input_df_cols = input_df.columns.tolist() + assert partition_by == input_df_cols[-1 * len(partition_by):] + + input_df = input_df[cols] + # Partitioned columns become 'categorical' dtypes + for col in partition_by: + output_df[col] = output_df[col].astype('category') + + if schema: + expected_date_type = schema.field('date').type.to_pandas_dtype() + output_df["date"] = output_df["date"].astype(expected_date_type) + + tm.assert_frame_equal(output_df, input_df) + + +def _test_write_to_dataset_no_partitions(base_path, + filesystem=None): + import pandas as pd + + import pyarrow.parquet as pq + + # ARROW-1400 + output_df = pd.DataFrame({ + 'group1': list('aaabbbbccc'), + 'group2': list('eefeffgeee'), + 'num': list(range(10)), + 'date': np.arange('2017-01-01', '2017-01-11', dtype='datetime64[D]').astype( + 'datetime64[ns]') + }) + cols = output_df.columns.tolist() + output_table = pa.Table.from_pandas(output_df) + + if filesystem is None: + filesystem = LocalFileSystem() + elif not isinstance(filesystem, FileSystem): + filesystem = PyFileSystem(FSSpecHandler(filesystem)) + + # Without partitions, append files to root_path + n = 5 + for i in range(n): + pq.write_to_dataset(output_table, base_path, + filesystem=filesystem) + + selector = FileSelector(str(base_path), allow_not_found=False, + recursive=True) + + infos = filesystem.get_file_info(selector) + output_files = [info for info in infos if info.path.endswith(".parquet")] + assert len(output_files) == n + + # Deduplicated incoming DataFrame should match + # original outgoing Dataframe + input_table = pq.ParquetDataset( + base_path, filesystem=filesystem + ).read() + input_df = input_table.to_pandas() + input_df = input_df.drop_duplicates() + input_df = input_df[cols] + tm.assert_frame_equal(output_df, input_df) + + +@pytest.mark.pandas +def test_write_to_dataset_with_partitions(tempdir): + _test_write_to_dataset_with_partitions(str(tempdir)) + + +@pytest.mark.pandas +def test_write_to_dataset_with_partitions_and_schema(tempdir): + schema = pa.schema([pa.field('group1', type=pa.string()), + pa.field('group2', type=pa.string()), + pa.field('num', type=pa.int64()), + pa.field('nan', type=pa.int32()), + pa.field('date', type=pa.timestamp(unit='us'))]) + _test_write_to_dataset_with_partitions( + str(tempdir), schema=schema) + + +@pytest.mark.pandas +def test_write_to_dataset_with_partitions_and_index_name(tempdir): + _test_write_to_dataset_with_partitions( + str(tempdir), index_name='index_name') + + +@pytest.mark.pandas +def test_write_to_dataset_no_partitions(tempdir): + _test_write_to_dataset_no_partitions(str(tempdir)) + + +@pytest.mark.pandas +def test_write_to_dataset_pathlib(tempdir): + _test_write_to_dataset_with_partitions(tempdir / "test1") + _test_write_to_dataset_no_partitions(tempdir / "test2") + + +@pytest.mark.pandas +@pytest.mark.s3 +def test_write_to_dataset_pathlib_nonlocal(tempdir, s3_example_s3fs): + # pathlib paths are only accepted for local files + fs, _ = s3_example_s3fs + + with pytest.raises(TypeError, match="path-like objects are only allowed"): + _test_write_to_dataset_with_partitions( + tempdir / "test1", filesystem=fs) + + with pytest.raises(TypeError, match="path-like objects are only allowed"): + _test_write_to_dataset_no_partitions( + tempdir / "test2", filesystem=fs) + + +@pytest.mark.pandas +@pytest.mark.s3 +def test_write_to_dataset_with_partitions_s3fs(s3_example_s3fs): + fs, path = s3_example_s3fs + + _test_write_to_dataset_with_partitions( + path, filesystem=fs) + + +@pytest.mark.pandas +@pytest.mark.s3 +def test_write_to_dataset_no_partitions_s3fs(s3_example_s3fs): + fs, path = s3_example_s3fs + + _test_write_to_dataset_no_partitions( + path, filesystem=fs) + + +@pytest.mark.pandas +def test_write_to_dataset_filesystem(tempdir): + df = pd.DataFrame({'A': [1, 2, 3]}) + table = pa.Table.from_pandas(df) + path = str(tempdir) + + pq.write_to_dataset(table, path, filesystem=LocalFileSystem()) + result = pq.read_table(path) + assert result.equals(table) + + +def _make_dataset_for_pickling(tempdir, N=100): + path = tempdir / 'data.parquet' + local = LocalFileSystem() + + df = pd.DataFrame({ + 'index': np.arange(N), + 'values': np.random.randn(N) + }, columns=['index', 'values']) + table = pa.Table.from_pandas(df) + + num_groups = 3 + with pq.ParquetWriter(path, table.schema) as writer: + for i in range(num_groups): + writer.write_table(table) + + reader = pq.ParquetFile(path) + assert reader.metadata.num_row_groups == num_groups + + metadata_path = tempdir / '_metadata' + with local.open_output_stream(str(metadata_path)) as f: + pq.write_metadata(table.schema, f) + + dataset = pq.ParquetDataset( + tempdir, filesystem=local) + + return dataset + + +@pytest.mark.pandas +def test_pickle_dataset(tempdir, pickle_module): + def is_pickleable(obj): + return obj == pickle_module.loads(pickle_module.dumps(obj)) + + dataset = _make_dataset_for_pickling(tempdir) + assert is_pickleable(dataset) + + +@pytest.mark.pandas +def test_partitioned_dataset(tempdir): + # ARROW-3208: Segmentation fault when reading a Parquet partitioned dataset + # to a Parquet file + path = tempdir / "ARROW-3208" + df = pd.DataFrame({ + 'one': [-1, 10, 2.5, 100, 1000, 1, 29.2], + 'two': [-1, 10, 2, 100, 1000, 1, 11], + 'three': [0, 0, 0, 0, 0, 0, 0] + }) + table = pa.Table.from_pandas(df) + pq.write_to_dataset(table, root_path=str(path), + partition_cols=['one', 'two']) + table = pq.ParquetDataset(path).read() + pq.write_table(table, path / "output.parquet") + + +def test_dataset_read_dictionary(tempdir): + path = tempdir / "ARROW-3325-dataset" + t1 = pa.table([[util.rands(10) for i in range(5)] * 10], names=['f0']) + t2 = pa.table([[util.rands(10) for i in range(5)] * 10], names=['f0']) + pq.write_to_dataset(t1, root_path=str(path)) + pq.write_to_dataset(t2, root_path=str(path)) + + result = pq.ParquetDataset( + path, read_dictionary=['f0']).read() + + # The order of the chunks is non-deterministic + ex_chunks = [t1[0].chunk(0).dictionary_encode(), + t2[0].chunk(0).dictionary_encode()] + + assert result[0].num_chunks == 2 + c0, c1 = result[0].chunk(0), result[0].chunk(1) + if c0.equals(ex_chunks[0]): + assert c1.equals(ex_chunks[1]) + else: + assert c0.equals(ex_chunks[1]) + assert c1.equals(ex_chunks[0]) + + +def test_read_table_schema(tempdir): + # test that schema keyword is passed through in read_table + table = pa.table({'a': pa.array([1, 2, 3], pa.int32())}) + pq.write_table(table, tempdir / "data1.parquet") + pq.write_table(table, tempdir / "data2.parquet") + + schema = pa.schema([('a', 'int64')]) + + # reading single file (which is special cased in the code) + result = pq.read_table(tempdir / "data1.parquet", schema=schema) + expected = pa.table({'a': [1, 2, 3]}, schema=schema) + assert result.equals(expected) + + # reading multiple fields + result = pq.read_table(tempdir, schema=schema) + expected = pa.table({'a': [1, 2, 3, 1, 2, 3]}, schema=schema) + assert result.equals(expected) + + result = pq.ParquetDataset(tempdir, schema=schema) + expected = pa.table({'a': [1, 2, 3, 1, 2, 3]}, schema=schema) + assert result.read().equals(expected) + + +def test_read_table_duplicate_column_selection(tempdir): + # test that duplicate column selection gives duplicate columns + table = pa.table({'a': pa.array([1, 2, 3], pa.int32()), + 'b': pa.array([1, 2, 3], pa.uint8())}) + pq.write_table(table, tempdir / "data.parquet") + + result = pq.read_table(tempdir / "data.parquet", columns=['a', 'a']) + expected_schema = pa.schema([('a', 'int32'), ('a', 'int32')]) + + assert result.column_names == ['a', 'a'] + assert result.schema == expected_schema + + +def test_dataset_partitioning(tempdir): + import pyarrow.dataset as ds + + # create small dataset with directory partitioning + root_path = tempdir / "test_partitioning" + (root_path / "2012" / "10" / "01").mkdir(parents=True) + + table = pa.table({'a': [1, 2, 3]}) + pq.write_table( + table, str(root_path / "2012" / "10" / "01" / "data.parquet")) + + # This works with new dataset API + + # read_table + part = ds.partitioning(field_names=["year", "month", "day"]) + result = pq.read_table( + str(root_path), partitioning=part) + assert result.column_names == ["a", "year", "month", "day"] + + result = pq.ParquetDataset( + str(root_path), partitioning=part).read() + assert result.column_names == ["a", "year", "month", "day"] + + +def test_parquet_dataset_new_filesystem(tempdir): + # Ensure we can pass new FileSystem object to ParquetDataset + table = pa.table({'a': [1, 2, 3]}) + pq.write_table(table, tempdir / 'data.parquet') + filesystem = SubTreeFileSystem(str(tempdir), LocalFileSystem()) + dataset = pq.ParquetDataset('.', filesystem=filesystem) + result = dataset.read() + assert result.equals(table) + + +def test_parquet_dataset_partitions_piece_path_with_fsspec(tempdir): + # ARROW-10462 ensure that on Windows we properly use posix-style paths + # as used by fsspec + fsspec = pytest.importorskip("fsspec") + filesystem = fsspec.filesystem('file') + table = pa.table({'a': [1, 2, 3]}) + pq.write_table(table, tempdir / 'data.parquet') + + # pass a posix-style path (using "/" also on Windows) + path = str(tempdir).replace("\\", "/") + dataset = pq.ParquetDataset( + path, filesystem=filesystem) + # ensure the piece path is also posix-style + expected = path + "/data.parquet" + assert dataset.fragments[0].path == expected + + +def test_parquet_write_to_dataset_exposed_keywords(tempdir): + table = pa.table({'a': [1, 2, 3]}) + path = tempdir / 'partitioning' + + paths_written = [] + + def file_visitor(written_file): + paths_written.append(written_file.path) + + basename_template = 'part-{i}.parquet' + + pq.write_to_dataset(table, path, partitioning=["a"], + file_visitor=file_visitor, + basename_template=basename_template) + + expected_paths = { + path / '1' / 'part-0.parquet', + path / '2' / 'part-0.parquet', + path / '3' / 'part-0.parquet' + } + paths_written_set = set(map(pathlib.Path, paths_written)) + assert paths_written_set == expected_paths + + +@pytest.mark.parametrize("write_dataset_kwarg", ( + ("create_dir", True), + ("create_dir", False), +)) +def test_write_to_dataset_kwargs_passed(tempdir, write_dataset_kwarg): + """Verify kwargs in pq.write_to_dataset are passed onto ds.write_dataset""" + import pyarrow.dataset as ds + + table = pa.table({"a": [1, 2, 3]}) + path = tempdir / 'out.parquet' + + signature = inspect.signature(ds.write_dataset) + key, arg = write_dataset_kwarg + + # kwarg not in pq.write_to_dataset, but will be passed to ds.write_dataset + assert key not in inspect.signature(pq.write_to_dataset).parameters + assert key in signature.parameters + + with mock.patch.object(ds, "write_dataset", autospec=True)\ + as mock_write_dataset: + pq.write_to_dataset(table, path, **{key: arg}) + _name, _args, kwargs = mock_write_dataset.mock_calls[0] + assert kwargs[key] == arg + + +@pytest.mark.pandas +def test_write_to_dataset_category_observed(tempdir): + # if we partition on a categorical variable with "unobserved" categories + # (values present in the dictionary, but not in the actual data) + # ensure those are not creating empty files/directories + df = pd.DataFrame({ + "cat": pd.Categorical(["a", "b", "a"], categories=["a", "b", "c"]), + "col": [1, 2, 3] + }) + table = pa.table(df) + path = tempdir / "dataset" + pq.write_to_dataset( + table, tempdir / "dataset", partition_cols=["cat"] + ) + subdirs = [f.name for f in path.iterdir() if f.is_dir()] + assert len(subdirs) == 2 + assert "cat=c" not in subdirs diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_encryption.py b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_encryption.py new file mode 100644 index 0000000000000000000000000000000000000000..ff388ef5069974d1787b7a94ba7303afed007482 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_encryption.py @@ -0,0 +1,572 @@ +# 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. +import pytest +from datetime import timedelta + +import pyarrow as pa +try: + import pyarrow.parquet as pq + import pyarrow.parquet.encryption as pe +except ImportError: + pq = None + pe = None +else: + from pyarrow.tests.parquet.encryption import ( + InMemoryKmsClient, verify_file_encrypted) + + +PARQUET_NAME = 'encrypted_table.in_mem.parquet' +FOOTER_KEY = b"0123456789112345" +FOOTER_KEY_NAME = "footer_key" +COL_KEY = b"1234567890123450" +COL_KEY_NAME = "col_key" + + +# Marks all of the tests in this module +# Ignore these with pytest ... -m 'not parquet_encryption' +# Ignore these with pytest ... -m 'not parquet' +pytestmark = [ + pytest.mark.parquet_encryption, + pytest.mark.parquet +] + + +@pytest.fixture(scope='module') +def data_table(): + data_table = pa.Table.from_pydict({ + 'a': pa.array([1, 2, 3]), + 'b': pa.array(['a', 'b', 'c']), + 'c': pa.array(['x', 'y', 'z']) + }) + return data_table + + +@pytest.fixture(scope='module') +def basic_encryption_config(): + basic_encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={ + COL_KEY_NAME: ["a", "b"], + }) + return basic_encryption_config + + +def setup_encryption_environment(custom_kms_conf): + """ + Sets up and returns the KMS connection configuration and crypto factory + based on provided KMS configuration parameters. + """ + kms_connection_config = pe.KmsConnectionConfig(custom_kms_conf=custom_kms_conf) + + def kms_factory(kms_connection_configuration): + return InMemoryKmsClient(kms_connection_configuration) + + # Create our CryptoFactory + crypto_factory = pe.CryptoFactory(kms_factory) + + return kms_connection_config, crypto_factory + + +def write_encrypted_file(path, data_table, footer_key_name, col_key_name, + footer_key, col_key, encryption_config): + """ + Writes an encrypted parquet file based on the provided parameters. + """ + # Setup the custom KMS configuration with provided keys + custom_kms_conf = { + footer_key_name: footer_key.decode("UTF-8"), + col_key_name: col_key.decode("UTF-8"), + } + + # Setup encryption environment + kms_connection_config, crypto_factory = setup_encryption_environment( + custom_kms_conf) + + # Write the encrypted parquet file + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + return kms_connection_config, crypto_factory + + +def test_encrypted_parquet_write_read(tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, and then read it.""" + path = tempdir / PARQUET_NAME + + # Encrypt the footer with the footer key, + # encrypt column `a` and column `b` with another key, + # keep `c` plaintext + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={ + COL_KEY_NAME: ["a", "b"], + }, + encryption_algorithm="AES_GCM_V1", + cache_lifetime=timedelta(minutes=5.0), + data_key_length_bits=256) + + kms_connection_config, crypto_factory = write_encrypted_file( + path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, FOOTER_KEY, COL_KEY, + encryption_config) + + verify_file_encrypted(path) + + # Read with decryption properties + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + result_table = read_encrypted_parquet( + path, decryption_config, kms_connection_config, crypto_factory) + assert data_table.equals(result_table) + + +def write_encrypted_parquet(path, table, encryption_config, + kms_connection_config, crypto_factory): + file_encryption_properties = crypto_factory.file_encryption_properties( + kms_connection_config, encryption_config) + assert file_encryption_properties is not None + with pq.ParquetWriter( + path, table.schema, + encryption_properties=file_encryption_properties) as writer: + writer.write_table(table) + + +def read_encrypted_parquet(path, decryption_config, + kms_connection_config, crypto_factory): + file_decryption_properties = crypto_factory.file_decryption_properties( + kms_connection_config, decryption_config) + assert file_decryption_properties is not None + meta = pq.read_metadata( + path, decryption_properties=file_decryption_properties) + assert meta.num_columns == 3 + schema = pq.read_schema( + path, decryption_properties=file_decryption_properties) + assert len(schema.names) == 3 + + result = pq.ParquetFile( + path, decryption_properties=file_decryption_properties) + return result.read(use_threads=True) + + +def test_encrypted_parquet_write_read_wrong_key(tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, + and then read it using wrong keys.""" + path = tempdir / PARQUET_NAME + + # Encrypt the footer with the footer key, + # encrypt column `a` and column `b` with another key, + # keep `c` plaintext + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={ + COL_KEY_NAME: ["a", "b"], + }, + encryption_algorithm="AES_GCM_V1", + cache_lifetime=timedelta(minutes=5.0), + data_key_length_bits=256) + + write_encrypted_file(path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, + FOOTER_KEY, COL_KEY, encryption_config) + + verify_file_encrypted(path) + + wrong_kms_connection_config, wrong_crypto_factory = setup_encryption_environment({ + FOOTER_KEY_NAME: COL_KEY.decode("UTF-8"), # Intentionally wrong + COL_KEY_NAME: FOOTER_KEY.decode("UTF-8"), # Intentionally wrong + }) + + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + with pytest.raises(ValueError, match=r"Incorrect master key used"): + read_encrypted_parquet( + path, decryption_config, wrong_kms_connection_config, + wrong_crypto_factory) + + +def test_encrypted_parquet_read_no_decryption_config(tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, + but then try to read it without decryption properties.""" + test_encrypted_parquet_write_read(tempdir, data_table) + # Read without decryption properties + with pytest.raises(IOError, match=r"no decryption"): + pq.ParquetFile(tempdir / PARQUET_NAME).read() + + +def test_encrypted_parquet_read_metadata_no_decryption_config( + tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, + but then try to read its metadata without decryption properties.""" + test_encrypted_parquet_write_read(tempdir, data_table) + # Read metadata without decryption properties + with pytest.raises(IOError, match=r"no decryption"): + pq.read_metadata(tempdir / PARQUET_NAME) + + +def test_encrypted_parquet_read_schema_no_decryption_config( + tempdir, data_table): + """Write an encrypted parquet, verify it's encrypted, + but then try to read its schema without decryption properties.""" + test_encrypted_parquet_write_read(tempdir, data_table) + with pytest.raises(IOError, match=r"no decryption"): + pq.read_schema(tempdir / PARQUET_NAME) + + +def test_encrypted_parquet_write_no_col_key(tempdir, data_table): + """Write an encrypted parquet, but give only footer key, + without column key.""" + path = tempdir / 'encrypted_table_no_col_key.in_mem.parquet' + + # Encrypt the footer with the footer key + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME) + + with pytest.raises(OSError, + match="Either column_keys or uniform_encryption " + "must be set"): + # Write with encryption properties + write_encrypted_file(path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, + FOOTER_KEY, b"", encryption_config) + + +def test_encrypted_parquet_write_kms_error(tempdir, data_table, + basic_encryption_config): + """Write an encrypted parquet, but raise KeyError in KmsClient.""" + path = tempdir / 'encrypted_table_kms_error.in_mem.parquet' + encryption_config = basic_encryption_config + + # Empty master_keys_map + kms_connection_config = pe.KmsConnectionConfig() + + def kms_factory(kms_connection_configuration): + # Empty master keys map will cause KeyError to be raised + # on wrap/unwrap calls + return InMemoryKmsClient(kms_connection_configuration) + + crypto_factory = pe.CryptoFactory(kms_factory) + with pytest.raises(KeyError, match="footer_key"): + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + +def test_encrypted_parquet_write_kms_specific_error(tempdir, data_table, + basic_encryption_config): + """Write an encrypted parquet, but raise KeyError in KmsClient.""" + path = tempdir / 'encrypted_table_kms_error.in_mem.parquet' + encryption_config = basic_encryption_config + + # Empty master_keys_map + kms_connection_config = pe.KmsConnectionConfig() + + class ThrowingKmsClient(pe.KmsClient): + """A KmsClient implementation that throws exception in + wrap/unwrap calls + """ + + def __init__(self, config): + """Create an InMemoryKmsClient instance.""" + pe.KmsClient.__init__(self) + self.config = config + + def wrap_key(self, key_bytes, master_key_identifier): + raise ValueError("Cannot Wrap Key") + + def unwrap_key(self, wrapped_key, master_key_identifier): + raise ValueError("Cannot Unwrap Key") + + def kms_factory(kms_connection_configuration): + # Exception thrown in wrap/unwrap calls + return ThrowingKmsClient(kms_connection_configuration) + + crypto_factory = pe.CryptoFactory(kms_factory) + with pytest.raises(ValueError, match="Cannot Wrap Key"): + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + +def test_encrypted_parquet_write_kms_factory_error(tempdir, data_table, + basic_encryption_config): + """Write an encrypted parquet, but raise ValueError in kms_factory.""" + path = tempdir / 'encrypted_table_kms_factory_error.in_mem.parquet' + encryption_config = basic_encryption_config + + # Empty master_keys_map + kms_connection_config = pe.KmsConnectionConfig() + + def kms_factory(kms_connection_configuration): + raise ValueError('Cannot create KmsClient') + + crypto_factory = pe.CryptoFactory(kms_factory) + with pytest.raises(ValueError, + match="Cannot create KmsClient"): + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + +def test_encrypted_parquet_write_kms_factory_type_error( + tempdir, data_table, basic_encryption_config): + """Write an encrypted parquet, but use wrong KMS client type + that doesn't implement KmsClient.""" + path = tempdir / 'encrypted_table_kms_factory_error.in_mem.parquet' + encryption_config = basic_encryption_config + + # Empty master_keys_map + kms_connection_config = pe.KmsConnectionConfig() + + class WrongTypeKmsClient(): + """This is not an implementation of KmsClient. + """ + + def __init__(self, config): + self.master_keys_map = config.custom_kms_conf + + def wrap_key(self, key_bytes, master_key_identifier): + return None + + def unwrap_key(self, wrapped_key, master_key_identifier): + return None + + def kms_factory(kms_connection_configuration): + return WrongTypeKmsClient(kms_connection_configuration) + + crypto_factory = pe.CryptoFactory(kms_factory) + with pytest.raises(TypeError): + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + +def test_encrypted_parquet_encryption_configuration(): + def validate_encryption_configuration(encryption_config): + assert FOOTER_KEY_NAME == encryption_config.footer_key + assert ["a", "b"] == encryption_config.column_keys[COL_KEY_NAME] + assert "AES_GCM_CTR_V1" == encryption_config.encryption_algorithm + assert encryption_config.plaintext_footer + assert not encryption_config.double_wrapping + assert timedelta(minutes=10.0) == encryption_config.cache_lifetime + assert not encryption_config.internal_key_material + assert 192 == encryption_config.data_key_length_bits + + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={COL_KEY_NAME: ["a", "b"], }, + encryption_algorithm="AES_GCM_CTR_V1", + plaintext_footer=True, + double_wrapping=False, + cache_lifetime=timedelta(minutes=10.0), + internal_key_material=False, + data_key_length_bits=192, + ) + validate_encryption_configuration(encryption_config) + + encryption_config_1 = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME) + encryption_config_1.column_keys = {COL_KEY_NAME: ["a", "b"], } + encryption_config_1.encryption_algorithm = "AES_GCM_CTR_V1" + encryption_config_1.plaintext_footer = True + encryption_config_1.double_wrapping = False + encryption_config_1.cache_lifetime = timedelta(minutes=10.0) + encryption_config_1.internal_key_material = False + encryption_config_1.data_key_length_bits = 192 + validate_encryption_configuration(encryption_config_1) + + +def test_encrypted_parquet_decryption_configuration(): + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=10.0)) + assert timedelta(minutes=10.0) == decryption_config.cache_lifetime + + decryption_config_1 = pe.DecryptionConfiguration() + decryption_config_1.cache_lifetime = timedelta(minutes=10.0) + assert timedelta(minutes=10.0) == decryption_config_1.cache_lifetime + + +def test_encrypted_parquet_kms_configuration(): + def validate_kms_connection_config(kms_connection_config): + assert "Instance1" == kms_connection_config.kms_instance_id + assert "URL1" == kms_connection_config.kms_instance_url + assert "MyToken" == kms_connection_config.key_access_token + assert ({"key1": "key_material_1", "key2": "key_material_2"} == + kms_connection_config.custom_kms_conf) + + kms_connection_config = pe.KmsConnectionConfig( + kms_instance_id="Instance1", + kms_instance_url="URL1", + key_access_token="MyToken", + custom_kms_conf={ + "key1": "key_material_1", + "key2": "key_material_2", + }) + validate_kms_connection_config(kms_connection_config) + + kms_connection_config_1 = pe.KmsConnectionConfig() + kms_connection_config_1.kms_instance_id = "Instance1" + kms_connection_config_1.kms_instance_url = "URL1" + kms_connection_config_1.key_access_token = "MyToken" + kms_connection_config_1.custom_kms_conf = { + "key1": "key_material_1", + "key2": "key_material_2", + } + validate_kms_connection_config(kms_connection_config_1) + + +@pytest.mark.xfail(reason="Plaintext footer - reading plaintext column subset" + " reads encrypted columns too") +def test_encrypted_parquet_write_read_plain_footer_single_wrapping( + tempdir, data_table): + """Write an encrypted parquet, with plaintext footer + and with single wrapping, + verify it's encrypted, and then read plaintext columns.""" + path = tempdir / PARQUET_NAME + + # Encrypt the footer with the footer key, + # encrypt column `a` and column `b` with another key, + # keep `c` plaintext + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={ + COL_KEY_NAME: ["a", "b"], + }, + plaintext_footer=True, + double_wrapping=False) + + kms_connection_config = pe.KmsConnectionConfig( + custom_kms_conf={ + FOOTER_KEY_NAME: FOOTER_KEY.decode("UTF-8"), + COL_KEY_NAME: COL_KEY.decode("UTF-8"), + } + ) + + def kms_factory(kms_connection_configuration): + return InMemoryKmsClient(kms_connection_configuration) + + crypto_factory = pe.CryptoFactory(kms_factory) + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + # # Read without decryption properties only the plaintext column + # result = pq.ParquetFile(path) + # result_table = result.read(columns='c', use_threads=False) + # assert table.num_rows == result_table.num_rows + + +@pytest.mark.xfail(reason="External key material not supported yet") +def test_encrypted_parquet_write_external(tempdir, data_table): + """Write an encrypted parquet, with external key + material. + Currently it's not implemented, so should throw + an exception""" + path = tempdir / PARQUET_NAME + + # Encrypt the file with the footer key + encryption_config = pe.EncryptionConfiguration( + footer_key=FOOTER_KEY_NAME, + column_keys={}, + internal_key_material=False) + + kms_connection_config = pe.KmsConnectionConfig( + custom_kms_conf={FOOTER_KEY_NAME: FOOTER_KEY.decode("UTF-8")} + ) + + def kms_factory(kms_connection_configuration): + return InMemoryKmsClient(kms_connection_configuration) + + crypto_factory = pe.CryptoFactory(kms_factory) + # Write with encryption properties + write_encrypted_parquet(path, data_table, encryption_config, + kms_connection_config, crypto_factory) + + +def test_encrypted_parquet_loop(tempdir, data_table, basic_encryption_config): + """Write an encrypted parquet, verify it's encrypted, + and then read it multithreaded in a loop.""" + path = tempdir / PARQUET_NAME + + # Encrypt the footer with the footer key, + # encrypt column `a` and column `b` with another key, + # keep `c` plaintext, defined in basic_encryption_config + kms_connection_config, crypto_factory = write_encrypted_file( + path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, FOOTER_KEY, COL_KEY, + basic_encryption_config) + + verify_file_encrypted(path) + + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + + for i in range(50): + # Read with decryption properties + file_decryption_properties = crypto_factory.file_decryption_properties( + kms_connection_config, decryption_config) + assert file_decryption_properties is not None + + result = pq.ParquetFile( + path, decryption_properties=file_decryption_properties) + result_table = result.read(use_threads=True) + assert data_table.equals(result_table) + + +def test_read_with_deleted_crypto_factory(tempdir, data_table, basic_encryption_config): + """ + Test that decryption properties can be used if the crypto factory is no longer alive + """ + path = tempdir / PARQUET_NAME + kms_connection_config, crypto_factory = write_encrypted_file( + path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, FOOTER_KEY, COL_KEY, + basic_encryption_config) + verify_file_encrypted(path) + + # Create decryption properties and delete the crypto factory that created + # the properties afterwards. + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + file_decryption_properties = crypto_factory.file_decryption_properties( + kms_connection_config, decryption_config) + del crypto_factory + + result = pq.ParquetFile( + path, decryption_properties=file_decryption_properties) + result_table = result.read(use_threads=True) + assert data_table.equals(result_table) + + +def test_encrypted_parquet_read_table(tempdir, data_table, basic_encryption_config): + """Write an encrypted parquet then read it back using read_table.""" + path = tempdir / PARQUET_NAME + + # Write the encrypted parquet file using the utility function + kms_connection_config, crypto_factory = write_encrypted_file( + path, data_table, FOOTER_KEY_NAME, COL_KEY_NAME, FOOTER_KEY, COL_KEY, + basic_encryption_config) + + decryption_config = pe.DecryptionConfiguration( + cache_lifetime=timedelta(minutes=5.0)) + file_decryption_properties = crypto_factory.file_decryption_properties( + kms_connection_config, decryption_config) + + # Read the encrypted parquet file using read_table + result_table = pq.read_table(path, decryption_properties=file_decryption_properties) + + # Assert that the read table matches the original data + assert data_table.equals(result_table) + + # Read the encrypted parquet folder using read_table + result_table = pq.read_table( + tempdir, decryption_properties=file_decryption_properties) + assert data_table.equals(result_table) diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_parquet_writer.py b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_parquet_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..bc3714a6232b1a551676f2a8dd8571ed012cad6f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/tests/parquet/test_parquet_writer.py @@ -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. + +import pytest + +import pyarrow as pa +from pyarrow import fs + +try: + import pyarrow.parquet as pq + from pyarrow.tests.parquet.common import (_read_table, _test_dataframe, + _range_integers) +except ImportError: + pq = None + + +try: + import pandas as pd + import pandas.testing as tm + +except ImportError: + pd = tm = None + + +# Marks all of the tests in this module +# Ignore these with pytest ... -m 'not parquet' +pytestmark = pytest.mark.parquet + + +@pytest.mark.pandas +def test_parquet_incremental_file_build(tempdir): + df = _test_dataframe(100) + df['unique_id'] = 0 + + arrow_table = pa.Table.from_pandas(df, preserve_index=False) + out = pa.BufferOutputStream() + + writer = pq.ParquetWriter(out, arrow_table.schema, version='2.6') + + frames = [] + for i in range(10): + df['unique_id'] = i + arrow_table = pa.Table.from_pandas(df, preserve_index=False) + writer.write_table(arrow_table) + + frames.append(df.copy()) + + writer.close() + + buf = out.getvalue() + result = _read_table(pa.BufferReader(buf)) + + expected = pd.concat(frames, ignore_index=True) + tm.assert_frame_equal(result.to_pandas(), expected) + + +def test_validate_schema_write_table(tempdir): + # ARROW-2926 + simple_fields = [ + pa.field('POS', pa.uint32()), + pa.field('desc', pa.string()) + ] + + simple_schema = pa.schema(simple_fields) + + # simple_table schema does not match simple_schema + simple_from_array = [pa.array([1]), pa.array(['bla'])] + simple_table = pa.Table.from_arrays(simple_from_array, ['POS', 'desc']) + + path = tempdir / 'simple_validate_schema.parquet' + + with pq.ParquetWriter(path, simple_schema, + version='2.6', + compression='snappy', flavor='spark') as w: + with pytest.raises(ValueError): + w.write_table(simple_table) + + +def test_parquet_invalid_writer(tempdir): + # avoid segfaults with invalid construction + with pytest.raises(TypeError): + some_schema = pa.schema([pa.field("x", pa.int32())]) + pq.ParquetWriter(None, some_schema) + + with pytest.raises(TypeError): + pq.ParquetWriter(tempdir / "some_path", None) + + +@pytest.mark.pandas +def test_parquet_writer_context_obj(tempdir): + df = _test_dataframe(100) + df['unique_id'] = 0 + + arrow_table = pa.Table.from_pandas(df, preserve_index=False) + out = pa.BufferOutputStream() + + with pq.ParquetWriter(out, arrow_table.schema, version='2.6') as writer: + + frames = [] + for i in range(10): + df['unique_id'] = i + arrow_table = pa.Table.from_pandas(df, preserve_index=False) + writer.write_table(arrow_table) + + frames.append(df.copy()) + + buf = out.getvalue() + result = _read_table(pa.BufferReader(buf)) + + expected = pd.concat(frames, ignore_index=True) + tm.assert_frame_equal(result.to_pandas(), expected) + + +@pytest.mark.pandas +def test_parquet_writer_context_obj_with_exception(tempdir): + df = _test_dataframe(100) + df['unique_id'] = 0 + + arrow_table = pa.Table.from_pandas(df, preserve_index=False) + out = pa.BufferOutputStream() + error_text = 'Artificial Error' + + try: + with pq.ParquetWriter(out, + arrow_table.schema, + version='2.6') as writer: + + frames = [] + for i in range(10): + df['unique_id'] = i + arrow_table = pa.Table.from_pandas(df, preserve_index=False) + writer.write_table(arrow_table) + frames.append(df.copy()) + if i == 5: + raise ValueError(error_text) + except Exception as e: + assert str(e) == error_text + + buf = out.getvalue() + result = _read_table(pa.BufferReader(buf)) + + expected = pd.concat(frames, ignore_index=True) + tm.assert_frame_equal(result.to_pandas(), expected) + + +@pytest.mark.pandas +@pytest.mark.parametrize("filesystem", [ + None, + fs.LocalFileSystem(), +]) +def test_parquet_writer_write_wrappers(tempdir, filesystem): + df = _test_dataframe(100) + table = pa.Table.from_pandas(df, preserve_index=False) + batch = pa.RecordBatch.from_pandas(df, preserve_index=False) + path_table = str(tempdir / 'data_table.parquet') + path_batch = str(tempdir / 'data_batch.parquet') + + with pq.ParquetWriter( + path_table, table.schema, filesystem=filesystem, version='2.6' + ) as writer: + writer.write_table(table) + + result = _read_table(path_table).to_pandas() + tm.assert_frame_equal(result, df) + + with pq.ParquetWriter( + path_batch, table.schema, filesystem=filesystem, version='2.6' + ) as writer: + writer.write_batch(batch) + + result = _read_table(path_batch).to_pandas() + tm.assert_frame_equal(result, df) + + with pq.ParquetWriter( + path_table, table.schema, filesystem=filesystem, version='2.6' + ) as writer: + writer.write(table) + + result = _read_table(path_table).to_pandas() + tm.assert_frame_equal(result, df) + + with pq.ParquetWriter( + path_batch, table.schema, filesystem=filesystem, version='2.6' + ) as writer: + writer.write(batch) + + result = _read_table(path_batch).to_pandas() + tm.assert_frame_equal(result, df) + + +@pytest.mark.large_memory +@pytest.mark.pandas +def test_parquet_writer_chunk_size(tempdir): + default_chunk_size = 1024 * 1024 + abs_max_chunk_size = 64 * 1024 * 1024 + + def check_chunk_size(data_size, chunk_size, expect_num_chunks): + table = pa.Table.from_arrays([ + _range_integers(data_size, 'b') + ], names=['x']) + if chunk_size is None: + pq.write_table(table, tempdir / 'test.parquet') + else: + pq.write_table(table, tempdir / 'test.parquet', row_group_size=chunk_size) + metadata = pq.read_metadata(tempdir / 'test.parquet') + expected_chunk_size = default_chunk_size if chunk_size is None else chunk_size + assert metadata.num_row_groups == expect_num_chunks + latched_chunk_size = min(expected_chunk_size, abs_max_chunk_size) + # First chunks should be full size + for chunk_idx in range(expect_num_chunks - 1): + assert metadata.row_group(chunk_idx).num_rows == latched_chunk_size + # Last chunk may be smaller + remainder = data_size - (expected_chunk_size * (expect_num_chunks - 1)) + if remainder == 0: + assert metadata.row_group( + expect_num_chunks - 1).num_rows == latched_chunk_size + else: + assert metadata.row_group(expect_num_chunks - 1).num_rows == remainder + + check_chunk_size(default_chunk_size * 2, default_chunk_size - 100, 3) + check_chunk_size(default_chunk_size * 2, default_chunk_size, 2) + check_chunk_size(default_chunk_size * 2, default_chunk_size + 100, 2) + check_chunk_size(default_chunk_size + 100, default_chunk_size + 100, 1) + # Even though the chunk size requested is large enough it will be capped + # by the absolute max chunk size + check_chunk_size(abs_max_chunk_size * 2, abs_max_chunk_size * 2, 2) + + # These tests don't pass a chunk_size to write_table and so the chunk size + # should be default_chunk_size + check_chunk_size(default_chunk_size, None, 1) + check_chunk_size(default_chunk_size + 1, None, 2) + + +@pytest.mark.pandas +@pytest.mark.parametrize("filesystem", [ + None, + fs.LocalFileSystem(), +]) +def test_parquet_writer_filesystem_local(tempdir, filesystem): + df = _test_dataframe(100) + table = pa.Table.from_pandas(df, preserve_index=False) + path = str(tempdir / 'data.parquet') + + with pq.ParquetWriter( + path, table.schema, filesystem=filesystem, version='2.6' + ) as writer: + writer.write_table(table) + + result = _read_table(path).to_pandas() + tm.assert_frame_equal(result, df) + + +@pytest.mark.pandas +@pytest.mark.s3 +def test_parquet_writer_filesystem_s3(s3_example_fs): + df = _test_dataframe(100) + table = pa.Table.from_pandas(df, preserve_index=False) + + fs, uri, path = s3_example_fs + + with pq.ParquetWriter( + path, table.schema, filesystem=fs, version='2.6' + ) as writer: + writer.write_table(table) + + result = _read_table(uri).to_pandas() + tm.assert_frame_equal(result, df) + + +@pytest.mark.pandas +@pytest.mark.s3 +def test_parquet_writer_filesystem_s3_uri(s3_example_fs): + df = _test_dataframe(100) + table = pa.Table.from_pandas(df, preserve_index=False) + + fs, uri, path = s3_example_fs + + with pq.ParquetWriter(uri, table.schema, version='2.6') as writer: + writer.write_table(table) + + result = _read_table(path, filesystem=fs).to_pandas() + tm.assert_frame_equal(result, df) + + +@pytest.mark.pandas +@pytest.mark.s3 +def test_parquet_writer_filesystem_s3fs(s3_example_s3fs): + df = _test_dataframe(100) + table = pa.Table.from_pandas(df, preserve_index=False) + + fs, directory = s3_example_s3fs + path = directory + "/test.parquet" + + with pq.ParquetWriter( + path, table.schema, filesystem=fs, version='2.6' + ) as writer: + writer.write_table(table) + + result = _read_table(path, filesystem=fs).to_pandas() + tm.assert_frame_equal(result, df) + + +@pytest.mark.pandas +def test_parquet_writer_filesystem_buffer_raises(): + df = _test_dataframe(100) + table = pa.Table.from_pandas(df, preserve_index=False) + filesystem = fs.LocalFileSystem() + + # Should raise ValueError when filesystem is passed with file-like object + with pytest.raises(ValueError, match="specified path is file-like"): + pq.ParquetWriter( + pa.BufferOutputStream(), table.schema, filesystem=filesystem + ) + + +def test_parquet_writer_store_schema(tempdir): + table = pa.table({'a': [1, 2, 3]}) + + # default -> write schema information + path1 = tempdir / 'test_with_schema.parquet' + with pq.ParquetWriter(path1, table.schema) as writer: + writer.write_table(table) + + meta = pq.read_metadata(path1) + assert b'ARROW:schema' in meta.metadata + assert meta.metadata[b'ARROW:schema'] + + # disable adding schema information + path2 = tempdir / 'test_without_schema.parquet' + with pq.ParquetWriter(path2, table.schema, store_schema=False) as writer: + writer.write_table(table) + + meta = pq.read_metadata(path2) + assert meta.metadata is None + + +def test_parquet_writer_append_key_value_metadata(tempdir): + table = pa.Table.from_arrays([pa.array([], type='int32')], ['f0']) + path = tempdir / 'metadata.parquet' + + with pq.ParquetWriter(path, table.schema) as writer: + writer.write_table(table) + writer.add_key_value_metadata({'key1': '1', 'key2': 'x'}) + writer.add_key_value_metadata({'key2': '2', 'key3': '3'}) + reader = pq.ParquetFile(path) + metadata = reader.metadata.metadata + assert metadata[b'key1'] == b'1' + assert metadata[b'key2'] == b'2' + assert metadata[b'key3'] == b'3' diff --git a/parrot/lib/python3.10/site-packages/pyarrow/tests/test_io.py b/parrot/lib/python3.10/site-packages/pyarrow/tests/test_io.py new file mode 100644 index 0000000000000000000000000000000000000000..ef499a3a8d76c1a021ba95bc040eed6ab0bcd98c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pyarrow/tests/test_io.py @@ -0,0 +1,2196 @@ +# 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. + +import bz2 +from contextlib import contextmanager +from io import (BytesIO, StringIO, TextIOWrapper, BufferedIOBase, IOBase) +import itertools +import gc +import gzip +import math +import os +import pathlib +import pytest +import sys +import tempfile +import weakref + +import numpy as np + +from pyarrow.util import guid +from pyarrow import Codec +import pyarrow as pa + + +def check_large_seeks(file_factory, expected_error=None): + if sys.platform in ('win32', 'darwin', 'emscripten'): + pytest.skip("need sparse file support") + try: + filename = tempfile.mktemp(prefix='test_io') + with open(filename, 'wb') as f: + f.truncate(2 ** 32 + 10) + f.seek(2 ** 32 + 5) + f.write(b'mark\n') + if expected_error: + with expected_error: + file_factory(filename) + else: + with file_factory(filename) as f: + assert f.size() == 2 ** 32 + 10 + assert f.seek(2 ** 32 + 5) == 2 ** 32 + 5 + assert f.tell() == 2 ** 32 + 5 + assert f.read(5) == b'mark\n' + assert f.tell() == 2 ** 32 + 10 + finally: + os.unlink(filename) + + +@contextmanager +def assert_file_not_found(): + with pytest.raises(FileNotFoundError): + yield + + +# ---------------------------------------------------------------------- +# Python file-like objects + + +def test_python_file_write(): + buf = BytesIO() + + f = pa.PythonFile(buf) + + assert f.tell() == 0 + + s1 = b'enga\xc3\xb1ado' + s2 = b'foobar' + + f.write(s1) + assert f.tell() == len(s1) + + f.write(s2) + + expected = s1 + s2 + + result = buf.getvalue() + assert result == expected + + assert not f.closed + f.close() + assert f.closed + + with pytest.raises(TypeError, match="binary file expected"): + pa.PythonFile(StringIO()) + + +def test_python_file_read(): + data = b'some sample data' + + buf = BytesIO(data) + f = pa.PythonFile(buf, mode='r') + + assert f.size() == len(data) + + assert f.tell() == 0 + + assert f.read(4) == b'some' + assert f.tell() == 4 + + f.seek(0) + assert f.tell() == 0 + + f.seek(5) + assert f.tell() == 5 + + v = f.read(50) + assert v == b'sample data' + assert len(v) == 11 + + assert f.size() == len(data) + + assert not f.closed + f.close() + assert f.closed + + with pytest.raises(TypeError, match="binary file expected"): + pa.PythonFile(StringIO(), mode='r') + + +@pytest.mark.parametrize("nbytes", (-1, 0, 1, 5, 100)) +@pytest.mark.parametrize("file_offset", (-1, 0, 5, 100)) +def test_python_file_get_stream(nbytes, file_offset): + + data = b'data1data2data3data4data5' + + f = pa.PythonFile(BytesIO(data), mode='r') + + # negative nbytes or offsets don't make sense here, raise ValueError + if nbytes < 0 or file_offset < 0: + with pytest.raises(pa.ArrowInvalid, + match="should be a positive value"): + f.get_stream(file_offset=file_offset, nbytes=nbytes) + f.close() + return + else: + stream = f.get_stream(file_offset=file_offset, nbytes=nbytes) + + # Subsequent calls to 'read' should match behavior if same + # data passed to BytesIO where get_stream should handle if + # nbytes/file_offset results in no bytes b/c out of bounds. + start = min(file_offset, len(data)) + end = min(file_offset + nbytes, len(data)) + buf = BytesIO(data[start:end]) + + # read some chunks + assert stream.read(nbytes=4) == buf.read(4) + assert stream.read(nbytes=6) == buf.read(6) + + # Read to end of each stream + assert stream.read() == buf.read() + + # Try reading past the stream + n = len(data) * 2 + assert stream.read(n) == buf.read(n) + + # NativeFile[CInputStream] is not seekable + with pytest.raises(OSError, match="seekable"): + stream.seek(0) + + stream.close() + assert stream.closed + + +def test_python_file_read_at(): + data = b'some sample data' + + buf = BytesIO(data) + f = pa.PythonFile(buf, mode='r') + + # test simple read at + v = f.read_at(nbytes=5, offset=3) + assert v == b'e sam' + assert len(v) == 5 + + # test reading entire file when nbytes > len(file) + w = f.read_at(nbytes=50, offset=0) + assert w == data + assert len(w) == 16 + + +def test_python_file_readall(): + data = b'some sample data' + + buf = BytesIO(data) + with pa.PythonFile(buf, mode='r') as f: + assert f.readall() == data + + +def test_python_file_readinto(): + length = 10 + data = b'some sample data longer than 10' + dst_buf = bytearray(length) + src_buf = BytesIO(data) + + with pa.PythonFile(src_buf, mode='r') as f: + assert f.readinto(dst_buf) == 10 + + assert dst_buf[:length] == data[:length] + assert len(dst_buf) == length + + +def test_python_file_read_buffer(): + length = 10 + data = b'0123456798' + dst_buf = bytearray(data) + + class DuckReader: + def close(self): + pass + + @property + def closed(self): + return False + + def read_buffer(self, nbytes): + assert nbytes == length + return memoryview(dst_buf)[:nbytes] + + duck_reader = DuckReader() + with pa.PythonFile(duck_reader, mode='r') as f: + buf = f.read_buffer(length) + assert len(buf) == length + assert memoryview(buf).tobytes() == dst_buf[:length] + # buf should point to the same memory, so modifying it + memoryview(buf)[0] = ord(b'x') + # should modify the original + assert dst_buf[0] == ord(b'x') + + +def test_python_file_correct_abc(): + with pa.PythonFile(BytesIO(b''), mode='r') as f: + assert isinstance(f, BufferedIOBase) + assert isinstance(f, IOBase) + + +def test_python_file_iterable(): + data = b'''line1 + line2 + line3 + ''' + + buf = BytesIO(data) + buf2 = BytesIO(data) + + with pa.PythonFile(buf, mode='r') as f: + for read, expected in zip(f, buf2): + assert read == expected + + +def test_python_file_large_seeks(): + def factory(filename): + return pa.PythonFile(open(filename, 'rb')) + + check_large_seeks(factory) + + +def test_bytes_reader(): + # Like a BytesIO, but zero-copy underneath for C++ consumers + data = b'some sample data' + f = pa.BufferReader(data) + assert f.tell() == 0 + + assert f.size() == len(data) + + assert f.read(4) == b'some' + assert f.tell() == 4 + + f.seek(0) + assert f.tell() == 0 + + f.seek(0, 2) + assert f.tell() == len(data) + + f.seek(5) + assert f.tell() == 5 + + assert f.read(50) == b'sample data' + + assert not f.closed + f.close() + assert f.closed + + +def test_bytes_reader_non_bytes(): + with pytest.raises(TypeError): + pa.BufferReader('some sample data') + + +def test_bytes_reader_retains_parent_reference(): + import gc + + # ARROW-421 + def get_buffer(): + data = b'some sample data' * 1000 + reader = pa.BufferReader(data) + reader.seek(5) + return reader.read_buffer(6) + + buf = get_buffer() + gc.collect() + assert buf.to_pybytes() == b'sample' + assert buf.parent is not None + + +def test_python_file_implicit_mode(tmpdir): + path = os.path.join(str(tmpdir), 'foo.txt') + with open(path, 'wb') as f: + pf = pa.PythonFile(f) + assert pf.writable() + assert not pf.readable() + assert not pf.seekable() # PyOutputStream isn't seekable + f.write(b'foobar\n') + + with open(path, 'rb') as f: + pf = pa.PythonFile(f) + assert pf.readable() + assert not pf.writable() + assert pf.seekable() + assert pf.read() == b'foobar\n' + + bio = BytesIO() + pf = pa.PythonFile(bio) + assert pf.writable() + assert not pf.readable() + assert not pf.seekable() + pf.write(b'foobar\n') + assert bio.getvalue() == b'foobar\n' + + +def test_python_file_writelines(tmpdir): + lines = [b'line1\n', b'line2\n' b'line3'] + path = os.path.join(str(tmpdir), 'foo.txt') + with open(path, 'wb') as f: + try: + f = pa.PythonFile(f, mode='w') + assert f.writable() + f.writelines(lines) + finally: + f.close() + + with open(path, 'rb') as f: + try: + f = pa.PythonFile(f, mode='r') + assert f.readable() + assert f.read() == b''.join(lines) + finally: + f.close() + + +def test_python_file_closing(): + bio = BytesIO() + pf = pa.PythonFile(bio) + wr = weakref.ref(pf) + del pf + assert wr() is None # object was destroyed + assert not bio.closed + pf = pa.PythonFile(bio) + pf.close() + assert bio.closed + + +# ---------------------------------------------------------------------- +# Buffers + + +def check_buffer_pickling(buf, pickler): + # Check that buffer survives a pickle roundtrip + for protocol in range(0, pickler.HIGHEST_PROTOCOL + 1): + result = pickler.loads(pickler.dumps(buf, protocol=protocol)) + assert len(result) == len(buf) + assert memoryview(result) == memoryview(buf) + assert result.to_pybytes() == buf.to_pybytes() + assert result.is_mutable == buf.is_mutable + + +def test_buffer_bytes(pickle_module): + val = b'some data' + + buf = pa.py_buffer(val) + assert isinstance(buf, pa.Buffer) + assert not buf.is_mutable + assert buf.is_cpu + + result = buf.to_pybytes() + assert result == val + + check_buffer_pickling(buf, pickle_module) + + +def test_buffer_null_data(pickle_module): + null_buff = pa.foreign_buffer(address=0, size=0) + assert null_buff.to_pybytes() == b"" + assert null_buff.address == 0 + # ARROW-16048: we shouldn't expose a NULL address through the Python + # buffer protocol. + m = memoryview(null_buff) + assert m.tobytes() == b"" + assert pa.py_buffer(m).address != 0 + + check_buffer_pickling(null_buff, pickle_module) + + +def test_buffer_memoryview(pickle_module): + val = b'some data' + + buf = pa.py_buffer(val) + assert isinstance(buf, pa.Buffer) + assert not buf.is_mutable + assert buf.is_cpu + + result = memoryview(buf) + assert result == val + + check_buffer_pickling(buf, pickle_module) + + +def test_buffer_bytearray(pickle_module): + val = bytearray(b'some data') + + buf = pa.py_buffer(val) + assert isinstance(buf, pa.Buffer) + assert buf.is_mutable + assert buf.is_cpu + + result = bytearray(buf) + assert result == val + + check_buffer_pickling(buf, pickle_module) + + +def test_buffer_invalid(): + with pytest.raises(TypeError, + match="(bytes-like object|buffer interface)"): + pa.py_buffer(None) + + +def test_buffer_weakref(): + buf = pa.py_buffer(b'some data') + wr = weakref.ref(buf) + assert wr() is not None + del buf + assert wr() is None + + +@pytest.mark.parametrize('val, expected_hex_buffer', + [(b'check', b'636865636B'), + (b'\a0', b'0730'), + (b'', b'')]) +def test_buffer_hex(val, expected_hex_buffer): + buf = pa.py_buffer(val) + assert buf.hex() == expected_hex_buffer + + +def test_buffer_to_numpy(): + # Make sure creating a numpy array from an arrow buffer works + byte_array = bytearray(20) + byte_array[0] = 42 + buf = pa.py_buffer(byte_array) + array = np.frombuffer(buf, dtype="uint8") + assert array[0] == byte_array[0] + byte_array[0] += 1 + assert array[0] == byte_array[0] + assert array.base == buf + + +def test_buffer_from_numpy(): + # C-contiguous + arr = np.arange(12, dtype=np.int8).reshape((3, 4)) + buf = pa.py_buffer(arr) + assert buf.is_cpu + assert buf.is_mutable + assert buf.to_pybytes() == arr.tobytes() + # F-contiguous; note strides information is lost + buf = pa.py_buffer(arr.T) + assert buf.is_cpu + assert buf.is_mutable + assert buf.to_pybytes() == arr.tobytes() + # Non-contiguous + with pytest.raises(ValueError, match="not contiguous"): + buf = pa.py_buffer(arr.T[::2]) + + +def test_buffer_address(): + b1 = b'some data!' + b2 = bytearray(b1) + b3 = bytearray(b1) + + buf1 = pa.py_buffer(b1) + buf2 = pa.py_buffer(b1) + buf3 = pa.py_buffer(b2) + buf4 = pa.py_buffer(b3) + + assert buf1.address > 0 + assert buf1.address == buf2.address + assert buf3.address != buf2.address + assert buf4.address != buf3.address + + arr = np.arange(5) + buf = pa.py_buffer(arr) + assert buf.address == arr.ctypes.data + + +def test_buffer_equals(): + # Buffer.equals() returns true iff the buffers have the same contents + def eq(a, b): + assert a.equals(b) + assert a == b + assert not (a != b) + + def ne(a, b): + assert not a.equals(b) + assert not (a == b) + assert a != b + + b1 = b'some data!' + b2 = bytearray(b1) + b3 = bytearray(b1) + b3[0] = 42 + buf1 = pa.py_buffer(b1) + buf2 = pa.py_buffer(b2) + buf3 = pa.py_buffer(b2) + buf4 = pa.py_buffer(b3) + buf5 = pa.py_buffer(np.frombuffer(b2, dtype=np.int16)) + eq(buf1, buf1) + eq(buf1, buf2) + eq(buf2, buf3) + ne(buf2, buf4) + # Data type is indifferent + eq(buf2, buf5) + + +def test_buffer_eq_bytes(): + buf = pa.py_buffer(b'some data') + assert buf == b'some data' + assert buf == bytearray(b'some data') + assert buf != b'some dat1' + + with pytest.raises(TypeError): + buf == 'some data' + + +def test_buffer_getitem(): + data = bytearray(b'some data!') + buf = pa.py_buffer(data) + + n = len(data) + for ix in range(-n, n - 1): + assert buf[ix] == data[ix] + + with pytest.raises(IndexError): + buf[n] + + with pytest.raises(IndexError): + buf[-n - 1] + + +def test_buffer_slicing(): + data = b'some data!' + buf = pa.py_buffer(data) + + sliced = buf.slice(2) + expected = pa.py_buffer(b'me data!') + assert sliced.equals(expected) + + sliced2 = buf.slice(2, 4) + expected2 = pa.py_buffer(b'me d') + assert sliced2.equals(expected2) + + # 0 offset + assert buf.slice(0).equals(buf) + + # Slice past end of buffer + assert len(buf.slice(len(buf))) == 0 + + with pytest.raises(IndexError): + buf.slice(-1) + + with pytest.raises(IndexError): + buf.slice(len(buf) + 1) + assert buf[11:].to_pybytes() == b"" + + # Slice stop exceeds buffer length + with pytest.raises(IndexError): + buf.slice(1, len(buf)) + assert buf[1:11].to_pybytes() == buf.to_pybytes()[1:] + + # Negative length + with pytest.raises(IndexError): + buf.slice(1, -1) + + # Test slice notation + assert buf[2:].equals(buf.slice(2)) + assert buf[2:5].equals(buf.slice(2, 3)) + assert buf[-5:].equals(buf.slice(len(buf) - 5)) + assert buf[-5:-2].equals(buf.slice(len(buf) - 5, 3)) + + with pytest.raises(IndexError): + buf[::-1] + with pytest.raises(IndexError): + buf[::2] + + n = len(buf) + for start in range(-n * 2, n * 2): + for stop in range(-n * 2, n * 2): + assert buf[start:stop].to_pybytes() == buf.to_pybytes()[start:stop] + + +def test_buffer_hashing(): + # Buffers are unhashable + with pytest.raises(TypeError, match="unhashable"): + hash(pa.py_buffer(b'123')) + + +def test_buffer_protocol_respects_immutability(): + # ARROW-3228; NumPy's frombuffer ctor determines whether a buffer-like + # object is mutable by first attempting to get a mutable buffer using + # PyObject_FromBuffer. If that fails, it assumes that the object is + # immutable + a = b'12345' + arrow_ref = pa.py_buffer(a) + numpy_ref = np.frombuffer(arrow_ref, dtype=np.uint8) + assert not numpy_ref.flags.writeable + + +def test_foreign_buffer(): + obj = np.array([1, 2], dtype=np.int32) + addr = obj.__array_interface__["data"][0] + size = obj.nbytes + buf = pa.foreign_buffer(addr, size, obj) + wr = weakref.ref(obj) + del obj + assert np.frombuffer(buf, dtype=np.int32).tolist() == [1, 2] + assert wr() is not None + del buf + assert wr() is None + + +def test_allocate_buffer(): + buf = pa.allocate_buffer(100) + assert buf.size == 100 + assert buf.is_mutable + assert buf.parent is None + + bit = b'abcde' + writer = pa.FixedSizeBufferWriter(buf) + writer.write(bit) + + assert buf.to_pybytes()[:5] == bit + + +def test_allocate_buffer_resizable(): + buf = pa.allocate_buffer(100, resizable=True) + assert isinstance(buf, pa.ResizableBuffer) + + buf.resize(200) + assert buf.size == 200 + + +def test_non_cpu_buffer(pickle_module): + cuda = pytest.importorskip("pyarrow.cuda") + ctx = cuda.Context(0) + + data = np.array([b'testing']) + cuda_buf = ctx.buffer_from_data(data) + arr = pa.FixedSizeBinaryArray.from_buffers(pa.binary(7), 1, [None, cuda_buf]) + buf_on_gpu = arr.buffers()[1] + + assert buf_on_gpu.size == cuda_buf.size + assert buf_on_gpu.address == cuda_buf.address + assert buf_on_gpu.is_cpu == cuda_buf.is_cpu + assert buf_on_gpu.is_mutable + + repr1 = "" + assert repr1 in repr(buf_on_gpu) + assert repr2 in repr(buf_on_gpu) + + buf_on_gpu_sliced = buf_on_gpu.slice(2) + cuda_sliced = cuda.CudaBuffer.from_buffer(buf_on_gpu_sliced) + assert cuda_sliced.to_pybytes() == b'sting' + + buf_on_gpu_sliced = buf_on_gpu[2:4] + cuda_sliced = cuda.CudaBuffer.from_buffer(buf_on_gpu_sliced) + assert cuda_sliced.to_pybytes() == b'st' + + # Sliced buffers with same address + assert buf_on_gpu_sliced.equals(cuda_buf[2:4]) + + # Buffers on different devices + msg_device = "Device on which the data resides differs between buffers" + with pytest.raises(ValueError, match=msg_device): + buf_on_gpu.equals(pa.py_buffer(data)) + + msg = "Implemented only for data on CPU device" + # Buffers with different addresses + arr_short = np.array([b'sting']) + cuda_buf_short = ctx.buffer_from_data(arr_short) + with pytest.raises(NotImplementedError, match=msg): + buf_on_gpu_sliced.equals(cuda_buf_short) + arr_short = pa.FixedSizeBinaryArray.from_buffers( + pa.binary(5), 1, [None, cuda_buf_short] + ) + buf_on_gpu_short = arr_short.buffers()[1] + with pytest.raises(NotImplementedError, match=msg): + buf_on_gpu_sliced.equals(buf_on_gpu_short) + + with pytest.raises(NotImplementedError, match=msg): + buf_on_gpu.hex() + + with pytest.raises(NotImplementedError, match=msg): + cuda_buf.hex() + + with pytest.raises(NotImplementedError, match=msg): + buf_on_gpu[1] + + with pytest.raises(NotImplementedError, match=msg): + buf_on_gpu.to_pybytes() + + with pytest.raises(NotImplementedError, match=msg): + pickle_module.dumps(buf_on_gpu, protocol=4) + + with pytest.raises(NotImplementedError, match=msg): + pickle_module.dumps(cuda_buf, protocol=4) + + with pytest.raises(NotImplementedError, match=msg): + memoryview(buf_on_gpu) + + +def test_cache_options(): + opts1 = pa.CacheOptions() + opts2 = pa.CacheOptions(hole_size_limit=1024) + opts3 = pa.CacheOptions(hole_size_limit=4096, range_size_limit=8192) + opts4 = pa.CacheOptions(hole_size_limit=4096, + range_size_limit=8192, prefetch_limit=5) + opts5 = pa.CacheOptions(hole_size_limit=4096, + range_size_limit=8192, lazy=False) + opts6 = pa.CacheOptions.from_network_metrics(time_to_first_byte_millis=100, + transfer_bandwidth_mib_per_sec=200, + ideal_bandwidth_utilization_frac=0.9, + max_ideal_request_size_mib=64) + + assert opts1.hole_size_limit == 8192 + assert opts1.range_size_limit == 32 * 1024 * 1024 + assert opts1.lazy is True + assert opts1.prefetch_limit == 0 + + assert opts2.hole_size_limit == 1024 + assert opts2.range_size_limit == 32 * 1024 * 1024 + assert opts2.lazy is True + assert opts2.prefetch_limit == 0 + + assert opts3.hole_size_limit == 4096 + assert opts3.range_size_limit == 8192 + assert opts3.lazy is True + assert opts3.prefetch_limit == 0 + + assert opts4.hole_size_limit == 4096 + assert opts4.range_size_limit == 8192 + assert opts4.lazy is True + assert opts4.prefetch_limit == 5 + + assert opts5.hole_size_limit == 4096 + assert opts5.range_size_limit == 8192 + assert opts5.lazy is False + assert opts5.prefetch_limit == 0 + + assert opts6.lazy is False + + assert opts1 == opts1 + assert opts1 != opts2 + assert opts2 != opts3 + assert opts3 != opts4 + assert opts4 != opts5 + assert opts6 != opts1 + + +def test_cache_options_pickling(pickle_module): + options = [ + pa.CacheOptions(), + pa.CacheOptions(hole_size_limit=4096, range_size_limit=8192, + lazy=True, prefetch_limit=5), + ] + + for option in options: + assert pickle_module.loads(pickle_module.dumps(option)) == option + + +@pytest.mark.parametrize("compression", [ + pytest.param( + "bz2", marks=pytest.mark.xfail(raises=pa.lib.ArrowNotImplementedError) + ), + "brotli", + "gzip", + "lz4", + "zstd", + "snappy" +]) +def test_compress_decompress(compression): + if not Codec.is_available(compression): + pytest.skip("{} support is not built".format(compression)) + + INPUT_SIZE = 10000 + test_data = (np.random.randint(0, 255, size=INPUT_SIZE) + .astype(np.uint8) + .tobytes()) + test_buf = pa.py_buffer(test_data) + + compressed_buf = pa.compress(test_buf, codec=compression) + compressed_bytes = pa.compress(test_data, codec=compression, + asbytes=True) + + assert isinstance(compressed_bytes, bytes) + + decompressed_buf = pa.decompress(compressed_buf, INPUT_SIZE, + codec=compression) + decompressed_bytes = pa.decompress(compressed_bytes, INPUT_SIZE, + codec=compression, asbytes=True) + + assert isinstance(decompressed_bytes, bytes) + + assert decompressed_buf.equals(test_buf) + assert decompressed_bytes == test_data + + with pytest.raises(ValueError): + pa.decompress(compressed_bytes, codec=compression) + + +@pytest.mark.parametrize("compression", [ + pytest.param( + "bz2", marks=pytest.mark.xfail(raises=pa.lib.ArrowNotImplementedError) + ), + "brotli", + "gzip", + "lz4", + "zstd", + "snappy" +]) +def test_compression_level(compression): + if not Codec.is_available(compression): + pytest.skip("{} support is not built".format(compression)) + + codec = Codec(compression) + if codec.name == "snappy": + assert codec.compression_level is None + else: + assert isinstance(codec.compression_level, int) + + # These codecs do not support a compression level + no_level = ['snappy'] + if compression in no_level: + assert not Codec.supports_compression_level(compression) + with pytest.raises(ValueError): + Codec(compression, 0) + with pytest.raises(ValueError): + Codec.minimum_compression_level(compression) + with pytest.raises(ValueError): + Codec.maximum_compression_level(compression) + with pytest.raises(ValueError): + Codec.default_compression_level(compression) + return + + INPUT_SIZE = 10000 + test_data = (np.random.randint(0, 255, size=INPUT_SIZE) + .astype(np.uint8) + .tobytes()) + test_buf = pa.py_buffer(test_data) + + min_level = Codec.minimum_compression_level(compression) + max_level = Codec.maximum_compression_level(compression) + default_level = Codec.default_compression_level(compression) + + assert min_level < max_level + assert default_level >= min_level + assert default_level <= max_level + + for compression_level in range(min_level, max_level+1): + codec = Codec(compression, compression_level) + compressed_buf = codec.compress(test_buf) + compressed_bytes = codec.compress(test_data, asbytes=True) + assert isinstance(compressed_bytes, bytes) + decompressed_buf = codec.decompress(compressed_buf, INPUT_SIZE) + decompressed_bytes = codec.decompress(compressed_bytes, INPUT_SIZE, + asbytes=True) + + assert isinstance(decompressed_bytes, bytes) + + assert decompressed_buf.equals(test_buf) + assert decompressed_bytes == test_data + + with pytest.raises(ValueError): + codec.decompress(compressed_bytes) + + # The ability to set a seed this way is not present on older versions of + # numpy (currently in our python 3.6 CI build). Some inputs might just + # happen to compress the same between the two levels so using seeded + # random numbers is necessary to help get more reliable results + # + # The goal of this part is to ensure the compression_level is being + # passed down to the C++ layer, not to verify the compression algs + # themselves + if not hasattr(np.random, 'default_rng'): + pytest.skip('Requires newer version of numpy') + rng = np.random.default_rng(seed=42) + values = rng.integers(0, 100, 1000) + arr = pa.array(values) + hard_to_compress_buffer = arr.buffers()[1] + + weak_codec = Codec(compression, min_level) + weakly_compressed_buf = weak_codec.compress(hard_to_compress_buffer) + + strong_codec = Codec(compression, max_level) + strongly_compressed_buf = strong_codec.compress(hard_to_compress_buffer) + + assert len(weakly_compressed_buf) > len(strongly_compressed_buf) + + +def test_buffer_memoryview_is_immutable(): + val = b'some data' + + buf = pa.py_buffer(val) + assert not buf.is_mutable + assert isinstance(buf, pa.Buffer) + + result = memoryview(buf) + assert result.readonly + + with pytest.raises(TypeError) as exc: + result[0] = b'h' + assert 'cannot modify read-only' in str(exc.value) + + b = bytes(buf) + with pytest.raises(TypeError) as exc: + b[0] = b'h' + assert 'cannot modify read-only' in str(exc.value) + + +def test_uninitialized_buffer(): + # ARROW-2039: calling Buffer() directly creates an uninitialized object + # ARROW-2638: prevent calling extension class constructors directly + with pytest.raises(TypeError): + pa.Buffer() + + +def test_memory_output_stream(): + # 10 bytes + val = b'dataabcdef' + f = pa.BufferOutputStream() + + K = 1000 + for i in range(K): + f.write(val) + + buf = f.getvalue() + assert len(buf) == len(val) * K + assert buf.to_pybytes() == val * K + + +def test_inmemory_write_after_closed(): + f = pa.BufferOutputStream() + f.write(b'ok') + assert not f.closed + f.getvalue() + assert f.closed + + with pytest.raises(ValueError): + f.write(b'not ok') + + +def test_buffer_protocol_ref_counting(): + def make_buffer(bytes_obj): + return bytearray(pa.py_buffer(bytes_obj)) + + buf = make_buffer(b'foo') + gc.collect() + assert buf == b'foo' + + # ARROW-1053 + val = b'foo' + refcount_before = sys.getrefcount(val) + for i in range(10): + make_buffer(val) + gc.collect() + assert refcount_before == sys.getrefcount(val) + + +def test_nativefile_write_memoryview(): + f = pa.BufferOutputStream() + data = b'ok' + + arr = np.frombuffer(data, dtype='S1') + + f.write(arr) + f.write(bytearray(data)) + f.write(pa.py_buffer(data)) + with pytest.raises(TypeError): + f.write(data.decode('utf8')) + + buf = f.getvalue() + + assert buf.to_pybytes() == data * 3 + + +# ---------------------------------------------------------------------- +# Mock output stream + + +def test_mock_output_stream(): + # Make sure that the MockOutputStream and the BufferOutputStream record the + # same size + + # 10 bytes + val = b'dataabcdef' + + f1 = pa.MockOutputStream() + f2 = pa.BufferOutputStream() + + K = 1000 + for i in range(K): + f1.write(val) + f2.write(val) + + assert f1.size() == len(f2.getvalue()) + + # Do the same test with a table + record_batch = pa.RecordBatch.from_arrays([pa.array([1, 2, 3])], ['a']) + + f1 = pa.MockOutputStream() + f2 = pa.BufferOutputStream() + + stream_writer1 = pa.RecordBatchStreamWriter(f1, record_batch.schema) + stream_writer2 = pa.RecordBatchStreamWriter(f2, record_batch.schema) + + stream_writer1.write_batch(record_batch) + stream_writer2.write_batch(record_batch) + stream_writer1.close() + stream_writer2.close() + + assert f1.size() == len(f2.getvalue()) + + +# ---------------------------------------------------------------------- +# OS files and memory maps + + +@pytest.fixture +def sample_disk_data(request, tmpdir): + SIZE = 4096 + arr = np.random.randint(0, 256, size=SIZE).astype('u1') + data = arr.tobytes()[:SIZE] + + path = os.path.join(str(tmpdir), guid()) + + with open(path, 'wb') as f: + f.write(data) + + def teardown(): + _try_delete(path) + + request.addfinalizer(teardown) + return path, data + + +def _check_native_file_reader(FACTORY, sample_data, + allow_read_out_of_bounds=True): + path, data = sample_data + + f = FACTORY(path, mode='r') + + assert f.read(10) == data[:10] + assert f.read(0) == b'' + assert f.tell() == 10 + + assert f.read() == data[10:] + + assert f.size() == len(data) + + f.seek(0) + assert f.tell() == 0 + + # Seeking past end of file not supported in memory maps + if allow_read_out_of_bounds: + f.seek(len(data) + 1) + assert f.tell() == len(data) + 1 + assert f.read(5) == b'' + + # Test whence argument of seek, ARROW-1287 + assert f.seek(3) == 3 + assert f.seek(3, os.SEEK_CUR) == 6 + assert f.tell() == 6 + + ex_length = len(data) - 2 + assert f.seek(-2, os.SEEK_END) == ex_length + assert f.tell() == ex_length + + +def test_memory_map_reader(sample_disk_data): + _check_native_file_reader(pa.memory_map, sample_disk_data, + allow_read_out_of_bounds=False) + + +def test_memory_map_retain_buffer_reference(sample_disk_data): + path, data = sample_disk_data + + cases = [] + with pa.memory_map(path, 'rb') as f: + cases.append((f.read_buffer(100), data[:100])) + cases.append((f.read_buffer(100), data[100:200])) + cases.append((f.read_buffer(100), data[200:300])) + + # Call gc.collect() for good measure + gc.collect() + + for buf, expected in cases: + assert buf.to_pybytes() == expected + + +def test_os_file_reader(sample_disk_data): + _check_native_file_reader(pa.OSFile, sample_disk_data) + + +def test_os_file_large_seeks(): + check_large_seeks(pa.OSFile) + + +def _try_delete(path): + try: + os.remove(path) + except os.error: + pass + + +def test_memory_map_writer(tmpdir): + if sys.platform == "emscripten": + pytest.xfail("Multiple memory maps to same file don't work on emscripten") + SIZE = 4096 + arr = np.random.randint(0, 256, size=SIZE).astype('u1') + data = arr.tobytes()[:SIZE] + + path = os.path.join(str(tmpdir), guid()) + with open(path, 'wb') as f: + f.write(data) + + f = pa.memory_map(path, mode='r+b') + + f.seek(10) + f.write(b'peekaboo') + assert f.tell() == 18 + + f.seek(10) + assert f.read(8) == b'peekaboo' + + f2 = pa.memory_map(path, mode='r+b') + + f2.seek(10) + f2.write(b'booapeak') + f2.seek(10) + + f.seek(10) + assert f.read(8) == b'booapeak' + + # Does not truncate file + f3 = pa.memory_map(path, mode='w') + f3.write(b'foo') + + with pa.memory_map(path) as f4: + assert f4.size() == SIZE + + with pytest.raises(IOError): + f3.read(5) + + f.seek(0) + assert f.read(3) == b'foo' + + +def test_memory_map_resize(tmpdir): + SIZE = 4096 + arr = np.random.randint(0, 256, size=SIZE).astype(np.uint8) + data1 = arr.tobytes()[:(SIZE // 2)] + data2 = arr.tobytes()[(SIZE // 2):] + + path = os.path.join(str(tmpdir), guid()) + + mmap = pa.create_memory_map(path, SIZE / 2) + mmap.write(data1) + + mmap.resize(SIZE) + mmap.write(data2) + + mmap.close() + + with open(path, 'rb') as f: + assert f.read() == arr.tobytes() + + +def test_memory_zero_length(tmpdir): + path = os.path.join(str(tmpdir), guid()) + f = open(path, 'wb') + f.close() + with pa.memory_map(path, mode='r+b') as memory_map: + assert memory_map.size() == 0 + + +def test_memory_map_large_seeks(): + if sys.maxsize >= 2**32: + expected_error = None + else: + expected_error = pytest.raises( + pa.ArrowCapacityError, + match="Requested memory map length 4294967306 " + "does not fit in a C size_t") + check_large_seeks(pa.memory_map, expected_error=expected_error) + + +def test_memory_map_close_remove(tmpdir): + # ARROW-6740: should be able to delete closed memory-mapped file (Windows) + path = os.path.join(str(tmpdir), guid()) + mmap = pa.create_memory_map(path, 4096) + mmap.close() + assert mmap.closed + os.remove(path) # Shouldn't fail + + +def test_memory_map_deref_remove(tmpdir): + path = os.path.join(str(tmpdir), guid()) + pa.create_memory_map(path, 4096) + os.remove(path) # Shouldn't fail + + +def test_os_file_writer(tmpdir): + SIZE = 4096 + arr = np.random.randint(0, 256, size=SIZE).astype('u1') + data = arr.tobytes()[:SIZE] + + path = os.path.join(str(tmpdir), guid()) + with open(path, 'wb') as f: + f.write(data) + + # Truncates file + f2 = pa.OSFile(path, mode='w') + f2.write(b'foo') + + with pa.OSFile(path) as f3: + assert f3.size() == 3 + + with pytest.raises(IOError): + f2.read(5) + f2.close() + + # Append + with pa.OSFile(path, mode='ab') as f4: + f4.write(b'bar') + with pa.OSFile(path) as f5: + assert f5.size() == 6 # foo + bar + + +def test_native_file_write_reject_unicode(): + # ARROW-3227 + nf = pa.BufferOutputStream() + with pytest.raises(TypeError): + nf.write('foo') + + +def test_native_file_modes(tmpdir): + path = os.path.join(str(tmpdir), guid()) + with open(path, 'wb') as f: + f.write(b'foooo') + + with pa.OSFile(path, mode='r') as f: + assert f.mode == 'rb' + assert f.readable() + assert not f.writable() + assert f.seekable() + + with pa.OSFile(path, mode='rb') as f: + assert f.mode == 'rb' + assert f.readable() + assert not f.writable() + assert f.seekable() + + with pa.OSFile(path, mode='w') as f: + assert f.mode == 'wb' + assert not f.readable() + assert f.writable() + assert not f.seekable() + + with pa.OSFile(path, mode='wb') as f: + assert f.mode == 'wb' + assert not f.readable() + assert f.writable() + assert not f.seekable() + + with pa.OSFile(path, mode='ab') as f: + assert f.mode == 'ab' + assert not f.readable() + assert f.writable() + assert not f.seekable() + + with pa.OSFile(path, mode='a') as f: + assert f.mode == 'ab' + assert not f.readable() + assert f.writable() + assert not f.seekable() + + with open(path, 'wb') as f: + f.write(b'foooo') + + with pa.memory_map(path, 'r') as f: + assert f.mode == 'rb' + assert f.readable() + assert not f.writable() + assert f.seekable() + + with pa.memory_map(path, 'r+') as f: + assert f.mode == 'rb+' + assert f.readable() + assert f.writable() + assert f.seekable() + + with pa.memory_map(path, 'r+b') as f: + assert f.mode == 'rb+' + assert f.readable() + assert f.writable() + assert f.seekable() + + +@pytest.mark.xfail( + sys.platform == "emscripten", reason="umask doesn't work on Emscripten" +) +def test_native_file_permissions(tmpdir): + # ARROW-10124: permissions of created files should follow umask + cur_umask = os.umask(0o002) + os.umask(cur_umask) + + path = os.path.join(str(tmpdir), guid()) + with pa.OSFile(path, mode='w'): + pass + assert os.stat(path).st_mode & 0o777 == 0o666 & ~cur_umask + + path = os.path.join(str(tmpdir), guid()) + with pa.memory_map(path, 'w'): + pass + assert os.stat(path).st_mode & 0o777 == 0o666 & ~cur_umask + + +def test_native_file_raises_ValueError_after_close(tmpdir): + path = os.path.join(str(tmpdir), guid()) + with open(path, 'wb') as f: + f.write(b'foooo') + + with pa.OSFile(path, mode='rb') as os_file: + assert not os_file.closed + assert os_file.closed + + with pa.memory_map(path, mode='rb') as mmap_file: + assert not mmap_file.closed + assert mmap_file.closed + + files = [os_file, + mmap_file] + + methods = [('tell', ()), + ('seek', (0,)), + ('size', ()), + ('flush', ()), + ('readable', ()), + ('writable', ()), + ('seekable', ())] + + for f in files: + for method, args in methods: + with pytest.raises(ValueError): + getattr(f, method)(*args) + + +def test_native_file_TextIOWrapper(tmpdir): + data = ('foooo\n' + 'barrr\n' + 'bazzz\n') + + path = os.path.join(str(tmpdir), guid()) + with open(path, 'wb') as f: + f.write(data.encode('utf-8')) + + with TextIOWrapper(pa.OSFile(path, mode='rb')) as fil: + assert fil.readable() + res = fil.read() + assert res == data + assert fil.closed + + with TextIOWrapper(pa.OSFile(path, mode='rb')) as fil: + # Iteration works + lines = list(fil) + assert ''.join(lines) == data + + # Writing + path2 = os.path.join(str(tmpdir), guid()) + with TextIOWrapper(pa.OSFile(path2, mode='wb')) as fil: + assert fil.writable() + fil.write(data) + + with TextIOWrapper(pa.OSFile(path2, mode='rb')) as fil: + res = fil.read() + assert res == data + + +def test_native_file_TextIOWrapper_perf(tmpdir): + # ARROW-16272: TextIOWrapper.readline() shouldn't exhaust a large + # Arrow input stream. + data = b'foo\nquux\n' + path = str(tmpdir / 'largefile.txt') + with open(path, 'wb') as f: + f.write(data * 100_000) + + binary_file = pa.OSFile(path, mode='rb') + with TextIOWrapper(binary_file) as f: + assert binary_file.tell() == 0 + nbytes = 20_000 + lines = f.readlines(nbytes) + assert len(lines) == math.ceil(2 * nbytes / len(data)) + assert nbytes <= binary_file.tell() <= nbytes * 2 + + +def test_native_file_read1(tmpdir): + # ARROW-16272: read1() should not exhaust the input stream if there + # is a large amount of data remaining. + data = b'123\n' * 1_000_000 + path = str(tmpdir / 'largefile.txt') + with open(path, 'wb') as f: + f.write(data) + + chunks = [] + with pa.OSFile(path, mode='rb') as f: + while True: + b = f.read1() + assert len(b) < len(data) + chunks.append(b) + b = f.read1(30_000) + assert len(b) <= 30_000 + chunks.append(b) + if not b: + break + + assert b"".join(chunks) == data + + +@pytest.mark.pandas +def test_native_file_pandas_text_reader(tmpdir): + # ARROW-16272: Pandas' read_csv() should not exhaust an Arrow + # input stream when a small nrows is passed. + import pandas as pd + import pandas.testing as tm + data = b'a,b\n' * 10_000_000 + path = str(tmpdir / 'largefile.txt') + with open(path, 'wb') as f: + f.write(data) + + with pa.OSFile(path, mode='rb') as f: + df = pd.read_csv(f, nrows=10) + expected = pd.DataFrame({'a': ['a'] * 10, 'b': ['b'] * 10}) + tm.assert_frame_equal(df, expected) + # Some readahead occurred, but not up to the end of file + assert f.tell() <= 256 * 1024 + + +def test_native_file_open_error(): + with assert_file_not_found(): + pa.OSFile('non_existent_file', 'rb') + with assert_file_not_found(): + pa.memory_map('non_existent_file', 'rb') + + +# ---------------------------------------------------------------------- +# Buffered streams + +def test_buffered_input_stream(): + raw = pa.BufferReader(b"123456789") + f = pa.BufferedInputStream(raw, buffer_size=4) + assert f.read(2) == b"12" + assert raw.tell() == 4 + f.close() + assert f.closed + assert raw.closed + + +def test_buffered_input_stream_detach_seekable(): + # detach() to a seekable file (io::RandomAccessFile in C++) + f = pa.BufferedInputStream(pa.BufferReader(b"123456789"), buffer_size=4) + assert f.read(2) == b"12" + raw = f.detach() + assert f.closed + assert not raw.closed + assert raw.seekable() + assert raw.read(4) == b"5678" + raw.seek(2) + assert raw.read(4) == b"3456" + + +def test_buffered_input_stream_detach_non_seekable(): + # detach() to a non-seekable file (io::InputStream in C++) + f = pa.BufferedInputStream( + pa.BufferedInputStream(pa.BufferReader(b"123456789"), buffer_size=4), + buffer_size=4) + assert f.read(2) == b"12" + raw = f.detach() + assert f.closed + assert not raw.closed + assert not raw.seekable() + assert raw.read(4) == b"5678" + with pytest.raises(EnvironmentError): + raw.seek(2) + + +def test_buffered_output_stream(): + np_buf = np.zeros(100, dtype=np.int8) # zero-initialized buffer + buf = pa.py_buffer(np_buf) + + raw = pa.FixedSizeBufferWriter(buf) + f = pa.BufferedOutputStream(raw, buffer_size=4) + f.write(b"12") + assert np_buf[:4].tobytes() == b'\0\0\0\0' + f.flush() + assert np_buf[:4].tobytes() == b'12\0\0' + f.write(b"3456789") + f.close() + assert f.closed + assert raw.closed + assert np_buf[:10].tobytes() == b'123456789\0' + + +def test_buffered_output_stream_detach(): + np_buf = np.zeros(100, dtype=np.int8) # zero-initialized buffer + buf = pa.py_buffer(np_buf) + + f = pa.BufferedOutputStream(pa.FixedSizeBufferWriter(buf), buffer_size=4) + f.write(b"12") + assert np_buf[:4].tobytes() == b'\0\0\0\0' + raw = f.detach() + assert f.closed + assert not raw.closed + assert np_buf[:4].tobytes() == b'12\0\0' + + +# ---------------------------------------------------------------------- +# Compressed input and output streams + +def check_compressed_input(data, fn, compression): + raw = pa.OSFile(fn, mode="rb") + with pa.CompressedInputStream(raw, compression) as compressed: + assert not compressed.closed + assert compressed.readable() + assert not compressed.writable() + assert not compressed.seekable() + got = compressed.read() + assert got == data + assert compressed.closed + assert raw.closed + + # Same with read_buffer() + raw = pa.OSFile(fn, mode="rb") + with pa.CompressedInputStream(raw, compression) as compressed: + buf = compressed.read_buffer() + assert isinstance(buf, pa.Buffer) + assert buf.to_pybytes() == data + + +@pytest.mark.gzip +def test_compressed_input_gzip(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "compressed_input_test.gz") + with gzip.open(fn, "wb") as f: + f.write(data) + check_compressed_input(data, fn, "gzip") + + +def test_compressed_input_bz2(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "compressed_input_test.bz2") + with bz2.BZ2File(fn, "w") as f: + f.write(data) + try: + check_compressed_input(data, fn, "bz2") + except NotImplementedError as e: + pytest.skip(str(e)) + + +@pytest.mark.gzip +def test_compressed_input_openfile(tmpdir): + if not Codec.is_available("gzip"): + pytest.skip("gzip support is not built") + + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "test_compressed_input_openfile.gz") + with gzip.open(fn, "wb") as f: + f.write(data) + + with pa.CompressedInputStream(fn, "gzip") as compressed: + buf = compressed.read_buffer() + assert buf.to_pybytes() == data + assert compressed.closed + + with pa.CompressedInputStream(pathlib.Path(fn), "gzip") as compressed: + buf = compressed.read_buffer() + assert buf.to_pybytes() == data + assert compressed.closed + + f = open(fn, "rb") + with pa.CompressedInputStream(f, "gzip") as compressed: + buf = compressed.read_buffer() + assert buf.to_pybytes() == data + assert f.closed + + +def check_compressed_concatenated(data, fn, compression): + raw = pa.OSFile(fn, mode="rb") + with pa.CompressedInputStream(raw, compression) as compressed: + got = compressed.read() + assert got == data + + +@pytest.mark.gzip +def test_compressed_concatenated_gzip(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "compressed_input_test2.gz") + with gzip.open(fn, "wb") as f: + f.write(data[:50]) + with gzip.open(fn, "ab") as f: + f.write(data[50:]) + check_compressed_concatenated(data, fn, "gzip") + + +@pytest.mark.gzip +def test_compressed_input_invalid(): + data = b"foo" * 10 + raw = pa.BufferReader(data) + with pytest.raises(ValueError): + pa.CompressedInputStream(raw, "unknown_compression") + with pytest.raises(TypeError): + pa.CompressedInputStream(raw, None) + + with pa.CompressedInputStream(raw, "gzip") as compressed: + with pytest.raises(IOError, match="zlib inflate failed"): + compressed.read() + + +def make_compressed_output(data, fn, compression): + raw = pa.BufferOutputStream() + with pa.CompressedOutputStream(raw, compression) as compressed: + assert not compressed.closed + assert not compressed.readable() + assert compressed.writable() + assert not compressed.seekable() + compressed.write(data) + assert compressed.closed + assert raw.closed + with open(fn, "wb") as f: + f.write(raw.getvalue()) + + +@pytest.mark.gzip +def test_compressed_output_gzip(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "compressed_output_test.gz") + make_compressed_output(data, fn, "gzip") + with gzip.open(fn, "rb") as f: + got = f.read() + assert got == data + + +def test_compressed_output_bz2(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + fn = str(tmpdir / "compressed_output_test.bz2") + try: + make_compressed_output(data, fn, "bz2") + except NotImplementedError as e: + pytest.skip(str(e)) + with bz2.BZ2File(fn, "r") as f: + got = f.read() + assert got == data + + +def test_output_stream_constructor(tmpdir): + if not Codec.is_available("gzip"): + pytest.skip("gzip support is not built") + with pa.CompressedOutputStream(tmpdir / "ctor.gz", "gzip") as stream: + stream.write(b"test") + with (tmpdir / "ctor2.gz").open("wb") as f: + with pa.CompressedOutputStream(f, "gzip") as stream: + stream.write(b"test") + + +@pytest.mark.parametrize(("path", "expected_compression"), [ + ("file.bz2", "bz2"), + ("file.lz4", "lz4"), + (pathlib.Path("file.gz"), "gzip"), + (pathlib.Path("path/to/file.zst"), "zstd"), +]) +def test_compression_detection(path, expected_compression): + if not Codec.is_available(expected_compression): + with pytest.raises(pa.lib.ArrowNotImplementedError): + Codec.detect(path) + else: + codec = Codec.detect(path) + assert isinstance(codec, Codec) + assert codec.name == expected_compression + + +def test_unknown_compression_raises(): + with pytest.raises(ValueError): + Codec.is_available('unknown') + with pytest.raises(TypeError): + Codec(None) + with pytest.raises(ValueError): + Codec('unknown') + + +@pytest.mark.parametrize("compression", [ + "bz2", + "brotli", + "gzip", + "lz4", + "zstd", + pytest.param( + "snappy", + marks=pytest.mark.xfail(raises=pa.lib.ArrowNotImplementedError) + ) +]) +def test_compressed_roundtrip(compression): + if not Codec.is_available(compression): + pytest.skip("{} support is not built".format(compression)) + + data = b"some test data\n" * 10 + b"eof\n" + raw = pa.BufferOutputStream() + with pa.CompressedOutputStream(raw, compression) as compressed: + compressed.write(data) + + cdata = raw.getvalue() + assert len(cdata) < len(data) + raw = pa.BufferReader(cdata) + with pa.CompressedInputStream(raw, compression) as compressed: + got = compressed.read() + assert got == data + + +@pytest.mark.parametrize( + "compression", + ["bz2", "brotli", "gzip", "lz4", "zstd"] +) +def test_compressed_recordbatch_stream(compression): + if not Codec.is_available(compression): + pytest.skip("{} support is not built".format(compression)) + + # ARROW-4836: roundtrip a RecordBatch through a compressed stream + table = pa.Table.from_arrays([pa.array([1, 2, 3, 4, 5])], ['a']) + raw = pa.BufferOutputStream() + stream = pa.CompressedOutputStream(raw, compression) + writer = pa.RecordBatchStreamWriter(stream, table.schema) + writer.write_table(table, max_chunksize=3) + writer.close() + stream.close() # Flush data + buf = raw.getvalue() + stream = pa.CompressedInputStream(pa.BufferReader(buf), compression) + got_table = pa.RecordBatchStreamReader(stream).read_all() + assert got_table == table + + +# ---------------------------------------------------------------------- +# Transform input streams + +unicode_transcoding_example = ( + "Dès Noël où un zéphyr haï me vêt de glaçons würmiens " + "je dîne d’exquis rôtis de bœuf au kir à l’aÿ d’âge mûr & cætera !" +) + + +def check_transcoding(data, src_encoding, dest_encoding, chunk_sizes): + chunk_sizes = iter(chunk_sizes) + stream = pa.transcoding_input_stream( + pa.BufferReader(data.encode(src_encoding)), + src_encoding, dest_encoding) + out = [] + while True: + buf = stream.read(next(chunk_sizes)) + out.append(buf) + if not buf: + break + out = b''.join(out) + assert out.decode(dest_encoding) == data + + +@pytest.mark.parametrize('src_encoding, dest_encoding', + [('utf-8', 'utf-16'), + ('utf-16', 'utf-8'), + ('utf-8', 'utf-32-le'), + ('utf-8', 'utf-32-be'), + ]) +def test_transcoding_input_stream(src_encoding, dest_encoding): + # All at once + check_transcoding(unicode_transcoding_example, + src_encoding, dest_encoding, [1000, 0]) + # Incremental + check_transcoding(unicode_transcoding_example, + src_encoding, dest_encoding, + itertools.cycle([1, 2, 3, 5])) + + +@pytest.mark.parametrize('src_encoding, dest_encoding', + [('utf-8', 'utf-8'), + ('utf-8', 'UTF8')]) +def test_transcoding_no_ops(src_encoding, dest_encoding): + # No indirection is wasted when a trivial transcoding is requested + stream = pa.BufferReader(b"abc123") + assert pa.transcoding_input_stream( + stream, src_encoding, dest_encoding) is stream + + +@pytest.mark.parametrize('src_encoding, dest_encoding', + [('utf-8', 'ascii'), + ('utf-8', 'latin-1'), + ]) +def test_transcoding_encoding_error(src_encoding, dest_encoding): + # Character \u0100 cannot be represented in the destination encoding + stream = pa.transcoding_input_stream( + pa.BufferReader("\u0100".encode(src_encoding)), + src_encoding, + dest_encoding) + with pytest.raises(UnicodeEncodeError): + stream.read(1) + + +@pytest.mark.parametrize('src_encoding, dest_encoding', + [('utf-8', 'utf-16'), + ('utf-16', 'utf-8'), + ]) +def test_transcoding_decoding_error(src_encoding, dest_encoding): + # The given bytestring is not valid in the source encoding + stream = pa.transcoding_input_stream( + pa.BufferReader(b"\xff\xff\xff\xff"), + src_encoding, + dest_encoding) + with pytest.raises(UnicodeError): + stream.read(1) + + +# ---------------------------------------------------------------------- +# High-level API + +@pytest.mark.gzip +def test_input_stream_buffer(): + data = b"some test data\n" * 10 + b"eof\n" + for arg in [pa.py_buffer(data), memoryview(data)]: + stream = pa.input_stream(arg) + assert stream.read() == data + + gz_data = gzip.compress(data) + stream = pa.input_stream(memoryview(gz_data)) + assert stream.read() == gz_data + stream = pa.input_stream(memoryview(gz_data), compression='gzip') + assert stream.read() == data + + +def test_input_stream_duck_typing(): + # Accept objects having the right file-like methods... + class DuckReader: + + def close(self): + pass + + @property + def closed(self): + return False + + def read(self, nbytes=None): + return b'hello' + + stream = pa.input_stream(DuckReader()) + assert stream.read(5) == b'hello' + + +def test_input_stream_file_path(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + file_path = tmpdir / 'input_stream' + with open(str(file_path), 'wb') as f: + f.write(data) + + stream = pa.input_stream(file_path) + assert stream.read() == data + stream = pa.input_stream(str(file_path)) + assert stream.read() == data + stream = pa.input_stream(pathlib.Path(str(file_path))) + assert stream.read() == data + + +@pytest.mark.gzip +def test_input_stream_file_path_compressed(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + gz_data = gzip.compress(data) + file_path = tmpdir / 'input_stream.gz' + with open(str(file_path), 'wb') as f: + f.write(gz_data) + + stream = pa.input_stream(file_path) + assert stream.read() == data + stream = pa.input_stream(str(file_path)) + assert stream.read() == data + stream = pa.input_stream(pathlib.Path(str(file_path))) + assert stream.read() == data + + stream = pa.input_stream(file_path, compression='gzip') + assert stream.read() == data + stream = pa.input_stream(file_path, compression=None) + assert stream.read() == gz_data + + +def test_input_stream_file_path_buffered(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + file_path = tmpdir / 'input_stream.buffered' + with open(str(file_path), 'wb') as f: + f.write(data) + + stream = pa.input_stream(file_path, buffer_size=32) + assert isinstance(stream, pa.BufferedInputStream) + assert stream.read() == data + stream = pa.input_stream(str(file_path), buffer_size=64) + assert isinstance(stream, pa.BufferedInputStream) + assert stream.read() == data + stream = pa.input_stream(pathlib.Path(str(file_path)), buffer_size=1024) + assert isinstance(stream, pa.BufferedInputStream) + assert stream.read() == data + + unbuffered_stream = pa.input_stream(file_path, buffer_size=0) + assert isinstance(unbuffered_stream, pa.OSFile) + + msg = 'Buffer size must be larger than zero' + with pytest.raises(ValueError, match=msg): + pa.input_stream(file_path, buffer_size=-1) + with pytest.raises(TypeError): + pa.input_stream(file_path, buffer_size='million') + + +@pytest.mark.gzip +def test_input_stream_file_path_compressed_and_buffered(tmpdir): + data = b"some test data\n" * 100 + b"eof\n" + gz_data = gzip.compress(data) + file_path = tmpdir / 'input_stream_compressed_and_buffered.gz' + with open(str(file_path), 'wb') as f: + f.write(gz_data) + + stream = pa.input_stream(file_path, buffer_size=32, compression='gzip') + assert stream.read() == data + stream = pa.input_stream(str(file_path), buffer_size=64) + assert stream.read() == data + stream = pa.input_stream(pathlib.Path(str(file_path)), buffer_size=1024) + assert stream.read() == data + + +@pytest.mark.gzip +def test_input_stream_python_file(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + bio = BytesIO(data) + + stream = pa.input_stream(bio) + assert stream.read() == data + + gz_data = gzip.compress(data) + bio = BytesIO(gz_data) + stream = pa.input_stream(bio) + assert stream.read() == gz_data + bio.seek(0) + stream = pa.input_stream(bio, compression='gzip') + assert stream.read() == data + + file_path = tmpdir / 'input_stream' + with open(str(file_path), 'wb') as f: + f.write(data) + with open(str(file_path), 'rb') as f: + stream = pa.input_stream(f) + assert stream.read() == data + + +@pytest.mark.gzip +def test_input_stream_native_file(): + data = b"some test data\n" * 10 + b"eof\n" + gz_data = gzip.compress(data) + reader = pa.BufferReader(gz_data) + stream = pa.input_stream(reader) + assert stream is reader + reader = pa.BufferReader(gz_data) + stream = pa.input_stream(reader, compression='gzip') + assert stream.read() == data + + +def test_input_stream_errors(tmpdir): + buf = memoryview(b"") + with pytest.raises(ValueError): + pa.input_stream(buf, compression="foo") + + for arg in [bytearray(), StringIO()]: + with pytest.raises(TypeError): + pa.input_stream(arg) + + with assert_file_not_found(): + pa.input_stream("non_existent_file") + + with open(str(tmpdir / 'new_file'), 'wb') as f: + with pytest.raises(TypeError, match="readable file expected"): + pa.input_stream(f) + + +def test_output_stream_buffer(): + data = b"some test data\n" * 10 + b"eof\n" + buf = bytearray(len(data)) + stream = pa.output_stream(pa.py_buffer(buf)) + stream.write(data) + assert buf == data + + buf = bytearray(len(data)) + stream = pa.output_stream(memoryview(buf)) + stream.write(data) + assert buf == data + + +def test_output_stream_duck_typing(): + # Accept objects having the right file-like methods... + class DuckWriter: + def __init__(self): + self.buf = pa.BufferOutputStream() + + def close(self): + pass + + @property + def closed(self): + return False + + def write(self, data): + self.buf.write(data) + + duck_writer = DuckWriter() + stream = pa.output_stream(duck_writer) + assert stream.write(b'hello') + assert duck_writer.buf.getvalue().to_pybytes() == b'hello' + + +def test_output_stream_file_path(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + file_path = tmpdir / 'output_stream' + + def check_data(file_path, data): + with pa.output_stream(file_path) as stream: + stream.write(data) + with open(str(file_path), 'rb') as f: + assert f.read() == data + + check_data(file_path, data) + check_data(str(file_path), data) + check_data(pathlib.Path(str(file_path)), data) + + +@pytest.mark.gzip +def test_output_stream_file_path_compressed(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + file_path = tmpdir / 'output_stream.gz' + + def check_data(file_path, data, **kwargs): + with pa.output_stream(file_path, **kwargs) as stream: + stream.write(data) + with open(str(file_path), 'rb') as f: + return f.read() + + assert gzip.decompress(check_data(file_path, data)) == data + assert gzip.decompress(check_data(str(file_path), data)) == data + assert gzip.decompress( + check_data(pathlib.Path(str(file_path)), data)) == data + + assert gzip.decompress( + check_data(file_path, data, compression='gzip')) == data + assert check_data(file_path, data, compression=None) == data + + with pytest.raises(ValueError, match='Invalid value for compression'): + assert check_data(file_path, data, compression='rabbit') == data + + +def test_output_stream_file_path_buffered(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + file_path = tmpdir / 'output_stream.buffered' + + def check_data(file_path, data, **kwargs): + with pa.output_stream(file_path, **kwargs) as stream: + if kwargs.get('buffer_size', 0) > 0: + assert isinstance(stream, pa.BufferedOutputStream) + stream.write(data) + with open(str(file_path), 'rb') as f: + return f.read() + + unbuffered_stream = pa.output_stream(file_path, buffer_size=0) + assert isinstance(unbuffered_stream, pa.OSFile) + + msg = 'Buffer size must be larger than zero' + with pytest.raises(ValueError, match=msg): + assert check_data(file_path, data, buffer_size=-128) == data + + assert check_data(file_path, data, buffer_size=32) == data + assert check_data(file_path, data, buffer_size=1024) == data + assert check_data(str(file_path), data, buffer_size=32) == data + + result = check_data(pathlib.Path(str(file_path)), data, buffer_size=32) + assert result == data + + +@pytest.mark.gzip +def test_output_stream_file_path_compressed_and_buffered(tmpdir): + data = b"some test data\n" * 100 + b"eof\n" + file_path = tmpdir / 'output_stream_compressed_and_buffered.gz' + + def check_data(file_path, data, **kwargs): + with pa.output_stream(file_path, **kwargs) as stream: + stream.write(data) + with open(str(file_path), 'rb') as f: + return f.read() + + result = check_data(file_path, data, buffer_size=32) + assert gzip.decompress(result) == data + + result = check_data(file_path, data, buffer_size=1024) + assert gzip.decompress(result) == data + + result = check_data(file_path, data, buffer_size=1024, compression='gzip') + assert gzip.decompress(result) == data + + +def test_output_stream_destructor(tmpdir): + # The wrapper returned by pa.output_stream() should respect Python + # file semantics, i.e. destroying it should close the underlying + # file cleanly. + data = b"some test data\n" + file_path = tmpdir / 'output_stream.buffered' + + def check_data(file_path, data, **kwargs): + stream = pa.output_stream(file_path, **kwargs) + stream.write(data) + del stream + gc.collect() + with open(str(file_path), 'rb') as f: + return f.read() + + assert check_data(file_path, data, buffer_size=0) == data + assert check_data(file_path, data, buffer_size=1024) == data + + +@pytest.mark.gzip +def test_output_stream_python_file(tmpdir): + data = b"some test data\n" * 10 + b"eof\n" + + def check_data(data, **kwargs): + # XXX cannot use BytesIO because stream.close() is necessary + # to finish writing compressed data, but it will also close the + # underlying BytesIO + fn = str(tmpdir / 'output_stream_file') + with open(fn, 'wb') as f: + with pa.output_stream(f, **kwargs) as stream: + stream.write(data) + with open(fn, 'rb') as f: + return f.read() + + assert check_data(data) == data + assert gzip.decompress(check_data(data, compression='gzip')) == data + + +def test_output_stream_errors(tmpdir): + buf = memoryview(bytearray()) + with pytest.raises(ValueError): + pa.output_stream(buf, compression="foo") + + for arg in [bytearray(), StringIO()]: + with pytest.raises(TypeError): + pa.output_stream(arg) + + fn = str(tmpdir / 'new_file') + with open(fn, 'wb') as f: + pass + with open(fn, 'rb') as f: + with pytest.raises(TypeError, match="writable file expected"): + pa.output_stream(f)